Compare commits

...

90 Commits

Author SHA1 Message Date
Louis Erbkamm
daf07bd743 Merge pull request #316 from louis-e/prepare-release-fmt
Handle block properties in new saving logic
2025-01-21 23:36:26 +01:00
louis-e
163ab0407d Handle block properties in new saving logic 2025-01-21 23:36:04 +01:00
Louis Erbkamm
0361e7d63d Merge pull request #315 from louis-e/prepare-release
Prepare release
2025-01-21 23:33:02 +01:00
louis-e
bc422460ff Handle block properties in new saving logic 2025-01-21 23:28:55 +01:00
louis-e
53f0097884 Prepare Alpine Release 2025-01-21 23:28:04 +01:00
Louis Erbkamm
bbfb63886d Update README.md 2025-01-21 22:37:38 +01:00
Louis Erbkamm
928f487a29 Merge pull request #260 from austenadler/feature/allow-disabling-gui
Allow disabling gui at compile time
2025-01-21 22:34:57 +01:00
Louis Erbkamm
ff7a09061e Merge branch 'main' into feature/allow-disabling-gui 2025-01-21 22:13:27 +01:00
Louis Erbkamm
911ec00ddb Merge pull request #312 from louis-e/minor-tweaks
Minor tweaks
2025-01-21 20:47:28 +01:00
louis-e
54137f2117 Updated README 2025-01-21 20:46:53 +01:00
louis-e
50d38a1dd4 Localization formatting changes 2025-01-21 20:44:08 +01:00
louis-e
e5ab62eb18 Added comments for better documentation 2025-01-21 20:36:39 +01:00
Louis Erbkamm
1a8a3114f4 Merge pull request #299 from HelleBenjamin/main
Add Finnish translation
2025-01-21 20:31:58 +01:00
Louis Erbkamm
a52ba2bd39 Merge pull request #289 from TheComputerGuy96/klaipeda
Translation support rework
2025-01-21 20:30:34 +01:00
Benjamin Helle
8195f0bc6e Merge branch 'main' into main 2025-01-21 16:49:03 +02:00
Louis Erbkamm
4df4a3de32 Merge pull request #306 from wielandb/main
Add "razed" to values of railway=* not rendered
2025-01-20 23:50:07 +01:00
Louis Erbkamm
e65a1ee37e Merge branch 'main' into main 2025-01-20 23:47:10 +01:00
Louis Erbkamm
66e47e190a Merge branch 'main' into klaipeda 2025-01-20 23:46:22 +01:00
Louis Erbkamm
8755fd3285 Merge pull request #308 from louis-e/elevation-wip
Merge Elevation feature
2025-01-20 23:44:28 +01:00
louis-e
982ef56b29 Fix chunk in wrong location issue with unfinished region patch 2025-01-20 23:13:44 +01:00
louis-e
28070d3c51 Fix chunk in wrong location issue with unfinished region patch 2025-01-20 23:03:57 +01:00
louis-e
d9a0a4aa86 CI (fmt): Fix formatting 2025-01-20 22:45:02 +01:00
louis-e
1f0f6676ed Added railway orientation blocks 2025-01-20 21:28:00 +01:00
louis-e
ff44fe4eda Adapted update messages 2025-01-20 21:27:37 +01:00
louis-e
42976b0113 Fixed railway orientation 2025-01-20 21:27:07 +01:00
louis-e
55b170fb7d TODO Edits 2025-01-20 21:26:54 +01:00
louis-e
852bbf2236 Added self signed signature to Windows release and added Mac release 2025-01-20 21:24:07 +01:00
louis-e
cc6080c0c3 Adapt aeroways to new elevation logic 2025-01-20 20:17:44 +01:00
louis-e
5672ca3f1e Update player rotation in world generation and minor tweaks 2025-01-20 20:00:00 +01:00
Wieland
fc29544835 Fix indentation 2025-01-19 03:35:13 +01:00
Wieland
bf6ac1f61a Add "turntable" to values that should not be rendered 2025-01-19 03:32:13 +01:00
louis-e
8c17a5b0bb Modify player position for world generation 2025-01-19 02:53:37 +01:00
Wieland
bc6ffa3bf9 Change formatting 2025-01-19 02:22:58 +01:00
louis-e
dec0317790 Implement fixes for elevation 2025-01-19 01:46:58 +01:00
louis-e
091acd5849 Added dynamic year in license 2025-01-19 01:46:37 +01:00
Wieland
056203fb21 Add "razed" to values of railway=* not rendered 2025-01-19 01:41:28 +01:00
louis-e
415c9d33fe Bresenham algorithm optimization 2025-01-19 00:14:23 +01:00
louis-e
1820112093 CI (fmt) fix: Merge main into elevation-wip 2025-01-19 00:08:26 +01:00
louis-e
c573a02fd6 Optimized cartesian 2025-01-18 23:52:08 +01:00
louis-e
4c6b9833eb Optimized bresenham algorithm performance 2025-01-18 23:51:41 +01:00
louis-e
8cb8d76357 Set terrain toggle to not-default on 2025-01-18 23:51:17 +01:00
louis-e
fc105b84e0 Merge main into elevation-wip 2025-01-18 21:23:53 +01:00
louis-e
f873a7ab69 Merge branch 'main' into elevation-wip 2025-01-18 18:43:03 +01:00
louis-e
61a67240a6 WIP: Save changes before merging main 2025-01-18 18:35:39 +01:00
Austen Adler
c0753ab23e Format with consistent style 2025-01-16 22:41:53 -05:00
Austen Adler
9461d1f46e Merge remote-tracking branch 'origin/main' into feature/allow-disabling-gui 2025-01-16 22:41:22 -05:00
Austen Adler
3036237fdf Free and reattach to console when running on Windows 2025-01-16 22:31:32 -05:00
Benjamin Helle
95e71b8da5 Added finnish language json 2025-01-17 00:57:53 +02:00
Echo J
255786bc93 Add Lithuanian translation
This may be strange in some places though
2025-01-15 16:44:13 +02:00
Echo J
3c552fe5ed Make placeholder strings translatable (and license one too)
There's some strings coming from the Rust side though (which
will require extra code work)
2025-01-15 16:44:13 +02:00
Echo J
49ff415316 Use localization helper function for JS-based HTML elements 2025-01-15 16:44:13 +02:00
Echo J
71315c60ea Rework applyLocalization() function
This removes all of the boilerplate for setting strings (now the
strings are set by looping through an object and calling a helper function)

The helper function also has an English string fallback if a translation
doesn't have one

And finally some functions/.html code were adjusted to simplify the localization
helper function (this also means innerHTML is no longer used for safety)
2025-01-15 16:44:11 +02:00
Echo J
18b1ea0e0b Don't hardcode language codes
This will make adding a new translation a bit easier (this change
also accepts full codes for language variations like en-UK or pt-BR)

Also specify a full code for English and Chinese translations (Chinese
variation was found with a translation tool's language detector so
it might not be accurate)
2025-01-15 16:43:23 +02:00
Echo J
c6a8da0b40 Remove unused translation strings
These 2 strings are a duplicate of existing ones (which should
reduce translation boilerplate a bit)
2025-01-15 16:43:23 +02:00
Louis Erbkamm
308498550b Merge pull request #290 from TheComputerGuy96/misc-fixes
Miscellaneous fixes
2025-01-15 14:35:16 +01:00
Louis Erbkamm
f7e917edc7 Merge pull request #286 from RedAuburn/better-fences
Support barrier / fence types
2025-01-15 14:32:09 +01:00
Echo J
8221da46e0 Add a NVIDIA WebKit workaround 2025-01-14 21:30:19 +02:00
Echo J
3645b7edd7 Fix wrong variable in an error handler 2025-01-14 21:01:17 +02:00
Echo J
606779f681 Set a border CSS property for buttons/input boxes
For some reason the background color isn't applied on input boxes
(only on WebKit) if I don't set this
2025-01-14 20:43:56 +02:00
Echo J
dce5f472f0 Make the GUI partially work in a web browser
The lack of window.__TAURI__ object prevents most of the JS code
from running (this change stubs it which allows the Tauri GUI to
be tested in a web browser with a simple web server like PHP's one)
2025-01-14 20:39:08 +02:00
Harry Bond
f4bf8c1d3c Support barrier / fence types 2025-01-13 22:22:28 +00:00
louis-e
686ac2c181 Fix rebasing issues 2025-01-12 22:45:50 +01:00
Louis Erbkamm
b334ed9841 Merge pull request #280 from krvstek/main
simplification & fixes for Polish
2025-01-12 22:26:27 +01:00
louis-e
96dc9ced30 Merge branch 'main' into elevation-wip 2025-01-12 22:23:22 +01:00
krvstek.
03d86f4552 simplification & fixes for Polish 2025-01-12 21:03:15 +00:00
Louis Erbkamm
6e3406f117 Merge pull request #276 from zer0-dev/russia_overpass_workaround
Add fallback api urls specifically for Russia
2025-01-12 20:05:16 +01:00
zer0-dev
7e929d5ef3 Add fallback api urls specifically for Russia 2025-01-12 21:27:18 +03:00
Louis Erbkamm
49a5ed8157 Merge pull request #272 from louis-e/park-relation-fix
Park relation fix and faster saving
2025-01-12 18:01:05 +01:00
louis-e
f60170ef59 CI (fmt) fix: Fixed leisure generation for multipolygons 2025-01-12 17:50:13 +01:00
louis-e
b34bf4f646 CI (fmt) fix: Fixed leisure generation for multipolygons 2025-01-12 17:46:56 +01:00
Austen Adler
efc14821cf Remove note about running with no-default-features 2025-01-12 11:46:30 -05:00
louis-e
ba9c7df5ff Merge branch 'main' into park-relation-fix 2025-01-12 17:41:16 +01:00
louis-e
3eb29a0c21 Fixed leisure generation for multipolygons 2025-01-12 17:38:51 +01:00
louis-e
17ead3c2fc Fixed leisure generation for multipolygons 2025-01-12 17:37:30 +01:00
louis-e
f661f174bd Optimize world save with parallel chunks & buffer reuse 2025-01-12 17:15:09 +01:00
louis-e
7792930277 Optimize world save with parallel chunks & buffer reuse 2025-01-12 17:05:45 +01:00
louis-e
18d3e45d2c Optimize world save with parallel chunks & buffer reuse 2025-01-12 17:05:32 +01:00
Louis Erbkamm
c2b9f87688 Update bug_report.md 2025-01-12 16:39:20 +01:00
Louis Erbkamm
0850bca4de Update prerelease.yml 2025-01-12 16:32:31 +01:00
Louis Erbkamm
3e88da384a Merge branch 'main' into feature/allow-disabling-gui 2025-01-11 16:53:11 +01:00
Austen Adler
ab21b88c90 Allow disabling gui 2025-01-10 22:49:40 -05:00
louis-e
ac8c5bf466 Enabled terrain by default 2025-01-06 23:13:48 +01:00
louis-e
e4c6208b22 Added elevation as settings feature 2025-01-06 23:12:42 +01:00
louis-e
f5144d7ba4 Added terrain logic to other element processors 2025-01-06 22:23:42 +01:00
louis-e
f50e10891b Patched all remaining element processors to new elevation logic (except for bridges) 2025-01-06 20:13:31 +01:00
Louis Erbkamm
66819a577b Merge pull request #209 from louis-e/main
Bring elevation-wip up to date to main code base
2025-01-06 17:53:51 +01:00
louis-e
c0778c265f Resolved merge conflicts between elevation-wip and main 2025-01-06 02:00:49 +01:00
Stephen D
c9c0cb2f2c rivers 2024-10-24 19:24:40 -03:00
Stephen D
18de6ec808 very beginnings of elevation. Using a sinewave map and not everything has been moved onto the surface yet. Also, some things need better logic when placed on the surface (buildings go underground a bit) 2024-10-24 19:24:39 -03:00
Stephen D
9f521489ab raise up world 2024-10-23 22:07:53 -03:00
48 changed files with 2737 additions and 1082 deletions

View File

@@ -20,4 +20,4 @@ Please tell us what version of Arnis and Minecraft you used.
If applicable, add screenshots to help explain your problem.
**Additional context**
Add any other context about the problem here. If you used any more custom settings, please provide them here too.
Add any other context about the problem here. If you used any more custom settings, please provide them here too. If you experienced any issue with the application itself like a crash, please provide the log file which can be found at C:\Users\USERNAME\AppData\Local\com.louisdev.arnis\logs

View File

@@ -1,4 +1,4 @@
name: Pre-release Dev Build
name: [DISABLED] Pre-release Dev Build
on:
push:
@@ -80,8 +80,8 @@ jobs:
uses: ncipollo/release-action@v1
with:
tag: "dev-build-${{ github.run_number }}"
name: "Dev Build #${{ github.run_number }}"
body: "Automated pre-release for testing purposes. This build may contain experimental features. For the latest official version, please download the latest stable release."
name: "Experimental Development Build #${{ github.run_number }}"
body: "Automated pre-release built from the main branch for testing purposes. This build may contain experimental features. For the latest official version, please download the latest stable release."
draft: false
prerelease: true
makeLatest: false

View File

@@ -12,11 +12,15 @@ jobs:
- os: windows-latest
target: x86_64-pc-windows-msvc
binary_name: arnis.exe
asset_name: arnis-windows-x64.exe
asset_name: arnis-windows.exe
- os: ubuntu-latest
target: x86_64-unknown-linux-gnu
binary_name: arnis
asset_name: arnis-linux-x64
asset_name: arnis-linux
- os: macos-latest
target: x86_64-apple-darwin
binary_name: arnis
asset_name: arnis-mac
runs-on: ${{ matrix.os }}
@@ -47,11 +51,42 @@ jobs:
- name: Build
run: cargo build --release
- name: Rename binary for release
run: mv target/release/${{ matrix.binary_name }} target/release/${{ matrix.asset_name }}
- name: Install Windows SDK
if: matrix.os == 'windows-latest'
run: |
choco install windows-sdk-10.1 -y
$env:Path += ";C:\Program Files (x86)\Windows Kits\10\bin\x64"
shell: powershell
- name: Locate signtool.exe
if: matrix.os == 'windows-latest'
id: locate_signtool
run: |
$env:ProgramFilesX86 = [System.Environment]::GetFolderPath('ProgramFilesX86')
$signtoolPath = Get-ChildItem -Path "$env:ProgramFilesX86\Windows Kits\10\bin" -Recurse -Filter signtool.exe | Where-Object { $_.FullName -match '\\x64\\' } | Select-Object -First 1 -ExpandProperty FullName
if (-not $signtoolPath) { throw "signtool.exe not found." }
echo "signtool=$signtoolPath" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
shell: powershell
- name: Self-sign Windows executable
if: matrix.os == 'windows-latest'
run: |
$password = ConvertTo-SecureString -String $env:WINDOWS_CERT_PASSWORD -Force -AsPlainText
$cert = New-SelfSignedCertificate -Type CodeSigningCert -Subject 'CN=Arnis' -CertStoreLocation Cert:\CurrentUser\My -NotAfter (Get-Date).AddYears(5)
Export-PfxCertificate -Cert $cert -FilePath arnis-cert.pfx -Password $password
& $env:signtool sign /f arnis-cert.pfx /p $env:WINDOWS_CERT_PASSWORD /t http://timestamp.digicert.com target/release/${{ matrix.asset_name }}
env:
WINDOWS_CERT_PASSWORD: ${{ secrets.WINDOWS_CERT_PASSWORD }}
shell: powershell
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
name: ${{ matrix.os }}-build
path: target/release/${{ matrix.binary_name }}
path: target/release/${{ matrix.asset_name }}
release:
needs: build
@@ -72,14 +107,23 @@ jobs:
name: ubuntu-latest-build
path: ./builds/linux
- name: Make Linux binary executable
run: chmod +x ./builds/linux/arnis
- name: Download macOS build artifact
uses: actions/download-artifact@v3
with:
name: macos-latest-build
path: ./builds/macos
- name: Make Linux and macOS binaries executable
run: |
chmod +x ./builds/linux/arnis-linux
chmod +x ./builds/macos/arnis-mac
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
with:
files: |
builds/windows/arnis.exe
builds/linux/arnis
builds/windows/arnis-windows.exe
builds/linux/arnis-linux
builds/macos/arnis-mac
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}

1
.gitignore vendored
View File

@@ -27,6 +27,7 @@ Thumbs.db
# Generated files
/export.json
/parsed_osm_data.txt
/elevation_debug.png
/gen/
/build/
*.rmeta

277
Cargo.lock generated
View File

@@ -168,7 +168,7 @@ dependencies = [
[[package]]
name = "arnis"
version = "2.1.3"
version = "2.2.0"
dependencies = [
"clap",
"colored",
@@ -179,11 +179,13 @@ dependencies = [
"fnv",
"fs2",
"geo",
"image 0.24.9",
"indicatif",
"itertools 0.14.0",
"log",
"once_cell",
"rand 0.8.5",
"rayon",
"reqwest",
"rfd",
"semver",
@@ -194,6 +196,7 @@ dependencies = [
"tauri-plugin-log",
"tauri-plugin-shell",
"tokio",
"windows 0.59.0",
]
[[package]]
@@ -984,6 +987,12 @@ version = "0.8.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]]
name = "crunchy"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7"
[[package]]
name = "crypto-common"
version = "0.1.6"
@@ -1346,6 +1355,21 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "exr"
version = "1.73.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83197f59927b46c04a183a619b7c29df34e63e63c7869320862268c0ef687e0"
dependencies = [
"bit_field",
"half",
"lebe",
"miniz_oxide",
"rayon-core",
"smallvec",
"zune-inflate",
]
[[package]]
name = "fastanvil"
version = "0.31.0"
@@ -1356,7 +1380,7 @@ dependencies = [
"byteorder",
"fastnbt",
"flate2",
"image",
"image 0.23.14",
"log",
"num_enum 0.5.11",
"once_cell",
@@ -1788,6 +1812,16 @@ dependencies = [
"wasi 0.11.0+wasi-snapshot-preview1",
]
[[package]]
name = "gif"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fb2d69b19215e18bb912fa30f7ce15846e301408695e44e0ef719f1da9e19f2"
dependencies = [
"color_quant",
"weezl",
]
[[package]]
name = "gimli"
version = "0.31.1"
@@ -1961,6 +1995,16 @@ dependencies = [
"tracing",
]
[[package]]
name = "half"
version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dd08c532ae367adf81c312a4580bc67f1d0fe8bc9c460520283f4c0ff277888"
dependencies = [
"cfg-if",
"crunchy",
]
[[package]]
name = "hash32"
version = "0.3.1"
@@ -2391,6 +2435,24 @@ dependencies = [
"num-traits",
]
[[package]]
name = "image"
version = "0.24.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5690139d2f55868e080017335e4b94cb7414274c74f1669c84fb5feba2c9f69d"
dependencies = [
"bytemuck",
"byteorder",
"color_quant",
"exr",
"gif",
"jpeg-decoder",
"num-traits",
"png",
"qoi",
"tiff",
]
[[package]]
name = "indexmap"
version = "1.9.3"
@@ -2541,6 +2603,15 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
[[package]]
name = "jpeg-decoder"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5d4a7da358eff58addd2877a45865158f0d78c911d43a5784ceb7bbf52833b0"
dependencies = [
"rayon",
]
[[package]]
name = "js-sys"
version = "0.3.76"
@@ -2603,6 +2674,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "lebe"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03087c2bad5e1034e8cace5926dec053fb3790248370865f5117a7d0213354c8"
[[package]]
name = "libappindicator"
version = "0.9.0"
@@ -3689,6 +3766,15 @@ dependencies = [
"syn 1.0.109",
]
[[package]]
name = "qoi"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
dependencies = [
"bytemuck",
]
[[package]]
name = "quick-xml"
version = "0.32.0"
@@ -4694,7 +4780,7 @@ dependencies = [
"tao-macros",
"unicode-segmentation",
"url",
"windows",
"windows 0.58.0",
"windows-core 0.58.0",
"windows-version",
"x11-dl",
@@ -4780,7 +4866,7 @@ dependencies = [
"webkit2gtk",
"webview2-com",
"window-vibrancy",
"windows",
"windows 0.58.0",
]
[[package]]
@@ -4922,7 +5008,7 @@ dependencies = [
"tauri-utils",
"thiserror 2.0.9",
"url",
"windows",
"windows 0.58.0",
]
[[package]]
@@ -4947,7 +5033,7 @@ dependencies = [
"url",
"webkit2gtk",
"webview2-com",
"windows",
"windows 0.58.0",
"wry",
]
@@ -5069,6 +5155,17 @@ dependencies = [
"syn 2.0.95",
]
[[package]]
name = "tiff"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba1310fcea54c6a9a4fd1aad794ecc02c31682f6bfbecdf460bf19533eed1e3e"
dependencies = [
"flate2",
"jpeg-decoder",
"weezl",
]
[[package]]
name = "time"
version = "0.3.37"
@@ -5789,10 +5886,10 @@ checksum = "823e7ebcfaea51e78f72c87fc3b65a1e602c321f407a0b36dbb327d7bb7cd921"
dependencies = [
"webview2-com-macros",
"webview2-com-sys",
"windows",
"windows 0.58.0",
"windows-core 0.58.0",
"windows-implement",
"windows-interface",
"windows-implement 0.58.0",
"windows-interface 0.58.0",
]
[[package]]
@@ -5813,10 +5910,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a82bce72db6e5ee83c68b5de1e2cd6ea195b9fbff91cb37df5884cbe3222df4"
dependencies = [
"thiserror 1.0.69",
"windows",
"windows 0.58.0",
"windows-core 0.58.0",
]
[[package]]
name = "weezl"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53a85b86a771b1c87058196170769dd264f66c0782acf1ae6cc51bfd64b39082"
[[package]]
name = "winapi"
version = "0.3.9"
@@ -5872,6 +5975,16 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f919aee0a93304be7f62e8e5027811bbba96bcb1de84d6618be56e43f8a32a1"
dependencies = [
"windows-core 0.59.0",
"windows-targets 0.53.0",
]
[[package]]
name = "windows-core"
version = "0.52.0"
@@ -5887,13 +6000,26 @@ version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
dependencies = [
"windows-implement",
"windows-interface",
"windows-result",
"windows-strings",
"windows-implement 0.58.0",
"windows-interface 0.58.0",
"windows-result 0.2.0",
"windows-strings 0.1.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "810ce18ed2112484b0d4e15d022e5f598113e220c53e373fb31e67e21670c1ce"
dependencies = [
"windows-implement 0.59.0",
"windows-interface 0.59.0",
"windows-result 0.3.0",
"windows-strings 0.3.0",
"windows-targets 0.53.0",
]
[[package]]
name = "windows-implement"
version = "0.58.0"
@@ -5905,6 +6031,17 @@ dependencies = [
"syn 2.0.95",
]
[[package]]
name = "windows-implement"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83577b051e2f49a058c308f17f273b570a6a758386fc291b5f6a934dd84e48c1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.95",
]
[[package]]
name = "windows-interface"
version = "0.58.0"
@@ -5916,14 +6053,25 @@ dependencies = [
"syn 2.0.95",
]
[[package]]
name = "windows-interface"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb26fd936d991781ea39e87c3a27285081e3c0da5ca0fcbc02d368cc6f52ff01"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.95",
]
[[package]]
name = "windows-registry"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e400001bb720a623c1c69032f8e3e4cf09984deec740f007dd2b03ec864804b0"
dependencies = [
"windows-result",
"windows-strings",
"windows-result 0.2.0",
"windows-strings 0.1.0",
"windows-targets 0.52.6",
]
@@ -5936,16 +6084,34 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-result"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d08106ce80268c4067c0571ca55a9b4e9516518eaa1a1fe9b37ca403ae1d1a34"
dependencies = [
"windows-targets 0.53.0",
]
[[package]]
name = "windows-strings"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"
dependencies = [
"windows-result",
"windows-result 0.2.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-strings"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b888f919960b42ea4e11c2f408fadb55f78a9f236d5eef084103c8ce52893491"
dependencies = [
"windows-targets 0.53.0",
]
[[package]]
name = "windows-sys"
version = "0.45.0"
@@ -6021,13 +6187,29 @@ dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm",
"windows_i686_gnullvm 0.52.6",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
name = "windows-targets"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1e4c7e8ceaaf9cb7d7507c974735728ab453b67ef8f18febdd7c11fe59dca8b"
dependencies = [
"windows_aarch64_gnullvm 0.53.0",
"windows_aarch64_msvc 0.53.0",
"windows_i686_gnu 0.53.0",
"windows_i686_gnullvm 0.53.0",
"windows_i686_msvc 0.53.0",
"windows_x86_64_gnu 0.53.0",
"windows_x86_64_gnullvm 0.53.0",
"windows_x86_64_msvc 0.53.0",
]
[[package]]
name = "windows-version"
version = "0.1.1"
@@ -6055,6 +6237,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.2"
@@ -6073,6 +6261,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_aarch64_msvc"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c"
[[package]]
name = "windows_i686_gnu"
version = "0.42.2"
@@ -6091,12 +6285,24 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnu"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_gnullvm"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11"
[[package]]
name = "windows_i686_msvc"
version = "0.42.2"
@@ -6115,6 +6321,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_i686_msvc"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.2"
@@ -6133,6 +6345,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnu"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.2"
@@ -6151,6 +6369,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.2"
@@ -6169,6 +6393,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "windows_x86_64_msvc"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
[[package]]
name = "winnow"
version = "0.5.40"
@@ -6246,7 +6476,7 @@ dependencies = [
"webkit2gtk",
"webkit2gtk-sys",
"webview2-com",
"windows",
"windows 0.58.0",
"windows-core 0.58.0",
"windows-version",
"x11-dl",
@@ -6449,6 +6679,15 @@ dependencies = [
"syn 2.0.95",
]
[[package]]
name = "zune-inflate"
version = "0.2.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
dependencies = [
"simd-adler32",
]
[[package]]
name = "zvariant"
version = "5.1.0"

View File

@@ -1,6 +1,6 @@
[package]
name = "arnis"
version = "2.1.3"
version = "2.2.0"
edition = "2021"
description = "Arnis - Generate real life cities in Minecraft"
homepage = "https://github.com/louis-e/arnis"
@@ -11,6 +11,10 @@ readme = "README.md"
[profile.release]
lto = "thin"
[features]
default = ["gui"]
gui = ["dep:tauri", "dep:tauri-plugin-log", "dep:tauri-plugin-shell"]
[build-dependencies]
tauri-build = "2"
@@ -24,17 +28,22 @@ flate2 = "1.0"
fnv = "1.0.7"
fs2 = "0.4"
geo = "0.29.3"
image = "0.24"
indicatif = "0.17.8"
itertools = "0.14.0"
log = "0.4.22"
once_cell = "1.19.0"
rand = "0.8.5"
rayon = "1.10.0"
reqwest = { version = "0.12.7", features = ["blocking", "json"] }
rfd = "0.15.1"
semver = "1.0.23"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tauri = "2"
tauri-plugin-log = { version = "2.2.0" }
tauri-plugin-shell = "2"
tauri = { version = "2", optional = true }
tauri-plugin-log = { version = "2.2.0", optional = true }
tauri-plugin-shell = { version = "2", optional = true }
tokio = { version = "1.42.0", features = ["full"] }
[target.'cfg(windows)'.dependencies]
windows = { version = "0.59.0", features = ["Win32_System_Console"] }

View File

@@ -22,9 +22,10 @@ Download the [latest release](https://github.com/louis-e/arnis/releases/) or [co
Choose your area in Arnis using the rectangle tool and select your Minecraft world - then simply click on 'Start Generation'!
The world will always be generated starting from the Minecraft coordinates 0 0 0 (/tp 0 0 0). This is the top left of your selected area.
If you choose to select an own world, make sure to generate a new flat world in advance in Minecraft.
To generate your world with terrain, make sure to enable the corresponding feature in the generation settings.
Minecraft version 1.16.5 and below is currently not supported, but we are working on it! For the best results, use Minecraft version 1.21.4.
If you choose to select an own world, be aware that Arnis will overwrite certain areas.
## :floppy_disk: How it works
![CLI Generation](https://github.com/louis-e/arnis/blob/main/gitassets/cli.gif?raw=true)
@@ -43,7 +44,7 @@ The raw data obtained from the API *[(see FAQ)](#question-faq)* includes each el
- *Wasn't this written in Python before?*<br>
Yes! Arnis was initially developed in Python, which benefited from Python's open-source friendliness and ease of readability. This is why we strive for clear, well-documented code in the Rust port of this project to find the right balance. I decided to port the project to Rust to learn more about the language and push the algorithm's performance further. We were nearing the limits of optimization in Python, and Rust's capabilities allow for even better performance and efficiency. The old Python implementation is still available in the python-legacy branch.
- *Where does the data come from?*<br>
The geographic data is sourced from OpenStreetMap (OSM)[^1], a free, collaborative mapping project that serves as an open-source alternative to commercial mapping services. The data is accessed via the Overpass API, which queries OSM's database.
The geographic data is sourced from OpenStreetMap (OSM)[^1], a free, collaborative mapping project that serves as an open-source alternative to commercial mapping services. The data is accessed via the Overpass API, which queries OSM's database. Other services like Google Maps do not provide data like this, which makes OSM perfect for this project.
- *How does the Minecraft world generation work?*<br>
The script uses the [fastnbt](https://github.com/owengage/fastnbt) cargo package to interact with Minecraft's world format. This library allows Arnis to manipulate Minecraft region files, enabling the generation of real-world locations. The section 'Processing Pipeline' goes a bit further into the details and steps of the generation process itself.
- *Where does the name come from?*<br>
@@ -57,6 +58,7 @@ Please use Minecraft version 1.21.4 for the best results. Minecraft version 1.16
- *The generation did finish, but there's nothing in the world!*<br>
Make sure to teleport to the generation starting point (/tp 0 0 0). If there is still nothing, you might need to travel a bit further into the positive X and positive Z direction.
- *What features are in the world generation settings?*<br>
**Terrain:** Make sure to enable this feature to generate your world with elevation data included.<br>
**Winter Mode:** This setting changes the generation style to a snowy theme and adds snow layers to the ground.<br>
**Scale Factor:** The scale factor determines the size of the generated world.<br>
**Custom BBOX Input:** This setting allows you to manually input the bounding box coordinates for the area you want to generate.<br>
@@ -73,18 +75,18 @@ Feel free to choose an item from the To-Do or Known Bugs list, or bring your own
- [ ] Mapping real coordinates to Minecraft coordinates (https://github.com/louis-e/arnis/issues/29)
- [ ] Add interior to buildings
- [ ] Implement house roof types
- [ ] Evaluate and implement elevation (https://github.com/louis-e/arnis/issues/66)
- [ ] Add support for inner attribute in multipolygons and multipolygon elements other than buildings
- [ ] Fix Github Action Workflow for releasing MacOS Binary
- [ ] Evaluate and implement faster region saving
- [ ] Refactor bridges implementation
- [ ] Refactor railway implementation
- [ ] Better code documentation
- [ ] Refactor fountain structure implementation
- [ ] Luanti Support (https://github.com/louis-e/arnis/issues/120)
- [ ] Minecraft Bedrock Edition Support (https://github.com/louis-e/arnis/issues/148)
- [x] Evaluate and implement elevation (https://github.com/louis-e/arnis/issues/66)
- [x] Refactor railway implementation
- [x] Evaluate and implement faster region saving
- [x] Support multipolygons (https://github.com/louis-e/arnis/issues/112, https://github.com/louis-e/arnis/issues/114)
- [x] Memory optimization
- [x] Fix Github Action Workflow for releasing MacOS Binary
- [x] Design and implement a GUI
- [x] Automatic new world creation instead of using an existing world
- [x] Fix faulty empty chunks ([https://github.com/owengage/fastnbt/issues/120](https://github.com/owengage/fastnbt/issues/120)) (workaround found)
@@ -101,7 +103,7 @@ Feel free to choose an item from the To-Do or Known Bugs list, or bring your own
#### How to contribute
This project is open source and welcomes contributions from everyone! Whether you're interested in fixing bugs, improving performance, adding new features, or enhancing documentation, your input is valuable. Simply fork the repository, make your changes, and submit a pull request. We encourage discussions and suggestions to ensure the project remains modular, optimized, and easy to use for the community. You can use the parameter --debug to get a more detailed output of the processed values, which can be helpful for debugging and development. Contributions of all levels are appreciated, and your efforts help improve this tool for everyone.
Build and run it using: ```cargo run --release -- --path="C:/YOUR_PATH/.minecraft/saves/worldname" --bbox="min_lng,min_lat,max_lng,max_lat"```<br>
Build and run it using: ```cargo run --release --no-default-features -- --path="C:/YOUR_PATH/.minecraft/saves/worldname" --bbox="min_lng,min_lat,max_lng,max_lat"```<br>
For the GUI: ```cargo run --release```<br>
After your pull request was merged, I will take care of regularly creating update releases which will include your changes.

View File

@@ -1,3 +1,4 @@
fn main() {
#[cfg(feature = "gui")]
tauri_build::build()
}

View File

@@ -186,6 +186,7 @@ button:hover {
button {
color: #ffffff;
background-color: #0f0f0f98;
border-style: inherit;
}
button:active {
background-color: #0f0f0f69;
@@ -202,39 +203,6 @@ button:hover {
width: 100%;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 90%;
background-color: #808080;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
position: absolute;
z-index: 1;
bottom: -100%;
left: 5%;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: -10px;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent transparent #808080 transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
.controls-box button {
width: 100%;
}
@@ -275,6 +243,14 @@ button:hover {
color: #ffffff;
}
#terrain-toggle {
accent-color: #fecc44;
}
.terrain-toggle-container, .scale-slider-container {
margin: 15px 0;
}
#winter-toggle {
accent-color: #fecc44;
}

19
gui-src/index.html vendored
View File

@@ -38,16 +38,13 @@
<!-- Updated Tooltip Structure -->
<div class="tooltip" style="width: 100%;">
<button type="button" onclick="openWorldPicker()" style="padding: 10px; line-height: 1.2; width: 100%;" data-localize="choose_world">
Choose World
<button type="button" onclick="openWorldPicker()" style="padding: 10px; line-height: 1.2; width: 100%;">
<span id="choose_world">Choose World</span>
<br>
<span id="selected-world" style="font-size: 0.8em; color: #fecc44; display: block; margin-top: 4px;" data-localize="no_world_selected">
No world selected
</span>
</button>
<span class="tooltiptext" style="font-size: 0.8em; line-height: 1.2;">
Please select a Minecraft world that can be overwritten, as the generation process will replace existing structures in the chosen world!
</span>
</div>
<div class="button-container">
@@ -89,6 +86,12 @@
<span class="close-button" onclick="closeSettings()">&times;</span>
<h2 data-localize="customization_settings">Customization Settings</h2>
<!-- Terrain Toggle Button -->
<div class="terrain-toggle-container">
<label for="terrain-toggle" data-localize="terrain">Terrain:</label>
<input type="checkbox" id="terrain-toggle" name="terrain-toggle">
</div>
<!-- Winter Mode Toggle Button -->
<div class="winter-toggle-container">
<label for="winter-toggle" data-localize="winter_mode">Winter Mode:</label>
@@ -105,7 +108,7 @@
<!-- Bounding Box Input -->
<div class="bbox-input-container">
<label for="bbox-coords" data-localize="custom_bounding_box">Custom Bounding Box:</label>
<input type="text" id="bbox-coords" name="bbox-coords" maxlength="55" style="width: 280px;" autocomplete="one-time-code" placeholder="Format: lat,lng,lat,lng">
<input type="text" id="bbox-coords" name="bbox-coords" maxlength="55" style="width: 280px;" placeholder="Format: lat,lng,lat,lng">
</div>
<!-- Floodfill Timeout Input -->
@@ -139,10 +142,10 @@
<!-- Footer -->
<footer class="footer">
<a href="https://github.com/louis-e/arnis" target="_blank" class="footer-link" data-localize="footer_text">
© <span id="current-year"></span> Arnis v<span id="version-placeholder">x.x.x</span> by louis-e
© {year} Arnis v{version} by louis-e
</a>
</footer>
</main>
</body>
</html>
</html>

View File

@@ -72,7 +72,7 @@ You may add Your own copyright statement to Your modifications andmay provide ad
END OF TERMS AND CONDITIONS
Copyright 2025 Louis Erbkamm
Copyright ${new Date().getFullYear()} Louis Erbkamm
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0

297
gui-src/js/main.js vendored
View File

@@ -1,6 +1,15 @@
import { licenseText } from './license.js';
const { invoke } = window.__TAURI__.core;
let invoke;
if (window.__TAURI__) {
invoke = window.__TAURI__.core.invoke;
} else {
function dummyFunc() {}
window.__TAURI__ = { event: { listen: dummyFunc } };
invoke = dummyFunc;
}
const DEFAULT_LOCALE_PATH = `./locales/en.json`;
// Initialize elements and start the demo progress
window.addEventListener("DOMContentLoaded", async () => {
@@ -11,151 +20,123 @@ window.addEventListener("DOMContentLoaded", async () => {
initSettings();
initWorldPicker();
handleBboxInput();
const language = detectLanguage();
const localization = await loadLocalization(language);
const localization = await getLocalization();
await applyLocalization(localization);
initFooter();
await checkForUpdates();
});
async function loadLocalization(language) {
const response = await fetch(`./locales/${language}.json`);
/**
* Checks if a JSON response is invalid or falls back to HTML
* @param {Response} response - The fetch response object
* @returns {boolean} True if the response is invalid JSON
*/
function invalidJSON(response) {
// Workaround for Tauri always falling back to index.html for asset loading
return !response.ok || response.headers.get("Content-Type") === "text/html";
}
/**
* Fetches and returns localization data based on user's language
* Falls back to English if requested language is not available
* @returns {Promise<Object>} The localization JSON object
*/
async function getLocalization() {
const lang = navigator.language;
let response = await fetch(`./locales/${lang}.json`);
// Try with only first part of language code
if (invalidJSON(response)) {
response = await fetch(`./locales/${lang.split('-')[0]}.json`);
// Fallback to default English localization
if (invalidJSON(response)) {
response = await fetch(DEFAULT_LOCALE_PATH);
}
}
const localization = await response.json();
return localization;
}
/**
* Updates an HTML element with localized text
* @param {Object} json - Localization data
* @param {Object} elementObject - Object containing element or selector
* @param {string} localizedStringKey - Key for the localized string
*/
async function localizeElement(json, elementObject, localizedStringKey) {
const element =
(!elementObject.element || elementObject.element === "")
? document.querySelector(elementObject.selector) : elementObject.element;
const attribute = localizedStringKey.startsWith("placeholder_") ? "placeholder" : "textContent";
if (element) {
if (localizedStringKey in json) {
element[attribute] = json[localizedStringKey];
} else {
// Fallback to default (English) string
const response = await fetch(DEFAULT_LOCALE_PATH);
const defaultJson = await response.json();
element[attribute] = defaultJson[localizedStringKey];
}
}
}
async function applyLocalization(localization) {
const selectLocationElement = document.querySelector("h2[data-localize='select_location']");
if (selectLocationElement) {
selectLocationElement.textContent = localization.select_location;
}
const localizationElements = {
"h2[data-localize='select_location']": "select_location",
"#bbox-text": "zoom_in_and_choose",
"h2[data-localize='select_world']": "select_world",
"span[id='choose_world']": "choose_world",
"#selected-world": "no_world_selected",
"#start-button": "start_generation",
"h2[data-localize='progress']": "progress",
"h2[data-localize='choose_world_modal_title']": "choose_world_modal_title",
"button[data-localize='select_existing_world']": "select_existing_world",
"button[data-localize='generate_new_world']": "generate_new_world",
"h2[data-localize='customization_settings']": "customization_settings",
"label[data-localize='winter_mode']": "winter_mode",
"label[data-localize='world_scale']": "world_scale",
"label[data-localize='custom_bounding_box']": "custom_bounding_box",
"label[data-localize='floodfill_timeout']": "floodfill_timeout",
"label[data-localize='ground_level']": "ground_level",
".footer-link": "footer_text",
"button[data-localize='license_and_credits']": "license_and_credits",
"h2[data-localize='license_and_credits']": "license_and_credits",
const bboxTextElement = document.getElementById("bbox-text");
if (bboxTextElement) {
bboxTextElement.textContent = localization.zoom_in_and_choose;
}
// Placeholder strings
"input[id='bbox-coords']": "placeholder_bbox",
"input[id='floodfill-timeout']": "placeholder_floodfill",
"input[id='ground-level']": "placeholder_ground"
};
const selectWorldElement = document.querySelector("h2[data-localize='select_world']");
if (selectWorldElement) {
selectWorldElement.textContent = localization.select_world;
}
const chooseWorldButton = document.querySelector("button[data-localize='choose_world']");
if (chooseWorldButton) {
chooseWorldButton.firstChild.textContent = localization.choose_world;
}
const selectedWorldElement = document.getElementById("selected-world");
if (selectedWorldElement) {
selectedWorldElement.textContent = localization.no_world_selected;
}
const startButtonElement = document.getElementById("start-button");
if (startButtonElement) {
startButtonElement.textContent = localization.start_generation;
}
const progressElement = document.querySelector("h2[data-localize='progress']");
if (progressElement) {
progressElement.textContent = localization.progress;
}
const chooseWorldModalTitle = document.querySelector("h2[data-localize='choose_world_modal_title']");
if (chooseWorldModalTitle) {
chooseWorldModalTitle.textContent = localization.choose_world_modal_title;
}
const selectExistingWorldButton = document.querySelector("button[data-localize='select_existing_world']");
if (selectExistingWorldButton) {
selectExistingWorldButton.textContent = localization.select_existing_world;
}
const generateNewWorldButton = document.querySelector("button[data-localize='generate_new_world']");
if (generateNewWorldButton) {
generateNewWorldButton.textContent = localization.generate_new_world;
}
const customizationSettingsTitle = document.querySelector("h2[data-localize='customization_settings']");
if (customizationSettingsTitle) {
customizationSettingsTitle.textContent = localization.customization_settings;
}
const winterModeLabel = document.querySelector("label[data-localize='winter_mode']");
if (winterModeLabel) {
winterModeLabel.textContent = localization.winter_mode;
}
const worldScaleLabel = document.querySelector("label[data-localize='world_scale']");
if (worldScaleLabel) {
worldScaleLabel.textContent = localization.world_scale;
}
const customBoundingBoxLabel = document.querySelector("label[data-localize='custom_bounding_box']");
if (customBoundingBoxLabel) {
customBoundingBoxLabel.textContent = localization.custom_bounding_box;
}
const floodfillTimeoutLabel = document.querySelector("label[data-localize='floodfill_timeout']");
if (floodfillTimeoutLabel) {
floodfillTimeoutLabel.textContent = localization.floodfill_timeout;
}
const groundLevelLabel = document.querySelector("label[data-localize='ground_level']");
if (groundLevelLabel) {
groundLevelLabel.textContent = localization.ground_level;
}
const footerLinkElement = document.querySelector(".footer-link");
if (footerLinkElement) {
footerLinkElement.innerHTML = localization.footer_text.replace("{year}", '<span id="current-year"></span>').replace("{version}", '<span id="version-placeholder"></span>');
for (const selector in localizationElements) {
localizeElement(localization, { selector: selector }, localizationElements[selector]);
}
// Update error messages
window.localization = localization;
}
function detectLanguage() {
const lang = navigator.language || navigator.userLanguage;
const langCode = lang.split('-')[0];
switch (langCode) {
case 'es':
return 'es';
case 'ru':
return 'ru';
case 'de':
return 'de';
case 'zh':
return 'zh';
case 'uk':
return 'ua';
case 'pl':
return 'pl';
case 'ko':
return 'ko';
case 'sv':
return 'sv';
default:
return 'en';
}
}
// Function to initialize the footer with the current year and version
async function initFooter() {
const currentYear = new Date().getFullYear();
const currentYearElement = document.getElementById("current-year");
if (currentYearElement) {
currentYearElement.textContent = currentYear;
}
let version = "x.x.x";
try {
const version = await invoke('gui_get_version');
const versionPlaceholder = document.getElementById("version-placeholder");
if (versionPlaceholder) {
versionPlaceholder.textContent = version;
}
version = await invoke('gui_get_version');
} catch (error) {
console.error("Failed to fetch version:", error);
}
const footerElement = document.querySelector(".footer-link");
if (footerElement) {
footerElement.textContent =
footerElement.textContent
.replace("{year}", currentYear)
.replace("{version}", version);
}
}
// Function to check for updates and display a notification if available
@@ -173,7 +154,7 @@ async function checkForUpdates() {
updateMessage.style.display = "block";
updateMessage.style.textDecoration = "none";
updateMessage.textContent = window.localization.new_version_available;
localizeElement(window.localization, { element: updateMessage }, "new_version_available");
footer.style.marginTop = "15px";
footer.appendChild(updateMessage);
}
@@ -294,7 +275,11 @@ function initWorldPicker() {
window.closeWorldPicker = closeWorldPicker;
}
// Function to validate and handle bbox input
/**
* Validates and processes bounding box coordinates input
* Supports both comma and space-separated formats
* Updates the map display when valid coordinates are entered
*/
function handleBboxInput() {
const inputBox = document.getElementById("bbox-coords");
const bboxInfo = document.getElementById("bbox-info");
@@ -338,24 +323,32 @@ function handleBboxInput() {
map_container.contentWindow.location.reload();
// Update the info text
bboxInfo.textContent = window.localization.custom_selection_confirmed;
localizeElement(window.localization, { element: bboxInfo }, "custom_selection_confirmed");
bboxInfo.style.color = "#7bd864";
} else {
// Valid numbers but invalid order or range
bboxInfo.textContent = window.localization.error_coordinates_out_of_range;
localizeElement(window.localization, { element: bboxInfo }, "error_coordinates_out_of_range");
bboxInfo.style.color = "#fecc44";
selectedBBox = "";
}
} else {
// Input doesn't match the required format
bboxInfo.textContent = window.localization.invalid_format;
localizeElement(window.localization, { element: bboxInfo }, "invalid_format");
bboxInfo.style.color = "#fecc44";
selectedBBox = "";
}
});
}
// Function to calculate the bounding box "size" in square meters based on latitude and longitude
/**
* Calculates the approximate area of a bounding box in square meters
* Uses the Haversine formula for geodesic calculations
* @param {number} lng1 - First longitude coordinate
* @param {number} lat1 - First latitude coordinate
* @param {number} lng2 - Second longitude coordinate
* @param {number} lat2 - Second latitude coordinate
* @returns {number} Area in square meters
*/
function calculateBBoxSize(lng1, lat1, lng2, lat2) {
// Approximate distance calculation using Haversine formula or geodesic formula
const toRad = (angle) => (angle * Math.PI) / 180;
@@ -376,7 +369,11 @@ function calculateBBoxSize(lng1, lat1, lng2, lat2) {
return Math.abs(width * height);
}
// Function to normalize longitude to the range [-180, 180]
/**
* Normalizes a longitude value to the range [-180, 180]
* @param {number} lon - Longitude value to normalize
* @returns {number} Normalized longitude value
*/
function normalizeLongitude(lon) {
return ((lon + 180) % 360 + 360) % 360 - 180;
}
@@ -407,13 +404,13 @@ function displayBboxInfoText(bboxText) {
const selectedSize = calculateBBoxSize(lng1, lat1, lng2, lat2);
if (selectedSize > threshold2) {
bboxInfo.textContent = window.localization.area_too_large;
localizeElement(window.localization, { element: bboxInfo }, "area_too_large");
bboxInfo.style.color = "#fa7878";
} else if (selectedSize > threshold1) {
bboxInfo.textContent = window.localization.area_extensive;
localizeElement(window.localization, { element: bboxInfo }, "area_extensive");
bboxInfo.style.color = "#fecc44";
} else {
bboxInfo.textContent = window.localization.selection_confirmed;
localizeElement(window.localization, { element: bboxInfo }, "selection_confirmed");
bboxInfo.style.color = "#7bd864";
}
}
@@ -435,22 +432,32 @@ async function selectWorld(generate_new_world) {
closeWorldPicker();
}
/**
* Handles world selection errors and displays appropriate messages
* @param {number} errorCode - Error code from the backend
*/
function handleWorldSelectionError(errorCode) {
const errorMessages = {
1: window.localization.minecraft_directory_not_found,
2: window.localization.world_in_use,
3: window.localization.failed_to_create_world,
4: window.localization.no_world_selected_error
const errorKeys = {
1: "minecraft_directory_not_found",
2: "world_in_use",
3: "failed_to_create_world",
4: "no_world_selected_error"
};
const errorMessage = errorMessages[errorCode] || "Unknown error";
document.getElementById('selected-world').textContent = errorMessage;
document.getElementById('selected-world').style.color = "#fa7878";
const errorKey = errorKeys[errorCode] || "unknown_error";
const selectedWorld = document.getElementById('selected-world');
localizeElement(window.localization, { element: selectedWorld }, errorKey);
selectedWorld.style.color = "#fa7878";
worldPath = "";
console.error(error);
console.error(errorCode);
}
let generationButtonEnabled = true;
/**
* Initiates the world generation process
* Validates required inputs and sends generation parameters to the backend
* @returns {Promise<void>}
*/
async function startGeneration() {
try {
if (generationButtonEnabled === false) {
@@ -458,17 +465,20 @@ async function startGeneration() {
}
if (!selectedBBox || selectedBBox == "0.000000 0.000000 0.000000 0.000000") {
document.getElementById('bbox-info').textContent = window.localization.select_location_first;
document.getElementById('bbox-info').style.color = "#fa7878";
const bboxInfo = document.getElementById('bbox-info');
localizeElement(window.localization, { element: bboxInfo }, "select_location_first");
bboxInfo.style.color = "#fa7878";
return;
}
if (!worldPath || worldPath === "") {
document.getElementById('selected-world').textContent = window.localization.select_minecraft_world_first;
document.getElementById('selected-world').style.color = "#fa7878";
const selectedWorld = document.getElementById('selected-world');
localizeElement(window.localization, { element: selectedWorld }, "select_minecraft_world_first");
selectedWorld.style.color = "#fa7878";
return;
}
var terrain = document.getElementById("terrain-toggle").checked;
var winter_mode = document.getElementById("winter-toggle").checked;
var scale = parseFloat(document.getElementById("scale-value-slider").value);
var floodfill_timeout = parseInt(document.getElementById("floodfill-timeout").value, 10);
@@ -486,6 +496,7 @@ async function startGeneration() {
groundLevel: ground_level,
winterMode: winter_mode,
floodfillTimeout: floodfill_timeout,
terrainEnabled: terrain
});
console.log("Generation process started.");

View File

@@ -9,8 +9,6 @@
"custom_selection_confirmed": "Benutzerdefinierte Auswahl bestätigt!",
"error_coordinates_out_of_range": "Fehler: Koordinaten sind außerhalb des Bereichs oder falsch geordnet (Lat vor Lng erforderlich).",
"invalid_format": "Ungültiges Format. Bitte verwende 'lat,lng,lat,lng' oder 'lat lng lat lng'.",
"select_a_location_first": "Wähle zuerst einen Standort aus!",
"select_a_minecraft_world_first": "Wähle zuerst eine Minecraft Welt aus!",
"generation_process_started": "Generierungsprozess gestartet.",
"winter_mode": "Wintermodus:",
"world_scale": "Weltmaßstab:",
@@ -31,5 +29,10 @@
"select_location_first": "Wähle zuerst einen Standort aus!",
"area_too_large": "Dieses Gebiet ist sehr groß und könnte das Berechnungslimit überschreiten.",
"area_extensive": "Diese Gebietsgröße könnte längere Zeit für die Generierung benötigen.",
"selection_confirmed": "Auswahl bestätigt!"
"selection_confirmed": "Auswahl bestätigt!",
"unknown_error": "Unknown error",
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Sekunden",
"placeholder_ground": "Bodenhöhe"
}

38
gui-src/locales/en-US.json vendored Normal file
View File

@@ -0,0 +1,38 @@
{
"select_location": "Select Location",
"zoom_in_and_choose": "Zoom in and choose your area using the rectangle tool",
"select_world": "Select World",
"choose_world": "Choose World",
"no_world_selected": "No world selected",
"start_generation": "Start Generation",
"progress": "Progress",
"custom_selection_confirmed": "Custom selection confirmed!",
"error_coordinates_out_of_range": "Error: Coordinates are out of range or incorrectly ordered (Lat before Lng required).",
"invalid_format": "Invalid format. Please use 'lat,lng,lat,lng' or 'lat lng lat lng'.",
"generation_process_started": "Generation process started.",
"winter_mode": "Winter Mode:",
"world_scale": "World Scale:",
"custom_bounding_box": "Custom Bounding Box:",
"floodfill_timeout": "Floodfill Timeout (sec):",
"ground_level": "Ground Level:",
"choose_world_modal_title": "Choose World",
"select_existing_world": "Select existing world",
"generate_new_world": "Generate new world",
"customization_settings": "Customization Settings",
"footer_text": "© {year} Arnis v{version} by louis-e",
"new_version_available": "There's a new version available! Click here to download it.",
"minecraft_directory_not_found": "Minecraft directory not found",
"world_in_use": "The selected world is currently in use",
"failed_to_create_world": "Failed to create new world",
"no_world_selected_error": "No world selected",
"select_minecraft_world_first": "Select a Minecraft world first!",
"select_location_first": "Select a location first!",
"area_too_large": "This area is very large and could exceed typical computing limits.",
"area_extensive": "The area is quite extensive and may take significant time and resources.",
"selection_confirmed": "Selection confirmed!",
"unknown_error": "Unknown error",
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level"
}

View File

@@ -1,35 +0,0 @@
{
"select_location": "Select Location",
"zoom_in_and_choose": "Zoom in and choose your area using the rectangle tool",
"select_world": "Select World",
"choose_world": "Choose World",
"no_world_selected": "No world selected",
"start_generation": "Start Generation",
"progress": "Progress",
"custom_selection_confirmed": "Custom selection confirmed!",
"error_coordinates_out_of_range": "Error: Coordinates are out of range or incorrectly ordered (Lat before Lng required).",
"invalid_format": "Invalid format. Please use 'lat,lng,lat,lng' or 'lat lng lat lng'.",
"select_a_location_first": "Select a location first!",
"select_a_minecraft_world_first": "Select a Minecraft world first!",
"generation_process_started": "Generation process started.",
"winter_mode": "Winter Mode:",
"world_scale": "World Scale:",
"custom_bounding_box": "Custom Bounding Box:",
"floodfill_timeout": "Floodfill Timeout (sec):",
"ground_level": "Ground Level:",
"choose_world_modal_title": "Choose World",
"select_existing_world": "Select existing world",
"generate_new_world": "Generate new world",
"customization_settings": "Customization Settings",
"footer_text": "© {year} Arnis v{version} by louis-e",
"new_version_available": "There's a new version available! Click here to download it.",
"minecraft_directory_not_found": "Minecraft directory not found",
"world_in_use": "The selected world is currently in use",
"failed_to_create_world": "Failed to create new world",
"no_world_selected_error": "No world selected",
"select_minecraft_world_first": "Select a Minecraft world first!",
"select_location_first": "Select a location first!",
"area_too_large": "This area is very large and could exceed typical computing limits.",
"area_extensive": "The area is quite extensive and may take significant time and resources.",
"selection_confirmed": "Selection confirmed!"
}

1
gui-src/locales/en.json vendored Symbolic link
View File

@@ -0,0 +1 @@
en-US.json

View File

@@ -9,8 +9,6 @@
"custom_selection_confirmed": "¡Selección personalizada confirmada!",
"error_coordinates_out_of_range": "Error: Las coordenadas están fuera de rango o están ordenadas incorrectamente (Lat antes de Lng requerido).",
"invalid_format": "Formato inválido. Por favor, use 'lat,lng,lat,lng' o 'lat lng lat lng'.",
"select_a_location_first": "¡Seleccione una ubicación primero!",
"select_a_minecraft_world_first": "¡Seleccione un mundo de Minecraft primero!",
"generation_process_started": "Proceso de generación iniciado.",
"winter_mode": "Modo invierno:",
"world_scale": "Escala del mundo:",
@@ -31,5 +29,10 @@
"select_location_first": "¡Seleccione una ubicación primero!",
"area_too_large": "Esta área es muy grande y podría exceder los límites típicos de computación.",
"area_extensive": "El área es bastante extensa y puede requerir mucho tiempo y recursos.",
"selection_confirmed": "¡Selección confirmada!"
"selection_confirmed": "¡Selección confirmada!",
"unknown_error": "Unknown error",
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level"
}

38
gui-src/locales/fi.json vendored Normal file
View File

@@ -0,0 +1,38 @@
{
"select_location": "Valitse paikka",
"zoom_in_and_choose": "Zoomaa ja valitse paikka käyttämällä suorakulmatyökalua.",
"select_world": "Valitse maailma",
"choose_world": "Valitse maailma",
"no_world_selected": "Maailmaa ei valittu",
"start_generation": "Aloita generointi",
"progress": "Edistys",
"custom_selection_confirmed": "Mukautettu valinta vahvistettu!",
"error_coordinates_out_of_range": "Virhe: Koordinaatit ovat kantaman ulkopuolella tai vääriin aseteltu (Lat ennen Lng vaadittu).",
"invalid_format": "Väärä formaatti. Käytä 'lat,lng,lat,lng' tai 'lat lng lat lng'.",
"generation_process_started": "Luontiprosessi aloitettu.",
"winter_mode": "Talvitila:",
"world_scale": "Maailmanskaalaus:",
"custom_bounding_box": "Mukautettu rajoituslaatikko:",
"floodfill_timeout": "Täytön aikakatkaisu (sec):",
"ground_level": "Maataso:",
"choose_world_modal_title": "Valitse maailma",
"select_existing_world": "Valitse olemassa oleva maailma",
"generate_new_world": "Luo uusi maailma",
"customization_settings": "Kustomisaatio-asetukset",
"footer_text": "© {year} Arnis v{version} tekijänä louis-e",
"new_version_available": "Uusi versio on saatavilla! Paina tästä ladataksesi sen.",
"minecraft_directory_not_found": "Minecraft-hakemistoa ei löytynyt",
"world_in_use": "Valittu maailma käytössä.",
"failed_to_create_world": "Uuden maailman luonti epäonnistui",
"no_world_selected_error": "Maailmaa ei valittu",
"select_minecraft_world_first": "Valitse Minecraft-maailma ensin!",
"select_location_first": "Valitse paikka ensin!",
"area_too_large": "Tämä alue on todella iso ja voi ylittää tyypilliset laskentarajat.",
"area_extensive": "Alue on aika laaja ja voi viedä pitkän ajan ja resursseja.",
"selection_confirmed": "Valinta vahvistettu!",
"unknown_error": "Unknown error",
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level"
}

View File

@@ -1,35 +1,38 @@
{
"select_location": "장소 선택",
"zoom_in_and_choose": "줌 인하고 직사각형 도구를 사용하여 영역을 선택하세요.",
"select_world": "세계 선택",
"choose_world": "세계 선택",
"no_world_selected": "선택된 세계 없음",
"start_generation": "생성 시작",
"progress": "진행",
"custom_selection_confirmed": "사용자 지정 선택이 확인되었습니다!",
"error_coordinates_out_of_range": "오류: 좌표가 범위를 벗어나거나 잘못된 순서입니다 (Lat이 Lng보다 먼저 필요합니다).",
"invalid_format": "잘못된 형식입니다. 'lat,lng,lat,lng' 또는 'lat lng lat lng' 형식을 사용하세요.",
"select_a_location_first": "먼저 위치를 선택하세요!",
"select_a_minecraft_world_first": "먼저 마인크래프트 세계를 선택하세요!",
"generation_process_started": "생성 프로세스가 시작되었습니다.",
"winter_mode": "겨울 모드:",
"world_scale": "세계 규모:",
"custom_bounding_box": "사용자 지정 경계 상자:",
"floodfill_timeout": "채우기 시간 초과 (초):",
"ground_level": "지면 레벨:",
"choose_world_modal_title": "세계 선택",
"select_existing_world": "이미 존재하는 세계 선택",
"generate_new_world": "새 세계 생성",
"customization_settings": "사용자 지정 설정",
"footer_text": "© {year} Arnis v{version} by louis-e",
"new_version_available": "새로운 버전이 있습니다! 여기를 클릭하여 다운로드하세요.",
"minecraft_directory_not_found": "마인크래프트 디렉토리가 발견되지 않았습니다",
"world_in_use": "선택 세계가 현재 사용 중입니다",
"failed_to_create_world": "새 세계 생성에 실패했습니다",
"no_world_selected_error": "선택된 세계 없음 오류",
"select_minecraft_world_first": "먼저 마인크래프트 세계를 선택하세요!",
"select_location_first": "먼저 위치를 선택하세요!",
"area_too_large": "이 지역은 매우 크고, 일반적인 계산 한계를 초과할 수 있습니다.",
"area_extensive": "이 지역은 꽤 광범위하여 значитель한 시간과 자원이 필요할 수 있습니다.",
"selection_confirmed": "선택이 확인되었습니다!"
"select_location": "장소 선택",
"zoom_in_and_choose": "줌 인하고 직사각형 도구를 사용하여 영역을 선택하세요.",
"select_world": "세계 선택",
"choose_world": "세계 선택",
"no_world_selected": "선택된 세계 없음",
"start_generation": "생성 시작",
"progress": "진행",
"custom_selection_confirmed": "사용자 지정 선택이 확인되었습니다!",
"error_coordinates_out_of_range": "오류: 좌표가 범위를 벗어나거나 잘못된 순서입니다 (Lat이 Lng보다 먼저 필요합니다).",
"invalid_format": "잘못된 형식입니다. 'lat,lng,lat,lng' 또는 'lat lng lat lng' 형식을 사용하세요.",
"generation_process_started": "생성 프로세스가 시작되었습니다.",
"winter_mode": "겨울 모드:",
"world_scale": "세계 규모:",
"custom_bounding_box": "사용자 지정 경계 상자:",
"floodfill_timeout": "채우기 시간 초과 (초):",
"ground_level": "지면 레벨:",
"choose_world_modal_title": "세계 선택",
"select_existing_world": "이미 존재하는 세계 선택",
"generate_new_world": "세계 생성",
"customization_settings": "사용자 지정 설정",
"footer_text": "© {year} Arnis v{version} by louis-e",
"new_version_available": "새로운 버전이 있습니다! 여기를 클릭하여 다운로드하세요.",
"minecraft_directory_not_found": "마인크래프트 디렉토리가 발견되지 않았습니다",
"world_in_use": "선택한 세계가 현재 사용 중입니다",
"failed_to_create_world": "새 세계 생성에 실패했습니다",
"no_world_selected_error": "선택 세계 없음 오류",
"select_minecraft_world_first": "먼저 마인크래프트 세계를 선택하세요!",
"select_location_first": "먼저 위치를 선택하세요!",
"area_too_large": "이 지역은 매우 크고, 일반적인 계산 한계를 초과할 수 있습니다.",
"area_extensive": "이 지역은 꽤 광범위하여 значитель한 시간과 자원이 필요할 수 있습니다.",
"selection_confirmed": "선택이 확인되었습니다!",
"unknown_error": "Unknown error",
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level"
}

38
gui-src/locales/lt.json vendored Normal file
View File

@@ -0,0 +1,38 @@
{
"select_location": "Vietos pasirinkimas",
"zoom_in_and_choose": "Pasididinkite žemėlapį ir pasirinkite plotą su kvadrato įrankiu",
"select_world": "Pasaulio pasirinkimas",
"choose_world": "Pasirinkti pasaulį",
"no_world_selected": "Pasaulis nepasirinktas",
"start_generation": "Pradėti generaciją",
"progress": "Progresas",
"custom_selection_confirmed": "Rėmo pasirinkimas patvirtintas!",
"error_coordinates_out_of_range": "Klaida: Koordinatės yra už ribų arba neteisingai išdėstytos (plat turi būti prieš ilg).",
"invalid_format": "Neteisingas formatas. Prašome naudoti 'plat,ilg,plat,ilg' arba 'plat ilg plat ilg'.",
"generation_process_started": "Generacijos procesas pradėtas.",
"winter_mode": "Žiemos režimas:",
"world_scale": "Pasaulio mastelis:",
"custom_bounding_box": "Pasirinktinis ribos rėmas:",
"floodfill_timeout": "Užpildymo laiko limitas (sek.):",
"ground_level": "Žemės lygis:",
"choose_world_modal_title": "Pasaulio pasirinkimas",
"select_existing_world": "Pasirinkti esamą pasaulį",
"generate_new_world": "Sugeneruoti naują pasaulį",
"customization_settings": "Generacijos nustatymai",
"footer_text": "© {year} „Arnis“ v{version} sukurta louis-e",
"new_version_available": "Surasta nauja versija! Spauskite čia kad ją atsisiųstumėte.",
"minecraft_directory_not_found": "Nerastas „Minecraft“ aplankas",
"world_in_use": "Pasirinktas pasaulis dabar užimtas",
"failed_to_create_world": "Klaida sukuriant naują pasaulį",
"no_world_selected_error": "Nėra pasirinktas pasaulis",
"select_minecraft_world_first": "Pirma pasirinkite „Minecraft“ pasaulį!",
"select_location_first": "Pirma pasirinkite vietą!",
"area_too_large": "Šis plotas yra labai didelis ir gali viršyti tipinius resursų limitus.",
"area_extensive": "Šis plotas yra pakankamai didelis kuriam reikėtų daug laiko ir resursų.",
"selection_confirmed": "Pasirinkimas patvirtintas!",
"unknown_error": "Nežinoma klaida",
"license_and_credits": "Licencija ir padėkos",
"placeholder_bbox": "Formatas: plat,lyg,plat,lyg",
"placeholder_floodfill": "Sekundės",
"placeholder_ground": "Žemės lygis"
}

View File

@@ -1,35 +1,38 @@
{
"select_location": "Wybierz lokalizację",
"zoom_in_and_choose": "Przybliż i zaznacz obszar za pomocą prostokątnego narzędzia",
"select_world": "Wybierz świat",
"choose_world": "Wybierz świat",
"no_world_selected": "Nie wybrano świata",
"start_generation": "Rozpocznij generowanie",
"progress": "Postęp",
"custom_selection_confirmed": "Niestandardowy wybór potwierdzony!",
"error_coordinates_out_of_range": "Błąd: Współrzędne są poza zakresem lub nieprawidłowo uporządkowane (wymagane Lat przed Lng).",
"invalid_format": "Nieprawidłowy format. Użyj 'lat,lng,lat,lng' lub 'lat lng lat lng'.",
"select_a_location_first": "Najpierw wybierz lokalizację!",
"select_a_minecraft_world_first": "Najpierw wybierz świat Minecrafta!",
"generation_process_started": "Proces generowania rozpoczęty.",
"winter_mode": "Tryb zimowy:",
"world_scale": "Skala świata:",
"custom_bounding_box": "Niestandardowe obramowanie obszaru:",
"floodfill_timeout": "Limit czasu wypełniania (sek):",
"ground_level": "Wysokość obszaru:",
"choose_world_modal_title": "Wybierz świat",
"select_existing_world": "Wybierz istniejący świat",
"generate_new_world": "Generuj nowy świat",
"customization_settings": "Ustawienia personalizacji",
"footer_text": "© {year} Arnis v{version} przez louis-e",
"new_version_available": "Dostępna jest nowa wersja! Kliknij tutaj, aby ją pobrać.",
"minecraft_directory_not_found": "Nie znaleziono katalogu Minecrafta",
"world_in_use": "Wybrany świat jest obecnie używany",
"failed_to_create_world": "Nie udało się utworzyć nowego świata",
"no_world_selected_error": "Nie wybrano świata",
"select_minecraft_world_first": "Najpierw wybierz świat Minecrafta!",
"select_location_first": "Najpierw wybierz lokalizację!",
"area_too_large": "Ten obszar jest bardzo duży i może przekroczyć typowe limity obliczeniowe.",
"area_extensive": "Ten obszar jest dość rozległy i może wymagać znacznego czasu i zasobów.",
"selection_confirmed": "Wybór potwierdzony!"
}
"select_location": "Wybierz lokalizację",
"zoom_in_and_choose": "Przybliż i zaznacz obszar za pomocą prostokąta",
"select_world": "Wybierz świat",
"choose_world": "Wybierz świat",
"no_world_selected": "Nie wybrano świata",
"start_generation": "Rozpocznij generowanie",
"progress": "Postęp",
"custom_selection_confirmed": "Niestandardowy wybór potwierdzony!",
"error_coordinates_out_of_range": "Błąd: Współrzędne są poza zakresem lub w złej kolejności (wymagana szerokość przed długością).",
"invalid_format": "Nieprawidłowy format. Użyj 'szer.,dł.,szer.,dł.' lub 'szer. dł. szer. dł.'.",
"generation_process_started": "Proces generowania rozpoczęty.",
"winter_mode": "Tryb Zimowy:",
"world_scale": "Skala świata:",
"custom_bounding_box": "Niestandardowy obszar:",
"floodfill_timeout": "Limit czasu wypełniania (sek):",
"ground_level": "Wysokość obszaru:",
"choose_world_modal_title": "Wybierz świat",
"select_existing_world": "Wybierz istniejący świat",
"generate_new_world": "Generuj nowy świat",
"customization_settings": "Ustawienia personalizacji",
"footer_text": "© {year} Arnis v{version} autorstwa louis-e",
"new_version_available": "Dostępna jest nowa wersja! Kliknij tutaj, aby ją pobrać.",
"minecraft_directory_not_found": "Nie znaleziono katalogu Minecrafta",
"world_in_use": "Wybrany świat jest obecnie używany",
"failed_to_create_world": "Nie udało się utworzyć świata",
"no_world_selected_error": "Nie wybrano świata",
"select_minecraft_world_first": "Najpierw wybierz świat Minecrafta!",
"select_location_first": "Najpierw wybierz lokalizację!",
"area_too_large": "Ten obszar jest bardzo duży i może przekroczyć limity obliczeniowe.",
"area_extensive": "Ten obszar jest rozległy i może pochłonąć dużo czasu oraz zasobów.",
"selection_confirmed": "Wybór potwierdzony!",
"unknown_error": "Unknown error",
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level"
}

View File

@@ -9,8 +9,6 @@
"custom_selection_confirmed": "Пользовательский выбор подтвержден!",
"error_coordinates_out_of_range": "Ошибка: Координаты находятся вне зоны действия или указаны в неправильном порядке (сначала широта, затем долгота)",
"invalid_format": "Неверный формат. Используйте 'широта,долгота,широта,долгота' или 'широта долгота широта долгота'",
"select_a_location_first": "Сначала выберите местоположение!",
"select_a_minecraft_world_first": "Сначала выберите мир Minecraft!",
"generation_process_started": "Процесс генерации начат",
"winter_mode": "Зимний режим:",
"world_scale": "Масштаб мира:",
@@ -31,5 +29,10 @@
"select_location_first": "Сначала выберите местоположение!",
"area_too_large": "Эта область слишком велика и может превысить типичные вычислительные ограничения",
"area_extensive": "Область довольно обширна и может потребовать значительного времени и ресурсов",
"selection_confirmed": "Выбор подтвержден!"
}
"selection_confirmed": "Выбор подтвержден!",
"unknown_error": "Unknown error",
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level"
}

View File

@@ -9,8 +9,6 @@
"custom_selection_confirmed": "Anpassad markering bekräftad!",
"error_coordinates_out_of_range": "Fel: Koordinater är utanför området eller felaktigt ordnade (Lat före Lng krävs).",
"invalid_format": "Ogiltigt format. Använd 'lat,lng,lat,lng' eller 'lat lng lat lng'.",
"select_a_location_first": "Välj en plats först!",
"select_a_minecraft_world_first": "Välj en Minecraft-värld först!",
"generation_process_started": "Genereringsprocessen startad.",
"winter_mode": "Vinterläge:",
"world_scale": "Världsskala:",
@@ -31,5 +29,10 @@
"select_location_first": "Välj plats först!",
"area_too_large": "Detta område är mycket stort och kan överskrida vanliga beräkningsgränser.",
"area_extensive": "Området är ganska extensivt och kan ta betydande tid och resurser.",
"selection_confirmed": "Val bekräftat!"
"selection_confirmed": "Val bekräftat!",
"unknown_error": "Unknown error",
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level"
}

View File

@@ -9,8 +9,6 @@
"custom_selection_confirmed": "Користувацький вибір підтверджено!",
"error_coordinates_out_of_range": "Помилка: Координати поза діапазоном або неправильно впорядковані (потрібно широта перед довгота)",
"invalid_format": "Неправильний формат. Будь ласка, використовуйте 'широта,довгота,широта,довгота' або 'широта довгота широта довгота'",
"select_a_location_first": "Спочатку оберіть місцезнахождення!",
"select_a_minecraft_world_first": "Спочатку оберіть світ Minecraft!",
"generation_process_started": "Процес генерації розпочато",
"winter_mode": "Зимовий режим:",
"world_scale": "Масштаб світу:",
@@ -31,5 +29,10 @@
"select_location_first": "Спочатку виберіть місцезнаходження!",
"area_too_large": "Ця область дуже велика і може перевищити типові обчислювальні межі",
"area_extensive": "Область досить велика і може вимагати значного часу та ресурсів",
"selection_confirmed": "Вибір підтверджено!"
}
"selection_confirmed": "Вибір підтверджено!",
"unknown_error": "Unknown error",
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level"
}

View File

@@ -9,8 +9,6 @@
"custom_selection_confirmed": "自定义选择已确认!",
"error_coordinates_out_of_range": "错误:坐标超出范围或顺序不正确(需要先纬度后经度)。",
"invalid_format": "格式无效。请使用 'lat,lng,lat,lng' 或 'lat lng lat lng'。",
"select_a_location_first": "请先选择一个位置!",
"select_a_minecraft_world_first": "请先选择一个 Minecraft 世界!",
"generation_process_started": "生成过程已开始。",
"winter_mode": "冬季模式:",
"world_scale": "世界比例:",
@@ -31,5 +29,10 @@
"select_location_first": "请先选择一个位置!",
"area_too_large": "该区域非常大,可能会超出典型的计算限制。",
"area_extensive": "该区域相当广泛,可能需要大量时间和资源。",
"selection_confirmed": "选择已确认!"
"selection_confirmed": "选择已确认!",
"unknown_error": "Unknown error",
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level"
}

View File

@@ -41,6 +41,10 @@ pub struct Args {
#[arg(long, default_value_t = false)]
pub winter: bool,
/// Enable terrain (optional)
#[arg(long, default_value_t = false, action = clap::ArgAction::SetFalse)]
pub terrain: bool,
/// Enable debug mode (optional)
#[arg(long, default_value_t = false, action = clap::ArgAction::SetTrue)]
pub debug: bool,

View File

@@ -141,6 +141,9 @@ impl Block {
111 => "snow_block",
112 => "snow",
113 => "oak_sign",
114 => "andesite_wall",
115 => "stone_brick_wall",
116..=125 => "rail",
_ => panic!("Invalid id"),
}
}
@@ -187,6 +190,80 @@ impl Block {
map
})),
116 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert(
"shape".to_string(),
Value::String("north_south".to_string()),
);
map
})),
117 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert("shape".to_string(), Value::String("east_west".to_string()));
map
})),
118 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert(
"shape".to_string(),
Value::String("ascending_east".to_string()),
);
map
})),
119 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert(
"shape".to_string(),
Value::String("ascending_west".to_string()),
);
map
})),
120 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert(
"shape".to_string(),
Value::String("ascending_north".to_string()),
);
map
})),
121 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert(
"shape".to_string(),
Value::String("ascending_south".to_string()),
);
map
})),
122 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert("shape".to_string(), Value::String("north_east".to_string()));
map
})),
123 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert("shape".to_string(), Value::String("north_west".to_string()));
map
})),
124 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert("shape".to_string(), Value::String("south_east".to_string()));
map
})),
125 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert("shape".to_string(), Value::String("south_west".to_string()));
map
})),
_ => None,
}
}
@@ -301,6 +378,8 @@ pub const YELLOW_TERRACOTTA: Block = Block::new(104);
pub const SNOW_BLOCK: Block = Block::new(111);
pub const SNOW_LAYER: Block = Block::new(112);
pub const SIGN: Block = Block::new(113);
pub const ANDESITE_WALL: Block = Block::new(114);
pub const STONE_BRICK_WALL: Block = Block::new(115);
pub const CARROTS: Block = Block::new(105);
pub const DARK_OAK_DOOR_LOWER: Block = Block::new(106);
@@ -310,6 +389,17 @@ pub const WHEAT: Block = Block::new(109);
pub const BEDROCK: Block = Block::new(110);
pub const RAIL_NORTH_SOUTH: Block = Block::new(116);
pub const RAIL_EAST_WEST: Block = Block::new(117);
pub const RAIL_ASCENDING_EAST: Block = Block::new(118);
pub const RAIL_ASCENDING_WEST: Block = Block::new(119);
pub const RAIL_ASCENDING_NORTH: Block = Block::new(120);
pub const RAIL_ASCENDING_SOUTH: Block = Block::new(121);
pub const RAIL_NORTH_EAST: Block = Block::new(122);
pub const RAIL_NORTH_WEST: Block = Block::new(123);
pub const RAIL_SOUTH_EAST: Block = Block::new(124);
pub const RAIL_SOUTH_WEST: Block = Block::new(125);
// Variations for building corners
pub fn building_corner_variations() -> Vec<Block> {
vec![

View File

@@ -8,26 +8,32 @@ pub fn bresenham_line(
y2: i32,
z2: i32,
) -> Vec<(i32, i32, i32)> {
let mut points: Vec<(i32, i32, i32)> = Vec::new();
// Calculate max possible points needed
let dx = if x2 > x1 { x2 - x1 } else { x1 - x2 };
let dy = if y2 > y1 { y2 - y1 } else { y1 - y2 };
let dz = if z2 > z1 { z2 - z1 } else { z1 - z2 };
let dx: i32 = (x2 - x1).abs();
let dy: i32 = (y2 - y1).abs();
let dz: i32 = (z2 - z1).abs();
// Pre-allocate vector with exact size needed
let capacity = dx.max(dy).max(dz) + 1;
let mut points = Vec::with_capacity(capacity as usize);
points.reserve_exact(capacity as usize);
let xs: i32 = if x1 < x2 { 1 } else { -1 };
let ys: i32 = if y1 < y2 { 1 } else { -1 };
let zs: i32 = if z1 < z2 { 1 } else { -1 };
let xs = if x1 < x2 { 1 } else { -1 };
let ys = if y1 < y2 { 1 } else { -1 };
let zs = if z1 < z2 { 1 } else { -1 };
let mut x: i32 = x1;
let mut y: i32 = y1;
let mut z: i32 = z1;
let mut x = x1;
let mut y = y1;
let mut z = z1;
// Determine dominant axis once, outside the loop
if dx >= dy && dx >= dz {
let mut p1: i32 = 2 * dy - dx;
let mut p2: i32 = 2 * dz - dx;
let mut p1 = 2 * dy - dx;
let mut p2 = 2 * dz - dx;
while x != x2 {
points.push((x, y, z));
if p1 >= 0 {
y += ys;
p1 -= 2 * dx;
@@ -41,11 +47,12 @@ pub fn bresenham_line(
x += xs;
}
} else if dy >= dx && dy >= dz {
let mut p1: i32 = 2 * dx - dy;
let mut p2: i32 = 2 * dz - dy;
let mut p1 = 2 * dx - dy;
let mut p2 = 2 * dz - dy;
while y != y2 {
points.push((x, y, z));
if p1 >= 0 {
x += xs;
p1 -= 2 * dy;
@@ -59,11 +66,12 @@ pub fn bresenham_line(
y += ys;
}
} else {
let mut p1: i32 = 2 * dy - dz;
let mut p2: i32 = 2 * dx - dz;
let mut p1 = 2 * dy - dz;
let mut p2 = 2 * dx - dz;
while z != z2 {
points.push((x, y, z));
if p1 >= 0 {
y += ys;
p1 -= 2 * dz;

12
src/cartesian.rs Normal file
View File

@@ -0,0 +1,12 @@
#[derive(Copy, Clone)]
pub struct XZPoint {
pub x: i32,
pub z: i32,
}
impl XZPoint {
#[inline]
pub fn new(x: i32, z: i32) -> Self {
Self { x, z }
}
}

View File

@@ -1,36 +1,32 @@
use crate::args::Args;
use crate::block_definitions::{DIRT, GRASS_BLOCK, SNOW_BLOCK};
use crate::cartesian::XZPoint;
use crate::element_processing::*;
use crate::ground::Ground;
use crate::osm_parser::ProcessedElement;
use crate::progress::emit_gui_progress_update;
use crate::world_editor::WorldEditor;
use colored::Colorize;
use indicatif::{ProgressBar, ProgressStyle};
const MIN_Y: i32 = -64;
pub fn generate_world(
elements: Vec<ProcessedElement>,
args: &Args,
scale_factor_x: f64,
scale_factor_z: f64,
) -> Result<(), String> {
println!("{} Processing data...", "[3/5]".bold());
emit_gui_progress_update(10.0, "Processing data...");
let ground_level: i32 = args.ground_level;
let region_dir: String = format!("{}/region", args.path);
let mut editor: WorldEditor =
WorldEditor::new(&region_dir, scale_factor_x, scale_factor_z, args);
let mut editor: WorldEditor = WorldEditor::new(&region_dir, scale_factor_x, scale_factor_z);
editor.set_sign(
"".to_string(),
"Generated World".to_string(),
"This direction".to_string(),
"".to_string(),
9,
-61,
9,
6,
);
println!("{} Processing data...", "[3/5]".bold());
if args.terrain {
emit_gui_progress_update(10.0, "Fetching elevation...");
}
let ground: Ground = Ground::new(args);
emit_gui_progress_update(11.0, "Processing terrain...");
// Process data
let elements_count: usize = elements.len();
@@ -40,8 +36,8 @@ pub fn generate_world(
.unwrap()
.progress_chars("█▓░"));
let progress_increment_prcs: f64 = 50.0 / elements_count as f64;
let mut current_progress_prcs: f64 = 10.0;
let progress_increment_prcs: f64 = 49.0 / elements_count as f64;
let mut current_progress_prcs: f64 = 11.0;
let mut last_emitted_progress: f64 = current_progress_prcs;
for element in &elements {
@@ -65,59 +61,56 @@ pub fn generate_world(
match element {
ProcessedElement::Way(way) => {
if way.tags.contains_key("building") || way.tags.contains_key("building:part") {
buildings::generate_buildings(&mut editor, way, ground_level, args, None);
buildings::generate_buildings(&mut editor, way, &ground, args, None);
} else if way.tags.contains_key("highway") {
highways::generate_highways(&mut editor, element, ground_level, args);
highways::generate_highways(&mut editor, element, &ground, args);
} else if way.tags.contains_key("landuse") {
landuse::generate_landuse(&mut editor, way, ground_level, args);
landuse::generate_landuse(&mut editor, way, &ground, args);
} else if way.tags.contains_key("natural") {
natural::generate_natural(&mut editor, element, ground_level, args);
natural::generate_natural(&mut editor, element, &ground, args);
} else if way.tags.contains_key("amenity") {
amenities::generate_amenities(&mut editor, element, ground_level, args);
amenities::generate_amenities(&mut editor, element, &ground, args);
} else if way.tags.contains_key("leisure") {
leisure::generate_leisure(&mut editor, way, ground_level, args);
leisure::generate_leisure(&mut editor, way, &ground, args);
} else if way.tags.contains_key("barrier") {
barriers::generate_barriers(&mut editor, element, ground_level);
barriers::generate_barriers(&mut editor, element, &ground);
} else if way.tags.contains_key("waterway") {
waterways::generate_waterways(&mut editor, way, ground_level);
waterways::generate_waterways(&mut editor, way, &ground);
} else if way.tags.contains_key("bridge") {
//bridges::generate_bridges(&mut editor, way, ground_level); // TODO FIX
} else if way.tags.contains_key("railway") {
railways::generate_railways(&mut editor, way, ground_level);
railways::generate_railways(&mut editor, way, &ground);
} else if way.tags.contains_key("aeroway") || way.tags.contains_key("area:aeroway")
{
highways::generate_aeroway(&mut editor, way, ground_level);
highways::generate_aeroway(&mut editor, way, &ground);
} else if way.tags.get("service") == Some(&"siding".to_string()) {
highways::generate_siding(&mut editor, way, ground_level);
highways::generate_siding(&mut editor, way, &ground);
}
}
ProcessedElement::Node(node) => {
if node.tags.contains_key("door") || node.tags.contains_key("entrance") {
doors::generate_doors(&mut editor, node, ground_level);
doors::generate_doors(&mut editor, node, &ground);
} else if node.tags.contains_key("natural")
&& node.tags.get("natural") == Some(&"tree".to_string())
{
natural::generate_natural(&mut editor, element, ground_level, args);
natural::generate_natural(&mut editor, element, &ground, args);
} else if node.tags.contains_key("amenity") {
amenities::generate_amenities(&mut editor, element, ground_level, args);
amenities::generate_amenities(&mut editor, element, &ground, args);
} else if node.tags.contains_key("barrier") {
barriers::generate_barriers(&mut editor, element, ground_level);
barriers::generate_barriers(&mut editor, element, &ground);
} else if node.tags.contains_key("highway") {
highways::generate_highways(&mut editor, element, ground_level, args);
highways::generate_highways(&mut editor, element, &ground, args);
} else if node.tags.contains_key("tourism") {
tourisms::generate_tourisms(&mut editor, node, ground_level);
tourisms::generate_tourisms(&mut editor, node, &ground);
}
}
ProcessedElement::Relation(rel) => {
if rel.tags.contains_key("building") || rel.tags.contains_key("building:part") {
buildings::generate_building_from_relation(
&mut editor,
rel,
ground_level,
args,
);
buildings::generate_building_from_relation(&mut editor, rel, &ground, args);
} else if rel.tags.contains_key("water") {
water_areas::generate_water_areas(&mut editor, rel, ground_level);
water_areas::generate_water_areas(&mut editor, rel, &ground);
} else if rel.tags.get("leisure") == Some(&"park".to_string()) {
leisure::generate_leisure_from_relation(&mut editor, rel, &ground, args);
}
}
}
@@ -132,8 +125,8 @@ pub fn generate_world(
let mut block_counter: u64 = 0;
println!("{} Generating ground layer...", "[4/5]".bold());
emit_gui_progress_update(60.0, "Generating ground layer...");
println!("{} Generating ground...", "[4/5]".bold());
emit_gui_progress_update(60.0, "Generating ground...");
let ground_pb: ProgressBar = ProgressBar::new(total_blocks);
ground_pb.set_style(
@@ -150,24 +143,86 @@ pub fn generate_world(
let groundlayer_block = if args.winter { SNOW_BLOCK } else { GRASS_BLOCK };
for x in 0..=(scale_factor_x as i32) {
for z in 0..=(scale_factor_z as i32) {
editor.set_block(groundlayer_block, x, ground_level, z, None, None);
editor.set_block(DIRT, x, ground_level - 1, z, None, None);
block_counter += 1;
if block_counter % batch_size == 0 {
ground_pb.inc(batch_size);
// Differentiate between terrain and non-terrain generation
if ground.elevation_enabled {
// Pre-calculate ground levels for all points
let mut ground_levels: Vec<Vec<i32>> = Vec::with_capacity(scale_factor_x as usize + 1);
for x in 0..=(scale_factor_x as i32) {
let mut row = Vec::with_capacity(scale_factor_z as usize + 1);
for z in 0..=(scale_factor_z as i32) {
row.push(ground.level(XZPoint::new(x, z)));
}
ground_levels.push(row);
}
gui_progress_grnd += progress_increment_grnd;
if (gui_progress_grnd - last_emitted_progress).abs() > 0.25 {
emit_gui_progress_update(gui_progress_grnd, "");
last_emitted_progress = gui_progress_grnd;
// Process blocks in larger batches
for x in 0..=(scale_factor_x as i32) {
for z in 0..=(scale_factor_z as i32) {
let ground_level = ground_levels[x as usize][z as usize];
// Find the highest block in this column
let max_y = (MIN_Y..ground_level)
.find(|y: &i32| editor.block_at(x, *y, z))
.unwrap_or(ground_level)
.min(ground_level);
// Set blocks in a single batch
editor.set_block(groundlayer_block, x, max_y, z, None, None);
editor.set_block(DIRT, x, max_y - 1, z, None, None);
editor.set_block(DIRT, x, max_y - 2, z, None, None);
block_counter += 1;
if block_counter % batch_size == 0 {
ground_pb.inc(batch_size);
}
gui_progress_grnd += progress_increment_grnd;
if (gui_progress_grnd - last_emitted_progress).abs() > 0.25 {
emit_gui_progress_update(gui_progress_grnd, "");
last_emitted_progress = gui_progress_grnd;
}
}
}
// Set blocks at spawn location
for x in 0..=20 {
for z in 0..=20 {
editor.set_block(groundlayer_block, x, -62, z, None, None);
}
}
} else {
for x in 0..=(scale_factor_x as i32) {
for z in 0..=(scale_factor_z as i32) {
let ground_level = ground.level(XZPoint::new(x, z));
editor.set_block(groundlayer_block, x, ground_level, z, None, None);
editor.set_block(DIRT, x, ground_level - 1, z, None, None);
block_counter += 1;
if block_counter % batch_size == 0 {
ground_pb.inc(batch_size);
}
gui_progress_grnd += progress_increment_grnd;
if (gui_progress_grnd - last_emitted_progress).abs() > 0.25 {
emit_gui_progress_update(gui_progress_grnd, "");
last_emitted_progress = gui_progress_grnd;
}
}
}
}
// Set sign for player orientation
/*editor.set_sign(
"↑".to_string(),
"Generated World".to_string(),
"This direction".to_string(),
"".to_string(),
9,
-61,
9,
6,
);*/
ground_pb.inc(block_counter % batch_size);
ground_pb.finish();

View File

@@ -1,14 +1,16 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::ProcessedElement;
use crate::world_editor::WorldEditor;
pub fn generate_amenities(
editor: &mut WorldEditor,
element: &ProcessedElement,
ground_level: i32,
ground: &Ground,
args: &Args,
) {
// Skip if 'layer' or 'level' is negative in the tags
@@ -25,21 +27,23 @@ pub fn generate_amenities(
}
if let Some(amenity_type) = element.tags().get("amenity") {
let first_node: Option<(i32, i32)> = element
let first_node: Option<XZPoint> = element
.nodes()
.map(|n: &crate::osm_parser::ProcessedNode| (n.x, n.z))
.map(|n: &crate::osm_parser::ProcessedNode| XZPoint::new(n.x, n.z))
.next();
match amenity_type.as_str() {
"waste_disposal" | "waste_basket" => {
// Place a cauldron for waste disposal or waste basket
if let Some((x, z)) = first_node {
editor.set_block(CAULDRON, x, ground_level + 1, z, None, None);
if let Some(pt) = first_node {
editor.set_block(CAULDRON, pt.x, ground.level(pt) + 1, pt.z, None, None);
}
}
"vending_machine" | "atm" => {
if let Some((x, z)) = first_node {
editor.set_block(IRON_BLOCK, x, ground_level + 1, z, None, None);
editor.set_block(IRON_BLOCK, x, ground_level + 2, z, None, None);
if let Some(pt) = first_node {
let y = ground.level(pt);
editor.set_block(IRON_BLOCK, pt.x, y + 1, pt.z, None, None);
editor.set_block(IRON_BLOCK, pt.x, y + 2, pt.z, None, None);
}
}
"bicycle_parking" => {
@@ -53,9 +57,18 @@ pub fn generate_amenities(
let floor_area: Vec<(i32, i32)> =
flood_fill_area(&polygon_coords, args.timeout.as_ref());
let pts: Vec<_> = floor_area.iter().map(|c| XZPoint::new(c.0, c.1)).collect();
if pts.is_empty() {
return;
}
let y_min = ground.min_level(pts.iter().cloned()).unwrap();
let roof_y = ground.max_level(pts.iter().cloned()).unwrap() + 5;
// Fill the floor area
for (x, z) in floor_area.iter() {
editor.set_block(ground_block, *x, ground_level, *z, None, None);
editor.set_block(ground_block, *x, y_min, *z, None, None);
}
// Place fences and roof slabs at each corner node directly
@@ -63,37 +76,79 @@ pub fn generate_amenities(
let x: i32 = node.x;
let z: i32 = node.z;
for y in 1..=4 {
editor.set_block(ground_block, x, ground_level, z, None, None);
editor.set_block(OAK_FENCE, x, ground_level + y, z, None, None);
let pt = XZPoint::new(x, z);
let y = ground.level(pt);
editor.set_block(ground_block, x, y, z, None, None);
for cur_y in (y_min + 1)..roof_y {
editor.set_block(OAK_FENCE, x, cur_y, z, None, None);
}
editor.set_block(roof_block, x, ground_level + 5, z, None, None);
editor.set_block(roof_block, x, roof_y, z, None, None);
}
// Flood fill the roof area
let roof_height: i32 = ground_level + 5;
for (x, z) in floor_area.iter() {
editor.set_block(roof_block, *x, roof_height, *z, None, None);
editor.set_block(roof_block, *x, roof_y, *z, None, None);
}
}
"bench" => {
// Place a bench
if let Some((x, z)) = first_node {
editor.set_block(SMOOTH_STONE, x, ground_level + 1, z, None, None);
editor.set_block(OAK_LOG, x + 1, ground_level + 1, z, None, None);
editor.set_block(OAK_LOG, x - 1, ground_level + 1, z, None, None);
if let Some(pt) = first_node {
let y = ground.level(pt) + 1;
editor.set_block(SMOOTH_STONE, pt.x, y, pt.z, None, None);
editor.set_block(OAK_LOG, pt.x + 1, y, pt.z, None, None);
editor.set_block(OAK_LOG, pt.x - 1, y, pt.z, None, None);
}
}
"vending" => {
// Place vending machine blocks
if let Some((x, z)) = first_node {
editor.set_block(IRON_BLOCK, x, ground_level + 1, z, None, None);
editor.set_block(IRON_BLOCK, x, ground_level + 2, z, None, None);
if let Some(pt) = first_node {
let y = ground.level(pt);
editor.set_block(IRON_BLOCK, pt.x, y + 1, pt.z, None, None);
editor.set_block(IRON_BLOCK, pt.x, y + 2, pt.z, None, None);
}
}
"shelter" => {
let roof_block: Block = STONE_BRICK_SLAB;
let polygon_coords: Vec<(i32, i32)> = element
.nodes()
.map(|n: &crate::osm_parser::ProcessedNode| (n.x, n.z))
.collect();
let roof_area: Vec<(i32, i32)> =
flood_fill_area(&polygon_coords, args.timeout.as_ref());
// Place fences and roof slabs at each corner node directly
for node in element.nodes() {
let x: i32 = node.x;
let z: i32 = node.z;
let Some(y) = ground.min_level(element.nodes().map(|n| n.xz())) else {
return;
};
for fence_height in 1..=4 {
editor.set_block(OAK_FENCE, x, y + fence_height, z, None, None);
}
editor.set_block(roof_block, x, y + 5, z, None, None);
}
// Flood fill the roof area
let Some(y) = ground.min_level(element.nodes().map(|n| n.xz())) else {
return;
};
let roof_height: i32 = y + 5;
for (x, z) in roof_area.iter() {
editor.set_block(roof_block, *x, roof_height, *z, None, None);
}
}
"parking" | "fountain" => {
// Process parking or fountain areas
let mut previous_node: Option<(i32, i32)> = None;
let mut previous_node: Option<XZPoint> = None;
let mut corner_addup: (i32, i32, i32) = (0, 0, 0);
let mut current_amenity: Vec<(i32, i32)> = vec![];
@@ -102,23 +157,18 @@ pub fn generate_amenities(
"parking" => GRAY_CONCRETE,
_ => GRAY_CONCRETE,
};
for node in element.nodes() {
let x: i32 = node.x;
let z: i32 = node.z;
let pt: XZPoint = node.xz();
let y = ground.level(pt);
if let Some(prev) = previous_node {
// Create borders for fountain or parking area
let prev_y = ground.level(prev);
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.0, ground_level, prev.1, x, ground_level, z);
for (bx, _, bz) in bresenham_points {
editor.set_block(
block_type,
bx,
ground_level,
bz,
Some(&[BLACK_CONCRETE]),
None,
);
bresenham_line(prev.x, prev_y, prev.z, pt.x, y, pt.z);
for (bx, by, bz) in bresenham_points {
editor.set_block(block_type, bx, by, bz, Some(&[BLACK_CONCRETE]), None);
// Decorative border around fountains
if amenity_type == "fountain" {
@@ -128,7 +178,7 @@ pub fn generate_amenities(
editor.set_block(
LIGHT_GRAY_CONCRETE,
bx + dx,
ground_level,
by,
bz + dz,
None,
None,
@@ -144,7 +194,7 @@ pub fn generate_amenities(
corner_addup.2 += 1;
}
}
previous_node = Some((x, z));
previous_node = Some(pt);
}
// Flood-fill the interior area for parking or fountains
@@ -154,10 +204,12 @@ pub fn generate_amenities(
flood_fill_area(&polygon_coords, args.timeout.as_ref());
for (x, z) in flood_area {
let pt = XZPoint::new(x, z);
let y = ground.level(pt);
editor.set_block(
block_type,
x,
ground_level,
y,
z,
Some(&[BLACK_CONCRETE, GRAY_CONCRETE]),
None,
@@ -168,7 +220,7 @@ pub fn generate_amenities(
editor.set_block(
LIGHT_GRAY_CONCRETE,
x,
ground_level,
y,
z,
Some(&[BLACK_CONCRETE, GRAY_CONCRETE]),
None,

View File

@@ -1,66 +1,117 @@
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::ground::Ground;
use crate::osm_parser::ProcessedElement;
use crate::world_editor::WorldEditor;
pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement, ground_level: i32) {
if let Some(barrier_type) = element.tags().get("barrier") {
if barrier_type == "bollard" {
pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement, ground: &Ground) {
// Default values
let mut barrier_material: Block = COBBLESTONE_WALL;
let mut barrier_height: i32 = 2;
match element.tags().get("barrier").map(|s| s.as_str()) {
Some("bollard") => {
if let ProcessedElement::Node(node) = element {
editor.set_block(
COBBLESTONE_WALL,
node.x,
ground_level + 1,
ground.level(node.xz()) + 1,
node.z,
None,
None,
);
// Place bollard
}
} else if barrier_type == "kerb" {
return;
}
Some("kerb") => {
// Ignore kerbs
return;
} else if let ProcessedElement::Way(way) = element {
// Determine wall height
let wall_height: i32 = element
.tags()
.get("height")
.and_then(|height: &String| height.parse::<f32>().ok())
.map(|height: f32| f32::min(3.0, height).round() as i32)
.unwrap_or(2); // Default height is 2 if not specified or invalid
}
Some("hedge") => {
barrier_material = OAK_LEAVES;
barrier_height = 2;
}
Some("fence") => {
// Handle fence sub-types
match element.tags().get("fence_type").map(|s| s.as_str()) {
Some("railing" | "bars" | "krest") => {
barrier_material = STONE_BRICK_WALL;
barrier_height = 1;
}
Some("chain_link" | "metal" | "wire" | "barbed_wire" | "corrugated_metal") => {
barrier_material = STONE_BRICK_WALL;
barrier_height = 2;
}
Some("slatted" | "paling") => {
barrier_material = OAK_FENCE;
barrier_height = 1;
}
Some("wood" | "split_rail" | "panel" | "pole") => {
barrier_material = OAK_FENCE;
barrier_height = 2;
}
Some("concrete") => {
barrier_material = ANDESITE_WALL;
barrier_height = 2;
}
Some("glass") => {
barrier_material = GLASS;
barrier_height = 1;
}
_ => {}
}
}
_ => {}
}
// Tagged material takes priority over inferred
if let Some(barrier_mat) = element.tags().get("material") {
if barrier_mat == "brick" {
barrier_material = BRICK;
}
}
// Process nodes to create the barrier wall
for i in 1..way.nodes.len() {
let prev: &crate::osm_parser::ProcessedNode = &way.nodes[i - 1];
let x1: i32 = prev.x;
let z1: i32 = prev.z;
if let ProcessedElement::Way(way) = element {
// Determine wall height
let wall_height: i32 = element
.tags()
.get("height")
.and_then(|height: &String| height.parse::<f32>().ok())
.map(|height: f32| f32::min(3.0, height).round() as i32)
.unwrap_or(barrier_height);
let cur: &crate::osm_parser::ProcessedNode = &way.nodes[i];
let x2: i32 = cur.x;
let z2: i32 = cur.z;
// Process nodes to create the barrier wall
for i in 1..way.nodes.len() {
let prev: &crate::osm_parser::ProcessedNode = &way.nodes[i - 1];
let x1: i32 = prev.x;
let z1: i32 = prev.z;
// Generate the line of coordinates between the two nodes
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(x1, ground_level, z1, x2, ground_level, z2);
let cur: &crate::osm_parser::ProcessedNode = &way.nodes[i];
let x2: i32 = cur.x;
let z2: i32 = cur.z;
for (bx, _, bz) in bresenham_points {
// Build the barrier wall to the specified height
for y in (ground_level + 1)..=(ground_level + wall_height) {
editor.set_block(COBBLESTONE_WALL, bx, y, bz, None, None);
// Barrier wall
}
// Generate the line of coordinates between the two nodes
let bresenham_points: Vec<(i32, i32, i32)> = bresenham_line(x1, 0, z1, x2, 0, z2);
// Add an optional top to the barrier if the height is more than 1
if wall_height > 1 {
editor.set_block(
STONE_BRICK_SLAB,
bx,
ground_level + wall_height + 1,
bz,
None,
None,
); // Top of the barrier
}
for (bx, _, bz) in bresenham_points {
// Build the barrier wall to the specified height
let ground_level = ground.level(XZPoint::new(bx, bz));
for y in (ground_level + 1)..=(ground_level + wall_height) {
editor.set_block(barrier_material, bx, y, bz, None, None);
// Barrier wall
}
// Add an optional top to the barrier if the height is more than 1
if wall_height > 1 {
editor.set_block(
STONE_BRICK_SLAB,
bx,
ground_level + wall_height + 1,
bz,
None,
None,
); // Top of the barrier
}
}
}

View File

@@ -1,5 +1,6 @@
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
//use crate::ground::Ground;
use crate::osm_parser::ProcessedWay;
use crate::world_editor::WorldEditor;

View File

@@ -1,8 +1,10 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::colors::{color_text_to_rgb_tuple, rgb_distance, RGBTuple};
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::{ProcessedMemberRole, ProcessedRelation, ProcessedWay};
use crate::world_editor::WorldEditor;
use rand::Rng;
@@ -12,17 +14,23 @@ use std::time::Duration;
pub fn generate_buildings(
editor: &mut WorldEditor,
element: &ProcessedWay,
ground_level: i32,
ground: &Ground,
args: &Args,
relation_levels: Option<i32>,
) {
// Adjust starting height based on building:min_level
let Some(base_y) = ground.min_level(element.nodes.iter().map(|n| n.xz())) else {
return;
};
// Get min_level first so we can use it both for start_level and building height calculations
let min_level = if let Some(min_level_str) = element.tags.get("building:min_level") {
min_level_str.parse::<i32>().unwrap_or(0)
} else {
0
};
let start_level = ground_level + (min_level * 4);
// Calculate starting level using base_y and min_level
let start_level = base_y + (min_level * 4);
let mut previous_node: Option<(i32, i32)> = None;
let mut corner_addup: (i32, i32, i32) = (0, 0, 0);
@@ -132,14 +140,22 @@ pub fn generate_buildings(
let x: i32 = node.x;
let z: i32 = node.z;
for y in 1..=4 {
editor.set_block(OAK_FENCE, x, ground_level + y, z, None, None);
let Some(y) = ground.min_level(element.nodes.iter().map(|n| n.xz())) else {
return;
};
for shelter_y in 1..=4 {
editor.set_block(OAK_FENCE, x, shelter_y + y, z, None, None);
}
editor.set_block(roof_block, x, ground_level + 5, z, None, None);
editor.set_block(roof_block, x, y + 5, z, None, None);
}
// Flood fill the roof area
let roof_height: i32 = ground_level + 5;
let Some(y) = ground.min_level(element.nodes.iter().map(|n| n.xz())) else {
return;
};
let roof_height: i32 = y + 5;
for (x, z) in roof_area.iter() {
editor.set_block(roof_block, *x, roof_height, *z, None, None);
}
@@ -166,9 +182,13 @@ pub fn generate_buildings(
let floor_area: Vec<(i32, i32)> =
flood_fill_area(&polygon_coords, args.timeout.as_ref());
let Some(y) = ground.min_level(element.nodes.iter().map(|n| n.xz())) else {
return;
};
// Fill the floor area
for (x, z) in floor_area.iter() {
editor.set_block(ground_block, *x, ground_level, *z, None, None);
editor.set_block(ground_block, *x, y, *z, None, None);
}
// Place fences and roof slabs at each corner node directly
@@ -176,15 +196,14 @@ pub fn generate_buildings(
let x: i32 = node.x;
let z: i32 = node.z;
for y in 1..=4 {
editor.set_block(ground_block, x, ground_level, z, None, None);
editor.set_block(OAK_FENCE, x, ground_level + y, z, None, None);
for dy in 1..=4 {
editor.set_block(OAK_FENCE, x, y + dy, z, None, None);
}
editor.set_block(roof_block, x, ground_level + 5, z, None, None);
editor.set_block(roof_block, x, y + 5, z, None, None);
}
// Flood fill the roof area
let roof_height: i32 = ground_level + 5;
let roof_height: i32 = y + 5;
for (x, z) in floor_area.iter() {
editor.set_block(roof_block, *x, roof_height, *z, None, None);
}
@@ -210,6 +229,10 @@ pub fn generate_buildings(
let floor_area: Vec<(i32, i32)> =
flood_fill_area(&polygon_coords, args.timeout.as_ref());
let Some(ground_level) = ground.min_level(element.nodes.iter().map(|n| n.xz())) else {
return;
};
for level in 0..=(building_height / 4) {
let current_level = ground_level + level * 4;
@@ -282,6 +305,9 @@ pub fn generate_buildings(
return;
} else if building_type == "roof" {
let Some(ground_level) = ground.min_level(element.nodes.iter().map(|n| n.xz())) else {
return;
};
let roof_height: i32 = ground_level + 5;
// Iterate through the nodes to create the roof edges using Bresenham's line algorithm
@@ -332,7 +358,7 @@ pub fn generate_buildings(
building_height = ((23.0 * scale_factor) as i32).max(3);
}
} else if building_type == "bridge" {
generate_bridge(editor, element, ground_level, args.timeout.as_ref());
generate_bridge(editor, element, ground, args.timeout.as_ref());
return;
}
}
@@ -344,24 +370,22 @@ pub fn generate_buildings(
if let Some(prev) = previous_node {
// Calculate walls and corners using Bresenham line
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.0, start_level, prev.1, x, start_level, z);
let bresenham_points = bresenham_line(prev.0, start_level, prev.1, x, start_level, z);
for (bx, _, bz) in bresenham_points {
for h in (start_level + 1)..=(start_level + building_height) {
if element.nodes[0].x == bx && element.nodes[0].x == bz {
editor.set_block(corner_block, bx, h, bz, None, None); // Corner block
// Corner Block
editor.set_block(corner_block, bx, h, bz, None, None);
} else {
// Add windows to the walls at intervals
if h > start_level + 1 && h % 4 != 0 && (bx + bz) % 6 < 3 {
editor.set_block(window_block, bx, h, bz, None, None);
// Window block
} else {
editor.set_block(wall_block, bx, h, bz, None, None);
// Wall block
}
}
}
// Ceiling cobblestone
editor.set_block(
COBBLESTONE,
bx,
@@ -374,9 +398,9 @@ pub fn generate_buildings(
if args.winter {
editor.set_block(
SNOW_LAYER,
x,
bx,
start_level + building_height + 2,
z,
bz,
None,
None,
);
@@ -401,23 +425,24 @@ pub fn generate_buildings(
for (x, z) in floor_area {
if processed_points.insert((x, z)) {
editor.set_block(floor_block, x, start_level, z, None, None); // Set floor
// Set floor at start_level
editor.set_block(floor_block, x, start_level, z, None, None);
// Set level ceilings if height > 4
if building_height > 4 {
for h in (start_level + 2 + 4..start_level + building_height).step_by(4) {
if x % 6 == 0 && z % 6 == 0 {
editor.set_block(GLOWSTONE, x, h, z, None, None); // Light fixtures
// Light fixtures
editor.set_block(GLOWSTONE, x, h, z, None, None);
} else {
editor.set_block(floor_block, x, h, z, None, None);
}
}
} else if x % 6 == 0 && z % 6 == 0 {
editor.set_block(GLOWSTONE, x, start_level + building_height, z, None, None);
// Light fixtures
}
// Set the house ceiling
// Set ceiling at proper height
editor.set_block(
floor_block,
x,
@@ -445,7 +470,7 @@ pub fn generate_buildings(
pub fn generate_building_from_relation(
editor: &mut WorldEditor,
relation: &ProcessedRelation,
ground_level: i32,
ground: &Ground,
args: &Args,
) {
// Extract levels from relation tags
@@ -458,13 +483,7 @@ pub fn generate_building_from_relation(
// Process the outer way to create the building walls
for member in &relation.members {
if member.role == ProcessedMemberRole::Outer {
generate_buildings(
editor,
&member.way,
ground_level,
args,
Some(relation_levels),
);
generate_buildings(editor, &member.way, ground, args, Some(relation_levels));
}
}
@@ -498,17 +517,9 @@ fn find_nearest_block_in_color_map(
fn generate_bridge(
editor: &mut WorldEditor,
element: &ProcessedWay,
base_level: i32,
ground: &Ground,
floodfill_timeout: Option<&Duration>,
) {
// Calculate the bridge level
let mut bridge_level: i32 = base_level;
if let Some(level_str) = element.tags.get("level") {
if let Ok(level) = level_str.parse::<i32>() {
bridge_level += (level * 3) + 1; // Adjust height by levels
}
}
let floor_block: Block = STONE;
let railing_block: Block = STONE_BRICKS;
@@ -518,26 +529,56 @@ fn generate_bridge(
let x: i32 = node.x;
let z: i32 = node.z;
// Calculate the dynamic bridge level based on the ground level
let mut bridge_level = ground.level(XZPoint::new(x, z));
// Adjust the bridge level based on the "level" tag
if let Some(level_str) = element.tags.get("level") {
if let Ok(level) = level_str.parse::<i32>() {
bridge_level += (level * 3) + 1;
}
}
// Create bridge path using Bresenham's line
if let Some(prev) = previous_node {
let bridge_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.0, bridge_level, prev.1, x, bridge_level, z);
for (bx, by, bz) in bridge_points {
// Place railing blocks
editor.set_block(railing_block, bx, by + 1, bz, None, None);
editor.set_block(railing_block, bx, by, bz, None, None);
}
}
previous_node = Some((x, z));
}
// Flood fill the area between the bridge path nodes
let polygon_coords: Vec<(i32, i32)> = element
.nodes
.iter()
.map(|n: &crate::osm_parser::ProcessedNode| (n.x, n.z))
.collect();
let bridge_area: Vec<(i32, i32)> = flood_fill_area(&polygon_coords, floodfill_timeout);
for (x, z) in bridge_area {
editor.set_block(floor_block, x, bridge_level, z, None, None);
let polygon_coords: Vec<XZPoint> = element.nodes.iter().map(|n| n.xz()).collect();
let bridge_area: Vec<XZPoint> = flood_fill_area(
&polygon_coords
.iter()
.map(|pt| (pt.x, pt.z))
.collect::<Vec<_>>(),
floodfill_timeout,
)
.into_iter()
.map(|(x, z)| XZPoint::new(x, z))
.collect();
for pt in bridge_area {
// Calculate the bridge's floor level dynamically
let mut bridge_level = ground.level(pt);
// Adjust the bridge level based on the "level" tag
if let Some(level_str) = element.tags.get("level") {
if let Ok(level) = level_str.parse::<i32>() {
bridge_level += (level * 3) + 1;
}
}
// Place floor blocks
editor.set_block(floor_block, pt.x, bridge_level, pt.z, None, None);
}
}

View File

@@ -1,8 +1,10 @@
use crate::block_definitions::*;
use crate::cartesian::XZPoint;
use crate::ground::Ground;
use crate::osm_parser::ProcessedNode;
use crate::world_editor::WorldEditor;
pub fn generate_doors(editor: &mut WorldEditor, element: &ProcessedNode, ground_level: i32) {
pub fn generate_doors(editor: &mut WorldEditor, element: &ProcessedNode, ground: &Ground) {
// Check if the element is a door or entrance
if element.tags.contains_key("door") || element.tags.contains_key("entrance") {
// Check for the "level" tag and skip doors that are not at ground level
@@ -17,6 +19,9 @@ pub fn generate_doors(editor: &mut WorldEditor, element: &ProcessedNode, ground_
let x: i32 = element.x;
let z: i32 = element.z;
// Calculate the dynamic ground level
let ground_level = ground.level(XZPoint::new(x, z));
// Set the ground block and the door blocks
editor.set_block(GRAY_CONCRETE, x, ground_level, z, None, None);
editor.set_block(DARK_OAK_DOOR_LOWER, x, ground_level + 1, z, None, None);

View File

@@ -1,14 +1,16 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::{ProcessedElement, ProcessedWay};
use crate::world_editor::WorldEditor;
pub fn generate_highways(
editor: &mut WorldEditor,
element: &ProcessedElement,
ground_level: i32,
ground: &Ground,
args: &Args,
) {
if let Some(highway_type) = element.tags().get("highway") {
@@ -16,11 +18,12 @@ pub fn generate_highways(
// Handle street lamps
if let ProcessedElement::Node(first_node) = element {
let x: i32 = first_node.x;
let y: i32 = ground.level(first_node.xz());
let z: i32 = first_node.z;
for y in 1..=4 {
editor.set_block(OAK_FENCE, x, ground_level + y, z, None, None);
for dy in 1..=4 {
editor.set_block(OAK_FENCE, x, y + dy, z, None, None);
}
editor.set_block(GLOWSTONE, x, ground_level + 5, z, None, None);
editor.set_block(GLOWSTONE, x, y + 5, z, None, None);
}
} else if highway_type == "crossing" {
// Handle traffic signals for crossings
@@ -28,17 +31,19 @@ pub fn generate_highways(
if crossing_type == "traffic_signals" {
if let ProcessedElement::Node(node) = element {
let x: i32 = node.x;
let y: i32 = ground.level(node.xz());
let z: i32 = node.z;
for y in 1..=3 {
editor.set_block(COBBLESTONE_WALL, x, ground_level + y, z, None, None);
for dy in 1..=3 {
editor.set_block(COBBLESTONE_WALL, x, y + dy, z, None, None);
}
editor.set_block(GREEN_WOOL, x, ground_level + 4, z, None, None);
editor.set_block(YELLOW_WOOL, x, ground_level + 5, z, None, None);
editor.set_block(RED_WOOL, x, ground_level + 6, z, None, None);
editor.set_block(GREEN_WOOL, x, y + 4, z, None, None);
editor.set_block(YELLOW_WOOL, x, y + 5, z, None, None);
editor.set_block(RED_WOOL, x, y + 6, z, None, None);
if args.winter {
editor.set_block(SNOW_LAYER, x, ground_level + 7, z, None, None);
editor.set_block(SNOW_LAYER, x, y + 7, z, None, None);
}
}
}
@@ -46,14 +51,15 @@ pub fn generate_highways(
} else if highway_type == "bus_stop" {
// Handle bus stops
if let ProcessedElement::Node(node) = element {
let x: i32 = node.x;
let z: i32 = node.z;
for y in 1..=3 {
editor.set_block(COBBLESTONE_WALL, x, ground_level + y, z, None, None);
let x = node.x;
let y = ground.level(node.xz());
let z = node.z;
for dy in 1..=3 {
editor.set_block(COBBLESTONE_WALL, x, y + dy, z, None, None);
}
editor.set_block(WHITE_WOOL, x, ground_level + 4, z, None, None);
editor.set_block(WHITE_WOOL, x + 1, ground_level + 4, z, None, None);
editor.set_block(WHITE_WOOL, x, y + 4, z, None, None);
editor.set_block(WHITE_WOOL, x + 1, y + 4, z, None, None);
}
} else if element
.tags()
@@ -99,7 +105,14 @@ pub fn generate_highways(
flood_fill_area(&polygon_coords, args.timeout.as_ref());
for (x, z) in filled_area {
editor.set_block(surface_block, x, ground_level, z, None, None);
editor.set_block(
surface_block,
x,
ground.level(XZPoint::new(x, z)),
z,
None,
None,
);
}
} else {
let mut previous_node: Option<(i32, i32)> = None;
@@ -132,7 +145,10 @@ pub fn generate_highways(
}
"motorway" | "primary" => {
block_range = 5;
add_stripe = true; // Add stripes for motorways and primary roads
add_stripe = true;
}
"tertiary" => {
add_stripe = true;
}
"track" => {
block_range = 1;
@@ -166,8 +182,10 @@ pub fn generate_highways(
let z2: i32 = node.z;
// Generate the line of coordinates between the two nodes
// we don't care about the y because it's going to get overwritten
// I'm not sure if we'll keep it this way
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(x1, ground_level, z1, x2, ground_level, z2);
bresenham_line(x1, 0, z1, x2, 0, z2);
// Variables to manage dashed line pattern
let mut stripe_length: i32 = 0;
@@ -192,7 +210,7 @@ pub fn generate_highways(
editor.set_block(
WHITE_CONCRETE,
set_x,
ground_level,
ground.level(XZPoint::new(set_x, set_z)),
set_z,
Some(&[BLACK_CONCRETE]),
None,
@@ -201,7 +219,7 @@ pub fn generate_highways(
editor.set_block(
BLACK_CONCRETE,
set_x,
ground_level,
ground.level(XZPoint::new(set_x, set_z)),
set_z,
None,
None,
@@ -211,7 +229,7 @@ pub fn generate_highways(
editor.set_block(
WHITE_CONCRETE,
set_x,
ground_level,
ground.level(XZPoint::new(set_x, set_z)),
set_z,
Some(&[BLACK_CONCRETE]),
None,
@@ -220,7 +238,7 @@ pub fn generate_highways(
editor.set_block(
BLACK_CONCRETE,
set_x,
ground_level,
ground.level(XZPoint::new(set_x, set_z)),
set_z,
None,
None,
@@ -230,7 +248,7 @@ pub fn generate_highways(
editor.set_block(
block_type,
set_x,
ground_level,
ground.level(XZPoint::new(set_x, set_z)),
set_z,
None,
Some(&[BLACK_CONCRETE, WHITE_CONCRETE]),
@@ -247,7 +265,7 @@ pub fn generate_highways(
editor.set_block(
WHITE_CONCRETE,
stripe_x,
ground_level,
ground.level(XZPoint::new(stripe_x, stripe_z)),
stripe_z,
Some(&[BLACK_CONCRETE]),
None,
@@ -269,48 +287,62 @@ pub fn generate_highways(
}
/// Generates a siding using stone brick slabs
pub fn generate_siding(editor: &mut WorldEditor, element: &ProcessedWay, ground_level: i32) {
let mut previous_node: Option<(i32, i32)> = None;
pub fn generate_siding(editor: &mut WorldEditor, element: &ProcessedWay, ground: &Ground) {
let mut previous_node: Option<XZPoint> = None;
let siding_block: Block = STONE_BRICK_SLAB;
for node in &element.nodes {
let x: i32 = node.x;
let z: i32 = node.z;
let current_node = node.xz();
// Draw the siding using Bresenham's line algorithm between nodes
if let Some(prev) = previous_node {
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.0, ground_level + 1, prev.1, x, ground_level + 1, z);
for (bx, by, bz) in bresenham_points {
if let Some(prev_node) = previous_node {
let bresenham_points: Vec<(i32, i32, i32)> = bresenham_line(
prev_node.x,
0,
prev_node.z,
current_node.x,
0,
current_node.z,
);
for (bx, _, bz) in bresenham_points {
let ground_level = ground.level(XZPoint::new(bx, bz)) + 1;
if !editor.check_for_block(
bx,
by - 1,
ground_level - 1,
bz,
None,
Some(&[BLACK_CONCRETE, WHITE_CONCRETE]),
) {
editor.set_block(siding_block, bx, by, bz, None, None);
editor.set_block(siding_block, bx, ground_level, bz, None, None);
}
}
}
previous_node = Some((x, z));
previous_node = Some(current_node);
}
}
/// Generates an aeroway
pub fn generate_aeroway(editor: &mut WorldEditor, way: &ProcessedWay, ground_level: i32) {
pub fn generate_aeroway(editor: &mut WorldEditor, way: &ProcessedWay, ground: &Ground) {
let mut previous_node: Option<(i32, i32)> = None;
let surface_block = LIGHT_GRAY_CONCRETE;
for node in &way.nodes {
if let Some(prev) = previous_node {
let points = bresenham_line(prev.0, ground_level, prev.1, node.x, ground_level, node.z);
let (x1, z1) = prev;
let x2 = node.x;
let z2 = node.z;
let points = bresenham_line(x1, 0, z1, x2, 0, z2);
for (x, y, z) in points {
for dx in -12..=1 {
for dz in -12..=1 {
editor.set_block(surface_block, x + dx, y, z + dz, None, None);
for (x, _, z) in points {
for dx in -12..=12 {
for dz in -12..=12 {
let set_x = x + dx;
let set_z = z + dz;
let y = ground.level(XZPoint::new(set_x, set_z));
editor.set_block(surface_block, set_x, y, set_z, None, None);
}
}
}

View File

@@ -1,8 +1,9 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::element_processing::tree::create_tree;
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::ProcessedWay;
use crate::world_editor::WorldEditor;
use rand::Rng;
@@ -10,13 +11,9 @@ use rand::Rng;
pub fn generate_landuse(
editor: &mut WorldEditor,
element: &ProcessedWay,
ground_level: i32,
ground: &Ground,
args: &Args,
) {
let mut previous_node: Option<(i32, i32)> = None;
let mut corner_addup: (i32, i32, i32) = (0, 0, 0);
let mut current_landuse: Vec<(i32, i32)> = vec![];
// Determine block type based on landuse tag
let binding: String = "".to_string();
let landuse_tag: &String = element.tags.get("landuse").unwrap_or(&binding);
@@ -56,330 +53,293 @@ pub fn generate_landuse(
}
};
let bresenham_block: Block = if args.winter { SNOW_BLOCK } else { GRASS_BLOCK };
// Get the area of the landuse element
let polygon_coords: Vec<(i32, i32)> = element.nodes.iter().map(|n| (n.x, n.z)).collect();
let floor_area: Vec<(i32, i32)> = flood_fill_area(&polygon_coords, args.timeout.as_ref());
// Process landuse nodes to fill the area
for node in &element.nodes {
let x: i32 = node.x;
let z: i32 = node.z;
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
if let Some(prev) = previous_node {
// Generate the line of coordinates between the two nodes
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.0, ground_level, prev.1, x, ground_level, z);
for (bx, _, bz) in bresenham_points {
editor.set_block(bresenham_block, bx, ground_level, bz, None, None);
}
current_landuse.push((x, z));
corner_addup = (corner_addup.0 + x, corner_addup.1 + z, corner_addup.2 + 1);
for (x, z) in floor_area {
let ground_level = ground.level(XZPoint::new(x, z));
if landuse_tag == "traffic_island" {
editor.set_block(block_type, x, ground_level + 1, z, None, None);
} else if landuse_tag == "construction" || landuse_tag == "railway" {
editor.set_block(block_type, x, ground_level, z, None, Some(&[SPONGE]));
} else {
editor.set_block(block_type, x, ground_level, z, None, None);
}
previous_node = Some((x, z));
}
// If there are landuse nodes, flood-fill the area
if !current_landuse.is_empty() {
let polygon_coords: Vec<(i32, i32)> = element.nodes.iter().map(|n| (n.x, n.z)).collect();
let floor_area: Vec<(i32, i32)> = flood_fill_area(&polygon_coords, args.timeout.as_ref());
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
for (x, z) in floor_area {
if landuse_tag == "traffic_island" {
editor.set_block(block_type, x, ground_level + 1, z, None, None);
} else if landuse_tag == "construction" || landuse_tag == "railway" {
editor.set_block(block_type, x, ground_level, z, None, Some(&[SPONGE]));
} else {
editor.set_block(block_type, x, ground_level, z, None, None);
}
// Add specific features for different landuse types
match landuse_tag.as_str() {
"cemetery" => {
if (x % 3 == 0) && (z % 3 == 0) {
let random_choice: i32 = rng.gen_range(0..100);
if random_choice < 15 {
// Place graves
if editor.check_for_block(x, ground_level, z, Some(&[PODZOL]), None) {
if rng.gen_bool(0.5) {
editor.set_block(
COBBLESTONE,
x - 1,
ground_level + 1,
z,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x - 1,
ground_level + 2,
z,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 1,
z,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x + 1,
ground_level + 1,
z,
None,
None,
);
} else {
editor.set_block(
COBBLESTONE,
x,
ground_level + 1,
z - 1,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 2,
z - 1,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 1,
z,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 1,
z + 1,
None,
None,
);
}
}
} else if random_choice < 30 {
if editor.check_for_block(x, ground_level, z, Some(&[PODZOL]), None) {
editor.set_block(RED_FLOWER, x, ground_level + 1, z, None, None);
}
} else if random_choice < 33 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
}
}
}
"forest" => {
if !editor.check_for_block(x, ground_level, z, None, Some(&[WATER])) {
let random_choice: i32 = rng.gen_range(0..21);
if random_choice == 20 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
} else if random_choice == 2 {
let flower_block: Block = match rng.gen_range(1..=4) {
1 => RED_FLOWER,
2 => BLUE_FLOWER,
3 => YELLOW_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_block, x, ground_level + 1, z, None, None);
} else if random_choice <= 1 {
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
}
}
}
"farmland" => {
// Check if the current block is not water or another undesired block
if !editor.check_for_block(x, ground_level, z, None, Some(&[WATER])) {
if x % 15 == 0 || z % 15 == 0 {
// Place water on the edges
editor.set_block(WATER, x, ground_level, z, Some(&[FARMLAND]), None);
editor.set_block(
AIR,
x,
ground_level + 1,
z,
Some(&[GRASS, WHEAT, CARROTS, POTATOES]),
None,
);
} else {
// Set the block below as farmland
editor.set_block(FARMLAND, x, ground_level, z, None, None);
// If a random condition is met, place a special object
if rng.gen_range(0..76) == 0 {
let special_choice: i32 = rng.gen_range(1..=10);
if special_choice <= 2 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
} else if special_choice <= 6 {
editor.set_block(HAY_BALE, x, ground_level + 1, z, None, None);
} else {
editor.set_block(
OAK_LEAVES,
x,
ground_level + 1,
z,
None,
None,
);
}
} else {
// Set crops only if the block below is farmland
if editor.check_for_block(
x,
ground_level,
// Add specific features for different landuse types
match landuse_tag.as_str() {
"cemetery" => {
if (x % 3 == 0) && (z % 3 == 0) {
let random_choice: i32 = rng.gen_range(0..100);
if random_choice < 15 {
// Place graves
if editor.check_for_block(x, ground_level, z, Some(&[PODZOL]), None) {
if rng.gen_bool(0.5) {
editor.set_block(
COBBLESTONE,
x - 1,
ground_level + 1,
z,
Some(&[FARMLAND]),
None,
) {
let crop_choice =
[WHEAT, CARROTS, POTATOES][rng.gen_range(0..3)];
editor.set_block(
crop_choice,
x,
ground_level + 1,
z,
None,
None,
);
}
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x - 1,
ground_level + 2,
z,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 1,
z,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x + 1,
ground_level + 1,
z,
None,
None,
);
} else {
editor.set_block(
COBBLESTONE,
x,
ground_level + 1,
z - 1,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 2,
z - 1,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 1,
z,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 1,
z + 1,
None,
None,
);
}
}
}
}
"construction" => {
let random_choice: i32 = rng.gen_range(0..1501);
if random_choice < 6 {
editor.set_block(SCAFFOLDING, x, ground_level + 1, z, None, None);
if random_choice < 2 {
editor.set_block(SCAFFOLDING, x, ground_level + 2, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 3, z, None, None);
} else if random_choice < 4 {
editor.set_block(SCAFFOLDING, x, ground_level + 2, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 3, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 4, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 1, z + 1, None, None);
} else {
editor.set_block(SCAFFOLDING, x, ground_level + 2, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 3, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 4, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 5, z, None, None);
editor.set_block(SCAFFOLDING, x - 1, ground_level + 1, z, None, None);
editor.set_block(
SCAFFOLDING,
x + 1,
ground_level + 1,
z - 1,
None,
None,
);
}
} else if random_choice < 30 {
let construction_items: [Block; 11] = [
OAK_LOG,
COBBLESTONE,
GRAVEL,
GLOWSTONE,
STONE,
COBBLESTONE_WALL,
BLACK_CONCRETE,
SAND,
OAK_PLANKS,
DIRT,
BRICK,
];
editor.set_block(
construction_items[rng.gen_range(0..construction_items.len())],
if editor.check_for_block(x, ground_level, z, Some(&[PODZOL]), None) {
editor.set_block(RED_FLOWER, x, ground_level + 1, z, None, None);
}
} else if random_choice < 33 {
create_tree(
editor,
x,
ground_level + 1,
z,
None,
None,
rng.gen_range(1..=3),
args.winter,
);
} else if random_choice < 35 {
if random_choice < 30 {
editor.set_block(DIRT, x, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 2, z, None, None);
editor.set_block(DIRT, x + 1, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 1, z + 1, None, None);
} else {
editor.set_block(DIRT, x, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 2, z, None, None);
editor.set_block(DIRT, x - 1, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 1, z - 1, None, None);
}
} else if random_choice < 150 {
editor.set_block(AIR, x, ground_level, z, None, Some(&[SPONGE]));
}
}
"grass" => {
if rng.gen_range(1..=7) != 1
&& editor.check_for_block(
}
"forest" => {
if !editor.check_for_block(x, ground_level, z, None, Some(&[WATER])) {
let random_choice: i32 = rng.gen_range(0..21);
if random_choice == 20 {
create_tree(
editor,
x,
ground_level,
ground_level + 1,
z,
Some(&[GRASS_BLOCK, SNOW_BLOCK]),
None,
)
{
rng.gen_range(1..=3),
args.winter,
);
} else if random_choice == 2 {
let flower_block: Block = match rng.gen_range(1..=4) {
1 => RED_FLOWER,
2 => BLUE_FLOWER,
3 => YELLOW_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_block, x, ground_level + 1, z, None, None);
} else if random_choice <= 1 {
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
}
}
"meadow" => {
if editor.check_for_block(
}
"farmland" => {
// Check if the current block is not water or another undesired block
if !editor.check_for_block(x, ground_level, z, None, Some(&[WATER])) {
if x % 15 == 0 || z % 15 == 0 {
// Place water on the edges
editor.set_block(WATER, x, ground_level, z, Some(&[FARMLAND]), None);
editor.set_block(
AIR,
x,
ground_level + 1,
z,
Some(&[GRASS, WHEAT, CARROTS, POTATOES]),
None,
);
} else {
// Set the block below as farmland
editor.set_block(FARMLAND, x, ground_level, z, None, None);
// If a random condition is met, place a special object
if rng.gen_range(0..76) == 0 {
let special_choice: i32 = rng.gen_range(1..=10);
if special_choice <= 2 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
} else if special_choice <= 6 {
editor.set_block(
HAY_BALE,
x,
ground_level + 1,
z,
None,
Some(&[SPONGE]),
);
} else {
editor.set_block(
OAK_LEAVES,
x,
ground_level + 1,
z,
None,
Some(&[SPONGE]),
);
}
} else {
// Set crops only if the block below is farmland
if editor.check_for_block(x, ground_level, z, Some(&[FARMLAND]), None) {
let crop_choice = [WHEAT, CARROTS, POTATOES][rng.gen_range(0..3)];
editor.set_block(crop_choice, x, ground_level + 1, z, None, None);
}
}
}
}
}
"construction" => {
let random_choice: i32 = rng.gen_range(0..1501);
if random_choice < 6 {
editor.set_block(SCAFFOLDING, x, ground_level + 1, z, None, None);
if random_choice < 2 {
editor.set_block(SCAFFOLDING, x, ground_level + 2, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 3, z, None, None);
} else if random_choice < 4 {
editor.set_block(SCAFFOLDING, x, ground_level + 2, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 3, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 4, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 1, z + 1, None, None);
} else {
editor.set_block(SCAFFOLDING, x, ground_level + 2, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 3, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 4, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 5, z, None, None);
editor.set_block(SCAFFOLDING, x - 1, ground_level + 1, z, None, None);
editor.set_block(SCAFFOLDING, x + 1, ground_level + 1, z - 1, None, None);
}
} else if random_choice < 30 {
let construction_items: [Block; 11] = [
OAK_LOG,
COBBLESTONE,
GRAVEL,
GLOWSTONE,
STONE,
COBBLESTONE_WALL,
BLACK_CONCRETE,
SAND,
OAK_PLANKS,
DIRT,
BRICK,
];
editor.set_block(
construction_items[rng.gen_range(0..construction_items.len())],
x,
ground_level + 1,
z,
None,
None,
);
} else if random_choice < 35 {
if random_choice < 30 {
editor.set_block(DIRT, x, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 2, z, None, None);
editor.set_block(DIRT, x + 1, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 1, z + 1, None, None);
} else {
editor.set_block(DIRT, x, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 2, z, None, None);
editor.set_block(DIRT, x - 1, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 1, z - 1, None, None);
}
} else if random_choice < 150 {
editor.set_block(AIR, x, ground_level, z, None, Some(&[SPONGE]));
}
}
"grass" => {
if rng.gen_range(1..=7) != 1
&& editor.check_for_block(
x,
ground_level,
z,
Some(&[GRASS_BLOCK, SNOW_BLOCK]),
None,
) {
let random_choice: i32 = rng.gen_range(0..1001);
if random_choice < 5 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
} else if random_choice < 800 {
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
}
)
{
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
}
}
"meadow" => {
if editor.check_for_block(
x,
ground_level,
z,
Some(&[GRASS_BLOCK, SNOW_BLOCK]),
None,
) {
let random_choice: i32 = rng.gen_range(0..1001);
if random_choice < 5 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
} else if random_choice < 800 {
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
}
}
_ => {}
}
_ => {}
}
}
}

View File

@@ -1,16 +1,18 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::element_processing::tree::create_tree;
use crate::floodfill::flood_fill_area;
use crate::osm_parser::ProcessedWay;
use crate::ground::Ground;
use crate::osm_parser::{ProcessedMemberRole, ProcessedRelation, ProcessedWay};
use crate::world_editor::WorldEditor;
use rand::Rng;
pub fn generate_leisure(
editor: &mut WorldEditor,
element: &ProcessedWay,
ground_level: i32,
ground: &Ground,
args: &Args,
) {
if let Some(leisure_type) = element.tags.get("leisure") {
@@ -61,12 +63,12 @@ pub fn generate_leisure(
if let Some(prev) = previous_node {
// Draw a line between the current and previous node
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.0, ground_level, prev.1, node.x, ground_level, node.z);
bresenham_line(prev.0, 0, prev.1, node.x, 0, node.z);
for (bx, _, bz) in bresenham_points {
editor.set_block(
block_type,
bx,
ground_level,
ground.level(XZPoint::new(bx, bz)),
bz,
Some(&[
GRASS_BLOCK,
@@ -99,6 +101,7 @@ pub fn generate_leisure(
flood_fill_area(&polygon_coords, args.timeout.as_ref());
for (x, z) in filled_area {
let ground_level = ground.level(XZPoint::new(x, z));
editor.set_block(block_type, x, ground_level, z, Some(&[GRASS_BLOCK]), None);
// Add decorative elements for parks and gardens
@@ -192,3 +195,37 @@ pub fn generate_leisure(
}
}
}
pub fn generate_leisure_from_relation(
editor: &mut WorldEditor,
rel: &ProcessedRelation,
ground: &Ground,
args: &Args,
) {
if rel.tags.get("leisure") == Some(&"park".to_string()) {
// First generate individual ways with their original tags
for member in &rel.members {
if member.role == ProcessedMemberRole::Outer {
generate_leisure(editor, &member.way, ground, args);
}
}
// Then combine all outer ways into one
let mut combined_nodes = Vec::new();
for member in &rel.members {
if member.role == ProcessedMemberRole::Outer {
combined_nodes.extend(member.way.nodes.clone());
}
}
// Create combined way with relation tags
let combined_way = ProcessedWay {
id: rel.id,
nodes: combined_nodes,
tags: rel.tags.clone(),
};
// Generate leisure area from combined way
generate_leisure(editor, &combined_way, ground, args);
}
}

View File

@@ -1,8 +1,10 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::element_processing::tree::create_tree;
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::ProcessedElement;
use crate::world_editor::WorldEditor;
use rand::Rng;
@@ -10,7 +12,7 @@ use rand::Rng;
pub fn generate_natural(
editor: &mut WorldEditor,
element: &ProcessedElement,
ground_level: i32,
ground: &Ground,
args: &Args,
) {
if let Some(natural_type) = element.tags().get("natural") {
@@ -23,7 +25,7 @@ pub fn generate_natural(
create_tree(
editor,
x,
ground_level + 1,
ground.level(node.xz()) + 1,
z,
rng.gen_range(1..=3),
args.winter,
@@ -73,9 +75,16 @@ pub fn generate_natural(
if let Some(prev) = previous_node {
// Generate the line of coordinates between the two nodes
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.0, ground_level, prev.1, x, ground_level, z);
bresenham_line(prev.0, 0, prev.1, x, 0, z);
for (bx, _, bz) in bresenham_points {
editor.set_block(block_type, bx, ground_level, bz, None, None);
editor.set_block(
block_type,
bx,
ground.level(XZPoint::new(bx, bz)),
bz,
None,
None,
);
}
current_natural.push((x, z));
@@ -98,24 +107,19 @@ pub fn generate_natural(
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
for (x, z) in filled_area {
editor.set_block(block_type, x, ground_level, z, None, None);
let y = ground.level(XZPoint::new(x, z));
editor.set_block(block_type, x, y, z, None, None);
// Generate elements for "wood" and "tree_row"
if natural_type == "wood" || natural_type == "tree_row" {
if editor.check_for_block(x, ground_level, z, None, Some(&[WATER])) {
if editor.check_for_block(x, y, z, None, Some(&[WATER])) {
continue;
}
let random_choice: i32 = rng.gen_range(0..26);
if random_choice == 25 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
create_tree(editor, x, y + 1, z, rng.gen_range(1..=3), args.winter);
} else if random_choice == 2 {
let flower_block = match rng.gen_range(1..=4) {
1 => RED_FLOWER,
@@ -123,9 +127,9 @@ pub fn generate_natural(
3 => YELLOW_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_block, x, ground_level + 1, z, None, None);
editor.set_block(flower_block, x, y + 1, z, None, None);
} else if random_choice <= 1 {
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
editor.set_block(GRASS, x, y + 1, z, None, None);
}
}
}

View File

@@ -1,11 +1,22 @@
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::ground::Ground;
use crate::osm_parser::ProcessedWay;
use crate::world_editor::WorldEditor;
pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay, ground_level: i32) {
pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay, ground: &Ground) {
if let Some(railway_type) = element.tags.get("railway") {
if ["proposed", "abandoned", "subway", "construction"].contains(&railway_type.as_str()) {
if [
"proposed",
"abandoned",
"subway",
"construction",
"razed",
"turntable",
]
.contains(&railway_type.as_str())
{
return;
}
@@ -22,22 +33,36 @@ pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay, groun
}
for i in 1..element.nodes.len() {
let prev: &crate::osm_parser::ProcessedNode = &element.nodes[i - 1];
let x1: i32 = prev.x;
let z1: i32 = prev.z;
let prev_node = element.nodes[i - 1].xz();
let cur_node = element.nodes[i].xz();
let cur: &crate::osm_parser::ProcessedNode = &element.nodes[i];
let x2: i32 = cur.x;
let z2: i32 = cur.z;
let points = bresenham_line(prev_node.x, 0, prev_node.z, cur_node.x, 0, cur_node.z);
let smoothed_points = smooth_diagonal_rails(&points);
// Generate the line of coordinates between the two nodes
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(x1, ground_level, z1, x2, ground_level, z2);
for j in 0..smoothed_points.len() {
let (bx, _, bz) = smoothed_points[j];
let ground_level = ground.level(XZPoint::new(bx, bz));
for (bx, _, bz) in bresenham_points {
// TODO: Set direction of rail
editor.set_block(IRON_BLOCK, bx, ground_level, bz, None, None);
editor.set_block(RAIL, bx, ground_level + 1, bz, None, None);
let prev = if j > 0 {
Some(smoothed_points[j - 1])
} else {
None
};
let next = if j < smoothed_points.len() - 1 {
Some(smoothed_points[j + 1])
} else {
None
};
let rail_block = determine_rail_direction(
(bx, bz),
prev.map(|(x, _, z)| (x, z)),
next.map(|(x, _, z)| (x, z)),
);
editor.set_block(rail_block, bx, ground_level + 1, bz, None, None);
if bx % 4 == 0 {
editor.set_block(OAK_LOG, bx, ground_level, bz, None, None);
@@ -46,3 +71,109 @@ pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay, groun
}
}
}
fn smooth_diagonal_rails(points: &[(i32, i32, i32)]) -> Vec<(i32, i32, i32)> {
let mut smoothed = Vec::new();
for i in 0..points.len() {
let current = points[i];
smoothed.push(current);
if i + 1 >= points.len() {
continue;
}
let next = points[i + 1];
let (x1, y1, z1) = current;
let (x2, _, z2) = next;
// If points are diagonally adjacent
if (x2 - x1).abs() == 1 && (z2 - z1).abs() == 1 {
// Look ahead to determine best intermediate point
let look_ahead = if i + 2 < points.len() {
Some(points[i + 2])
} else {
None
};
// Look behind
let look_behind = if i > 0 { Some(points[i - 1]) } else { None };
// Choose intermediate point based on the overall curve direction
let intermediate = if let Some((prev_x, _, _prev_z)) = look_behind {
if prev_x == x1 {
// Coming from vertical, keep x constant
(x1, y1, z2)
} else {
// Coming from horizontal, keep z constant
(x2, y1, z1)
}
} else if let Some((next_x, _, _next_z)) = look_ahead {
if next_x == x2 {
// Going to vertical, keep x constant
(x2, y1, z1)
} else {
// Going to horizontal, keep z constant
(x1, y1, z2)
}
} else {
// Default to horizontal first if no context
(x2, y1, z1)
};
smoothed.push(intermediate);
}
}
smoothed
}
fn determine_rail_direction(
current: (i32, i32),
prev: Option<(i32, i32)>,
next: Option<(i32, i32)>,
) -> Block {
let (x, z) = current;
match (prev, next) {
(Some((px, pz)), Some((nx, nz))) => {
if px == nx {
RAIL_NORTH_SOUTH
} else if pz == nz {
RAIL_EAST_WEST
} else {
// Calculate relative movements
let from_prev = (px - x, pz - z);
let to_next = (nx - x, nz - z);
match (from_prev, to_next) {
// East to North or North to East
((-1, 0), (0, -1)) | ((0, -1), (-1, 0)) => RAIL_NORTH_WEST,
// West to North or North to West
((1, 0), (0, -1)) | ((0, -1), (1, 0)) => RAIL_NORTH_EAST,
// East to South or South to East
((-1, 0), (0, 1)) | ((0, 1), (-1, 0)) => RAIL_SOUTH_WEST,
// West to South or South to West
((1, 0), (0, 1)) | ((0, 1), (1, 0)) => RAIL_SOUTH_EAST,
_ => {
if (px - x).abs() > (pz - z).abs() {
RAIL_EAST_WEST
} else {
RAIL_NORTH_SOUTH
}
}
}
}
}
(Some((px, pz)), None) | (None, Some((px, pz))) => {
if px == x {
RAIL_NORTH_SOUTH
} else if pz == z {
RAIL_EAST_WEST
} else {
RAIL_NORTH_SOUTH
}
}
(None, None) => RAIL_NORTH_SOUTH,
}
}

View File

@@ -1,8 +1,10 @@
use crate::block_definitions::*;
use crate::cartesian::XZPoint;
use crate::ground::Ground;
use crate::osm_parser::ProcessedNode;
use crate::world_editor::WorldEditor;
pub fn generate_tourisms(editor: &mut WorldEditor, element: &ProcessedNode, ground_level: i32) {
pub fn generate_tourisms(editor: &mut WorldEditor, element: &ProcessedNode, ground: &Ground) {
// Skip if 'layer' or 'level' is negative in the tags
if let Some(layer) = element.tags.get("layer") {
if layer.parse::<i32>().unwrap_or(0) < 0 {
@@ -20,10 +22,15 @@ pub fn generate_tourisms(editor: &mut WorldEditor, element: &ProcessedNode, grou
let x: i32 = element.x;
let z: i32 = element.z;
// Calculate the dynamic ground level
let ground_level = ground.level(XZPoint::new(x, z));
if tourism_type == "information" {
if let Some("board") = element.tags.get("information").map(|x: &String| x.as_str()) {
// TODO draw a sign
editor.set_block(OAK_PLANKS, x, ground_level + 1, z, None, None);
// Draw an information board
// TODO draw a sign with text
editor.set_block(COBBLESTONE_WALL, x, ground_level + 1, z, None, None);
editor.set_block(OAK_PLANKS, x, ground_level + 2, z, None, None);
}
}
}

View File

@@ -3,6 +3,8 @@ use std::time::Instant;
use crate::{
block_definitions::WATER,
cartesian::XZPoint,
ground::Ground,
osm_parser::{ProcessedMemberRole, ProcessedNode, ProcessedRelation},
world_editor::WorldEditor,
};
@@ -10,7 +12,7 @@ use crate::{
pub fn generate_water_areas(
editor: &mut WorldEditor,
element: &ProcessedRelation,
ground_level: i32,
ground: &Ground,
) {
let start_time = Instant::now();
@@ -18,7 +20,7 @@ pub fn generate_water_areas(
return;
}
// don't handle water below layer 0
// Don't handle water below layer 0
if let Some(layer) = element.tags.get("layer") {
if layer.parse::<i32>().map(|x| x < 0).unwrap_or(false) {
return;
@@ -46,32 +48,16 @@ pub fn generate_water_areas(
}
let (max_x, max_z) = editor.get_max_coords();
let outers: Vec<Vec<(f64, f64)>> = outers
let outers: Vec<Vec<XZPoint>> = outers
.iter()
.map(|x: &Vec<ProcessedNode>| {
x.iter()
.map(|y: &ProcessedNode| (y.x as f64, y.z as f64))
.collect()
})
.map(|x| x.iter().map(|y| y.xz()).collect::<Vec<_>>())
.collect();
let inners: Vec<Vec<(f64, f64)>> = inners
let inners: Vec<Vec<XZPoint>> = inners
.iter()
.map(|x: &Vec<ProcessedNode>| {
x.iter()
.map(|y: &ProcessedNode| (y.x as f64, y.z as f64))
.collect()
})
.map(|x| x.iter().map(|y| y.xz()).collect::<Vec<_>>())
.collect();
inverse_floodfill(
max_x,
max_z,
outers,
inners,
editor,
ground_level,
start_time,
);
inverse_floodfill(max_x, max_z, outers, inners, editor, ground, start_time);
}
// Merges ways that share nodes into full loops
@@ -164,10 +150,10 @@ fn verify_loopy_loops(loops: &[Vec<ProcessedNode>]) -> bool {
fn inverse_floodfill(
max_x: i32,
max_z: i32,
outers: Vec<Vec<(f64, f64)>>,
inners: Vec<Vec<(f64, f64)>>,
outers: Vec<Vec<XZPoint>>,
inners: Vec<Vec<XZPoint>>,
editor: &mut WorldEditor,
ground_level: i32,
ground: &Ground,
start_time: Instant,
) {
let min_x: i32 = 0;
@@ -175,21 +161,39 @@ fn inverse_floodfill(
let inners: Vec<_> = inners
.into_iter()
.map(|x: Vec<(f64, f64)>| Polygon::new(LineString::from(x), vec![]))
.map(|x| {
Polygon::new(
LineString::from(
x.iter()
.map(|pt| (pt.x as f64, pt.z as f64))
.collect::<Vec<_>>(),
),
vec![],
)
})
.collect();
let outers: Vec<_> = outers
.into_iter()
.map(|x: Vec<(f64, f64)>| Polygon::new(LineString::from(x), vec![]))
.map(|x| {
Polygon::new(
LineString::from(
x.iter()
.map(|pt| (pt.x as f64, pt.z as f64))
.collect::<Vec<_>>(),
),
vec![],
)
})
.collect();
inverse_floodfill_recursive(
(min_x, min_z),
(max_x, max_z),
ground_level,
&outers,
&inners,
editor,
ground,
start_time,
);
}
@@ -197,10 +201,10 @@ fn inverse_floodfill(
fn inverse_floodfill_recursive(
min: (i32, i32),
max: (i32, i32),
ground_level: i32,
outers: &[Polygon],
inners: &[Polygon],
editor: &mut WorldEditor,
ground: &Ground,
start_time: Instant,
) {
// Check if we've exceeded 25 seconds
@@ -215,8 +219,8 @@ fn inverse_floodfill_recursive(
}
if (max.0 - min.0) * (max.1 - min.1) < ITERATIVE_THRES {
let ground_level = ground.level(XZPoint::new(min.0, min.1));
inverse_floodfill_iterative(min, max, ground_level, outers, inners, editor);
return;
}
@@ -238,40 +242,30 @@ fn inverse_floodfill_recursive(
if outers.iter().any(|outer: &Polygon| outer.contains(&rect))
&& !inners.iter().any(|inner: &Polygon| inner.intersects(&rect))
{
// every block in rect is water
// so we can safely just set the whole thing to water
let ground_level = ground.level(XZPoint::new(min_x, min_z));
rect_fill(min_x, max_x, min_z, max_z, ground_level, editor);
continue;
}
// When we recurse, we only really need the polygons we potentially intersect with
// This saves on processing time
let outers_intersects: Vec<_> = outers
.iter()
.filter(|poly: &&Polygon| poly.intersects(&rect))
.filter(|poly| poly.intersects(&rect))
.cloned()
.collect();
// Moving this inside the below `if` statement makes it slower for some reason.
// I assume it changes how the compiler is able to optimize it
let inners_intersects: Vec<_> = inners
.iter()
.filter(|poly: &&Polygon| poly.intersects(&rect))
.filter(|poly| poly.intersects(&rect))
.cloned()
.collect();
if !outers_intersects.is_empty() {
// recurse
inverse_floodfill_recursive(
(min_x, min_z),
(max_x, max_z),
ground_level,
&outers_intersects,
&inners_intersects,
editor,
ground,
start_time,
);
}

View File

@@ -1,11 +1,13 @@
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::ground::Ground;
use crate::osm_parser::ProcessedWay;
use crate::world_editor::WorldEditor;
pub fn generate_waterways(editor: &mut WorldEditor, element: &ProcessedWay, ground_level: i32) {
pub fn generate_waterways(editor: &mut WorldEditor, element: &ProcessedWay, ground: &Ground) {
if let Some(_waterway_type) = element.tags.get("waterway") {
let mut previous_node: Option<(i32, i32)> = None;
let mut previous_node: Option<XZPoint> = None;
let mut waterway_width: i32 = 4; // Default waterway width
// Check for custom width in tags
@@ -20,6 +22,8 @@ pub fn generate_waterways(editor: &mut WorldEditor, element: &ProcessedWay, grou
// Process nodes to create waterways
for node in &element.nodes {
let current_node = node.xz();
if let Some(prev) = previous_node {
// Skip layers below the ground level
if !matches!(
@@ -28,11 +32,16 @@ pub fn generate_waterways(editor: &mut WorldEditor, element: &ProcessedWay, grou
) {
// Draw a line between the current and previous node
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.0, ground_level, prev.1, node.x, ground_level, node.z);
bresenham_line(prev.x, 0, prev.z, current_node.x, 0, current_node.z);
for (bx, _, bz) in bresenham_points {
let ground_level = ground.level(XZPoint::new(bx, bz));
for x in (bx - waterway_width / 2)..=(bx + waterway_width / 2) {
for z in (bz - waterway_width / 2)..=(bz + waterway_width / 2) {
editor.set_block(WATER, x, ground_level, z, None, None); // Set water block
// Set water block at the ground level
editor.set_block(WATER, x, ground_level, z, None, None);
// Clear vegetation above the water
editor.set_block(
AIR,
x,
@@ -46,7 +55,7 @@ pub fn generate_waterways(editor: &mut WorldEditor, element: &ProcessedWay, grou
}
}
}
previous_node = Some((node.x, node.z));
previous_node = Some(current_node);
}
}
}

424
src/ground.rs Normal file
View File

@@ -0,0 +1,424 @@
use crate::cartesian::XZPoint;
use image::{Rgb, RgbImage};
/// Minimum Y coordinate in Minecraft (bedrock level)
const MIN_Y: i32 = -62;
/// Maximum Y coordinate in Minecraft (build height limit)
const MAX_Y: i32 = 256;
/// Scale factor for converting real elevation to Minecraft heights
const BASE_HEIGHT_SCALE: f64 = 0.6;
/// Mapbox API access token for terrain data
const MAPBOX_PUBKEY: &str =
"pk.eyJ1IjoiY3Vnb3MiLCJhIjoiY2p4Nm43MzA3MDFmZDQwcGxsMjB4Z3hnNiJ9.SQbnMASwdqZe6G4n6OMvVw";
/// Minimum zoom level for terrain tiles
const MIN_ZOOM: u8 = 10;
/// Maximum zoom level for terrain tiles
const MAX_ZOOM: u8 = 15;
/// Represents terrain data and elevation settings
pub struct Ground {
pub elevation_enabled: bool,
ground_level: i32,
elevation_data: Option<ElevationData>,
}
/// Holds processed elevation data and metadata
#[derive(Clone)]
struct ElevationData {
/// Height values in Minecraft Y coordinates
heights: Vec<Vec<i32>>,
/// Width of the elevation grid
width: usize,
/// Height of the elevation grid
height: usize,
}
impl Ground {
pub fn new(args: &crate::args::Args) -> Self {
let mut elevation_enabled: bool = args.terrain;
let elevation_data: Option<ElevationData> = if elevation_enabled && args.bbox.is_some() {
match Self::fetch_elevation_data(args.bbox.as_deref().unwrap(), args.scale) {
Ok(data) => {
if args.debug {
Self::save_debug_image(&data.heights, "elevation_debug");
}
Some(data)
}
Err(e) => {
eprintln!("Warning: Failed to fetch elevation data: {}", e);
elevation_enabled = false;
None
}
}
} else {
None
};
Self {
elevation_enabled,
ground_level: args.ground_level,
elevation_data,
}
}
/// Returns the ground level at the given coordinates
#[inline(always)]
pub fn level(&self, coord: XZPoint) -> i32 {
if !self.elevation_enabled || self.elevation_data.is_none() {
return self.ground_level;
}
let data: &ElevationData = self.elevation_data.as_ref().unwrap();
let (x_ratio, z_ratio) = self.get_data_coordinates(coord, data);
self.interpolate_height(x_ratio, z_ratio, data)
}
#[inline(always)]
pub fn min_level<I: Iterator<Item = XZPoint>>(&self, coords: I) -> Option<i32> {
if !self.elevation_enabled {
return Some(self.ground_level);
}
coords.map(|c: XZPoint| self.level(c)).min()
}
#[inline(always)]
pub fn max_level<I: Iterator<Item = XZPoint>>(&self, coords: I) -> Option<i32> {
if !self.elevation_enabled {
return Some(self.ground_level);
}
coords.map(|c: XZPoint| self.level(c)).max()
}
/// Converts game coordinates to elevation data coordinates
#[inline(always)]
fn get_data_coordinates(&self, coord: XZPoint, data: &ElevationData) -> (f64, f64) {
let x_ratio: f64 = coord.x as f64 / data.width as f64;
let z_ratio: f64 = coord.z as f64 / data.height as f64;
(x_ratio.clamp(0.0, 1.0), z_ratio.clamp(0.0, 1.0))
}
/// Interpolates height value from the elevation grid
#[inline(always)]
fn interpolate_height(&self, x_ratio: f64, z_ratio: f64, data: &ElevationData) -> i32 {
let x: usize = ((x_ratio * (data.width - 1) as f64).round() as usize).min(data.width - 1);
let z: usize = ((z_ratio * (data.height - 1) as f64).round() as usize).min(data.height - 1);
data.heights[z][x]
}
/// Calculates appropriate zoom level for the given bounding box
fn calculate_zoom_level(bbox: (f64, f64, f64, f64)) -> u8 {
let lat_diff: f64 = (bbox.2 - bbox.0).abs();
let lng_diff: f64 = (bbox.3 - bbox.1).abs();
let max_diff: f64 = lat_diff.max(lng_diff);
let zoom: u8 = (-max_diff.log2() + 20.0) as u8;
zoom.clamp(MIN_ZOOM, MAX_ZOOM)
}
fn lat_lng_to_tile(lat: f64, lng: f64, zoom: u8) -> (u32, u32) {
let lat_rad: f64 = lat.to_radians();
let n: f64 = 2.0_f64.powi(zoom as i32);
let x: u32 = ((lng + 180.0) / 360.0 * n).floor() as u32;
let y: u32 =
((1.0 - lat_rad.tan().asinh() / std::f64::consts::PI) / 2.0 * n).floor() as u32;
(x, y)
}
fn fetch_elevation_data(
bbox_str: &str,
scale: f64,
) -> Result<ElevationData, Box<dyn std::error::Error>> {
let coords: Vec<f64> = bbox_str
.split_whitespace()
.map(|s: &str| s.parse::<f64>())
.collect::<Result<Vec<f64>, _>>()?;
let (min_lat, min_lng, max_lat, max_lng) = (coords[0], coords[1], coords[2], coords[3]);
// Use OSM parser's scale calculation and apply user scale factor
let (scale_factor_z, scale_factor_x) =
crate::osm_parser::geo_distance(min_lat, max_lat, min_lng, max_lng);
let scale_factor_x: f64 = scale_factor_x * scale;
let scale_factor_z: f64 = scale_factor_z * scale;
// Calculate zoom and tiles
let zoom: u8 = Self::calculate_zoom_level((min_lat, min_lng, max_lat, max_lng));
let tiles: Vec<(u32, u32)> =
Self::get_tile_coordinates(min_lat, min_lng, max_lat, max_lng, zoom);
// Calculate tile boundaries
let x_min: &u32 = tiles.iter().map(|(x, _)| x).min().unwrap();
let x_max: &u32 = tiles.iter().map(|(x, _)| x).max().unwrap();
let y_min: &u32 = tiles.iter().map(|(_, y)| y).min().unwrap();
let y_max: &u32 = tiles.iter().map(|(_, y)| y).max().unwrap();
// Match grid dimensions with Minecraft world size
let grid_width: usize = scale_factor_x.round() as usize;
let grid_height: usize = scale_factor_z.round() as usize;
// Calculate total tile dimensions
let total_tile_width: u32 = (x_max - x_min + 1) * 256;
let total_tile_height: u32 = (y_max - y_min + 1) * 256;
// Calculate scaling factors to match the desired grid dimensions
let x_scale: f64 = grid_width as f64 / total_tile_width as f64;
let y_scale: f64 = grid_height as f64 / total_tile_height as f64;
// Initialize height grid with proper dimensions
let mut height_grid: Vec<Vec<f64>> = vec![vec![f64::NAN; grid_width]; grid_height];
let client: reqwest::blocking::Client = reqwest::blocking::Client::new();
let access_token: &str = MAPBOX_PUBKEY;
// Fetch and process each tile
for (tile_x, tile_y) in &tiles {
let url: String = format!(
"https://api.mapbox.com/v4/mapbox.terrain-rgb/{}/{}/{}.pngraw?access_token={}",
zoom, tile_x, tile_y, access_token
);
let response: reqwest::blocking::Response = client.get(&url).send()?;
let img: image::DynamicImage = image::load_from_memory(&response.bytes()?)?;
let rgb_img: image::ImageBuffer<Rgb<u8>, Vec<u8>> = img.to_rgb8();
// Calculate position in the scaled grid
let base_x: f64 = ((*tile_x - x_min) * 256) as f64;
let base_y: f64 = ((*tile_y - y_min) * 256) as f64;
// Process tile data with scaling
for (y, row) in rgb_img.rows().enumerate() {
for (x, pixel) in row.enumerate() {
let scaled_x: usize = ((base_x + x as f64) * x_scale) as usize;
let scaled_y: usize = ((base_y + y as f64) * y_scale) as usize;
if scaled_y >= grid_height || scaled_x >= grid_width {
continue;
}
let height: f64 = -10000.0
+ ((pixel[0] as f64 * 256.0 * 256.0
+ pixel[1] as f64 * 256.0
+ pixel[2] as f64)
* 0.1);
height_grid[scaled_y][scaled_x] = height;
}
}
}
// Fill in any NaN values by interpolating from nearest valid values
Self::fill_nan_values(&mut height_grid);
// Continue with the existing blur and conversion to Minecraft heights...
let blurred_heights: Vec<Vec<f64>> = Self::apply_gaussian_blur(&height_grid, 1.0);
let mut mc_heights: Vec<Vec<i32>> = Vec::with_capacity(blurred_heights.len());
// Find min/max in raw data
let mut min_height: f64 = f64::MAX;
let mut max_height: f64 = f64::MIN;
for row in &blurred_heights {
for &height in row {
min_height = min_height.min(height);
max_height = max_height.max(height);
}
}
let height_range: f64 = max_height - min_height;
// Apply scale factor to height scaling
let height_scale: f64 = BASE_HEIGHT_SCALE * scale.sqrt(); // sqrt to make height scaling less extreme
let scaled_range: f64 = height_range * height_scale;
// Convert to scaled Minecraft Y coordinates
for row in blurred_heights {
let mc_row: Vec<i32> = row
.iter()
.map(|&h| {
// Scale the height differences
let relative_height: f64 = (h - min_height) / height_range;
let scaled_height: f64 = relative_height * scaled_range;
((MIN_Y as f64 + scaled_height).round() as i32).clamp(MIN_Y, MAX_Y)
})
.collect();
mc_heights.push(mc_row);
}
Ok(ElevationData {
heights: mc_heights,
width: grid_width,
height: grid_height,
})
}
fn get_tile_coordinates(
min_lat: f64,
min_lng: f64,
max_lat: f64,
max_lng: f64,
zoom: u8,
) -> Vec<(u32, u32)> {
// Convert lat/lng to tile coordinates
let (x1, y1) = Self::lat_lng_to_tile(min_lat, min_lng, zoom);
let (x2, y2) = Self::lat_lng_to_tile(max_lat, max_lng, zoom);
let mut tiles: Vec<(u32, u32)> = Vec::new();
for x in x1.min(x2)..=x1.max(x2) {
for y in y1.min(y2)..=y1.max(y2) {
tiles.push((x, y));
}
}
tiles
}
fn apply_gaussian_blur(heights: &[Vec<f64>], sigma: f64) -> Vec<Vec<f64>> {
let kernel_size: usize = (sigma * 3.0).ceil() as usize * 2 + 1;
let kernel: Vec<f64> = Self::create_gaussian_kernel(kernel_size, sigma);
// Apply blur
let mut blurred: Vec<Vec<f64>> = heights.to_owned();
// Horizontal pass
for row in blurred.iter_mut() {
let mut temp: Vec<f64> = row.clone();
for (i, val) in temp.iter_mut().enumerate() {
let mut sum: f64 = 0.0;
let mut weight_sum: f64 = 0.0;
for (j, k) in kernel.iter().enumerate() {
let idx: i32 = i as i32 + j as i32 - kernel_size as i32 / 2;
if idx >= 0 && idx < row.len() as i32 {
sum += row[idx as usize] * k;
weight_sum += k;
}
}
*val = sum / weight_sum;
}
*row = temp;
}
// Vertical pass
let height: usize = blurred.len();
let width: usize = blurred[0].len();
for x in 0..width {
let temp: Vec<_> = blurred
.iter()
.take(height)
.map(|row: &Vec<f64>| row[x])
.collect();
for (y, row) in blurred.iter_mut().enumerate().take(height) {
let mut sum: f64 = 0.0;
let mut weight_sum: f64 = 0.0;
for (j, k) in kernel.iter().enumerate() {
let idx: i32 = y as i32 + j as i32 - kernel_size as i32 / 2;
if idx >= 0 && idx < height as i32 {
sum += temp[idx as usize] * k;
weight_sum += k;
}
}
row[x] = sum / weight_sum;
}
}
blurred
}
fn create_gaussian_kernel(size: usize, sigma: f64) -> Vec<f64> {
let mut kernel: Vec<f64> = vec![0.0; size];
let center: f64 = size as f64 / 2.0;
for (i, value) in kernel.iter_mut().enumerate() {
let x: f64 = i as f64 - center;
*value = (-x * x / (2.0 * sigma * sigma)).exp();
}
let sum: f64 = kernel.iter().sum();
for k in kernel.iter_mut() {
*k /= sum;
}
kernel
}
fn fill_nan_values(height_grid: &mut [Vec<f64>]) {
let height: usize = height_grid.len();
let width: usize = height_grid[0].len();
let mut changes_made: bool = true;
while changes_made {
changes_made = false;
for y in 0..height {
for x in 0..width {
if height_grid[y][x].is_nan() {
let mut sum: f64 = 0.0;
let mut count: i32 = 0;
// Check neighboring cells
for dy in -1..=1 {
for dx in -1..=1 {
let ny: i32 = y as i32 + dy;
let nx: i32 = x as i32 + dx;
if ny >= 0 && ny < height as i32 && nx >= 0 && nx < width as i32 {
let val: f64 = height_grid[ny as usize][nx as usize];
if !val.is_nan() {
sum += val;
count += 1;
}
}
}
}
if count > 0 {
height_grid[y][x] = sum / count as f64;
changes_made = true;
}
}
}
}
}
}
fn save_debug_image(heights: &Vec<Vec<i32>>, filename: &str) {
if heights.is_empty() || heights[0].is_empty() {
return;
}
let height: usize = heights.len();
let width: usize = heights[0].len();
let mut img: image::ImageBuffer<Rgb<u8>, Vec<u8>> =
RgbImage::new(width as u32, height as u32);
let mut min_height: i32 = i32::MAX;
let mut max_height: i32 = i32::MIN;
for row in heights {
for &h in row {
min_height = min_height.min(h);
max_height = max_height.max(h);
}
}
for (y, row) in heights.iter().enumerate() {
for (x, &h) in row.iter().enumerate() {
let normalized: u8 =
(((h - min_height) as f64 / (max_height - min_height) as f64) * 255.0) as u8;
img.put_pixel(
x as u32,
y as u32,
Rgb([normalized, normalized, normalized]),
);
}
}
// Ensure filename has .png extension
let filename: String = if !filename.ends_with(".png") {
format!("{}.png", filename)
} else {
filename.to_string()
};
if let Err(e) = img.save(&filename) {
eprintln!("Failed to save debug image: {}", e);
}
}
}

View File

@@ -3,12 +3,24 @@
mod args;
mod block_definitions;
mod bresenham;
mod cartesian;
mod colors;
mod data_processing;
mod element_processing;
mod floodfill;
mod ground;
mod osm_parser;
#[cfg(feature = "gui")]
mod progress;
// If the user does not want the GUI, it's easiest to just mock the progress module to do nothing
#[cfg(not(feature = "gui"))]
mod progress {
pub fn emit_gui_error(_message: &str) {}
pub fn emit_gui_progress_update(_progress: f64, _message: &str) {}
pub fn is_running_with_gui() -> bool {
false
}
}
mod retrieve_data;
mod version_check;
mod world_editor;
@@ -27,7 +39,10 @@ use std::{
panic,
path::{Path, PathBuf},
};
#[cfg(feature = "gui")]
use tauri_plugin_log::{Builder as LogBuilder, Target, TargetKind};
#[cfg(target_os = "windows")]
use windows::Win32::System::Console::{AttachConsole, FreeConsole, ATTACH_PARENT_PROCESS};
fn print_banner() {
let version: &str = env!("CARGO_PKG_VERSION");
@@ -53,6 +68,14 @@ fn print_banner() {
}
fn main() {
// If on Windows, free and reattach to the parent console when using as a CLI tool
// Either of these can fail, but if they do it is not an issue, so the return value is ignored
#[cfg(target_os = "windows")]
unsafe {
let _ = FreeConsole();
let _ = AttachConsole(ATTACH_PARENT_PROCESS);
}
// Parse arguments to decide whether to launch the UI or CLI
let raw_args: Vec<String> = std::env::args().collect();
@@ -120,47 +143,63 @@ fn main() {
let _ =
data_processing::generate_world(parsed_elements, &args, scale_factor_x, scale_factor_z);
} else {
// Launch the UI
println!("Launching UI...");
#[cfg(not(feature = "gui"))]
{
panic!("This version of arnis was not built with GUI enabled");
}
// Set a custom panic hook to log panic information
panic::set_hook(Box::new(|panic_info| {
let message = format!("Application panicked: {:?}", panic_info);
error!("{}", message);
std::process::exit(1);
}));
#[cfg(feature = "gui")]
{
// Launch the UI
println!("Launching UI...");
tauri::Builder::default()
.plugin(
LogBuilder::default()
.level(LevelFilter::Warn)
.targets([
Target::new(TargetKind::LogDir {
file_name: Some("arnis".into()),
}),
Target::new(TargetKind::Stdout),
])
.build(),
)
.plugin(tauri_plugin_shell::init())
.invoke_handler(tauri::generate_handler![
gui_select_world,
gui_start_generation,
gui_get_version,
gui_check_for_updates
])
.setup(|app| {
let app_handle = app.handle();
let main_window = tauri::Manager::get_webview_window(app_handle, "main")
.expect("Failed to get main window");
progress::set_main_window(main_window);
Ok(())
})
.run(tauri::generate_context!())
.expect("Error while starting the application UI (Tauri)");
// Set a custom panic hook to log panic information
panic::set_hook(Box::new(|panic_info| {
let message = format!("Application panicked: {:?}", panic_info);
error!("{}", message);
std::process::exit(1);
}));
// Workaround WebKit2GTK issue with NVIDIA drivers (likely explicit sync related?)
// Source: https://github.com/tauri-apps/tauri/issues/10702 (TODO: Remove this later)
#[cfg(target_os = "linux")]
unsafe {
env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
}
tauri::Builder::default()
.plugin(
LogBuilder::default()
.level(LevelFilter::Warn)
.targets([
Target::new(TargetKind::LogDir {
file_name: Some("arnis".into()),
}),
Target::new(TargetKind::Stdout),
])
.build(),
)
.plugin(tauri_plugin_shell::init())
.invoke_handler(tauri::generate_handler![
gui_select_world,
gui_start_generation,
gui_get_version,
gui_check_for_updates
])
.setup(|app| {
let app_handle = app.handle();
let main_window = tauri::Manager::get_webview_window(app_handle, "main")
.expect("Failed to get main window");
progress::set_main_window(main_window);
Ok(())
})
.run(tauri::generate_context!())
.expect("Error while starting the application UI (Tauri)");
}
}
}
#[cfg(feature = "gui")]
#[tauri::command]
fn gui_select_world(generate_new: bool) -> Result<String, i32> {
// Determine the default Minecraft 'saves' directory based on the OS
@@ -275,7 +314,7 @@ fn create_new_world(base_path: &Path) -> Result<String, String> {
let mut level_data: Value = fastnbt::from_bytes(&decompressed_data)
.map_err(|e| format!("Failed to parse level.dat template: {}", e))?;
// Modify the LevelName and LastPlayed fields
// Modify the LevelName, LastPlayed and player position fields
if let Value::Compound(ref mut root) = level_data {
if let Some(Value::Compound(ref mut data)) = root.get_mut("Data") {
// Update LevelName
@@ -287,6 +326,27 @@ fn create_new_world(base_path: &Path) -> Result<String, String> {
.map_err(|e| format!("Failed to get current time: {}", e))?;
let current_time_millis = current_time.as_millis() as i64;
data.insert("LastPlayed".to_string(), Value::Long(current_time_millis));
// Update player position and rotation
if let Some(Value::Compound(ref mut player)) = data.get_mut("Player") {
if let Some(Value::List(ref mut pos)) = player.get_mut("Pos") {
if let Value::Double(ref mut x) = pos.get_mut(0).unwrap() {
*x = -5.0;
}
if let Value::Double(ref mut y) = pos.get_mut(1).unwrap() {
*y = -61.0;
}
if let Value::Double(ref mut z) = pos.get_mut(2).unwrap() {
*z = -5.0;
}
}
if let Some(Value::List(ref mut rot)) = player.get_mut("Rotation") {
if let Value::Float(ref mut x) = rot.get_mut(0).unwrap() {
*x = -45.0;
}
}
}
}
}
@@ -315,11 +375,13 @@ fn create_new_world(base_path: &Path) -> Result<String, String> {
Ok(new_world_path.display().to_string())
}
#[cfg(feature = "gui")]
#[tauri::command]
fn gui_get_version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[cfg(feature = "gui")]
#[tauri::command]
fn gui_check_for_updates() -> Result<bool, String> {
match version_check::check_for_updates() {
@@ -328,6 +390,7 @@ fn gui_check_for_updates() -> Result<bool, String> {
}
}
#[cfg(feature = "gui")]
#[tauri::command]
fn gui_start_generation(
bbox_text: String,
@@ -336,6 +399,7 @@ fn gui_start_generation(
ground_level: i32,
winter_mode: bool,
floodfill_timeout: u64,
terrain_enabled: bool,
) -> Result<(), String> {
tauri::async_runtime::spawn(async move {
if let Err(e) = tokio::task::spawn_blocking(move || {
@@ -362,6 +426,7 @@ fn gui_start_generation(
downloader: "requests".to_string(),
scale: world_scale,
ground_level,
terrain: terrain_enabled,
winter: winter_mode,
debug: false,
timeout: Some(std::time::Duration::from_secs(floodfill_timeout)),

View File

@@ -1,4 +1,4 @@
use crate::{args::Args, progress::emit_gui_progress_update};
use crate::{args::Args, cartesian::XZPoint, progress::emit_gui_progress_update};
use colored::Colorize;
use serde::Deserialize;
use serde_json::Value;
@@ -44,6 +44,15 @@ pub struct ProcessedNode {
pub z: i32,
}
impl ProcessedNode {
pub fn xz(&self) -> XZPoint {
XZPoint {
x: self.x,
z: self.z,
}
}
}
#[derive(Debug, Clone)]
pub struct ProcessedWay {
pub id: u64,
@@ -281,7 +290,8 @@ pub fn get_priority(element: &ProcessedElement) -> usize {
}
// (lat meters, lon meters)
fn geo_distance(lat1: f64, lat2: f64, lon1: f64, lon2: f64) -> (f64, f64) {
#[inline]
pub fn geo_distance(lat1: f64, lat2: f64, lon1: f64, lon2: f64) -> (f64, f64) {
let z: f64 = lat_distance(lat1, lat2);
// distance between two lons depends on their latitude. In this case we'll just average them

View File

@@ -95,9 +95,10 @@ pub fn fetch_data(
"https://z.overpass-api.de/api/interpreter",
//"https://overpass.kumi.systems/api/interpreter", // This server is not reliable anymore
//"https://overpass.private.coffee/api/interpreter", // This server is not reliable anymore
"https://overpass.osm.ch/api/interpreter",
];
let url: &&str = api_servers.choose(&mut rand::thread_rng()).unwrap();
let fallback_api_servers: Vec<&str> =
vec!["https://maps.mail.ru/osm/tools/overpass/api/interpreter"];
let mut url: &&str = api_servers.choose(&mut rand::thread_rng()).unwrap();
// Generate Overpass API query for bounding box
let query: String = format!(
@@ -140,11 +141,30 @@ pub fn fetch_data(
Ok(data)
} else {
// Fetch data from Overpass API
let response: String = match download_method {
"requests" => download_with_reqwest(url, &query)?,
"curl" => download_with_curl(url, &query)?,
"wget" => download_with_wget(url, &query)?,
_ => download_with_reqwest(url, &query)?, // Default to requests
let mut attempt = 0;
let max_attempts = 1;
let response: String = loop {
let result = match download_method {
"requests" => download_with_reqwest(url, &query),
"curl" => download_with_curl(url, &query).map_err(|e| e.into()),
"wget" => download_with_wget(url, &query).map_err(|e| e.into()),
_ => download_with_reqwest(url, &query), // Default to requests
};
match result {
Ok(response) => break response,
Err(error) => {
if attempt >= max_attempts {
return Err(error);
}
println!("Request failed. Switching to fallback url...");
url = fallback_api_servers
.choose(&mut rand::thread_rng())
.unwrap();
attempt += 1;
}
}
};
let data: Value = serde_json::from_str(&response)?;
@@ -171,9 +191,11 @@ pub fn fetch_data(
// General case for when there are no elements and no specific remark
eprintln!(
"{}",
"Error! No data available in this region.".red().bold()
"Error! API returned no data. Please try again!"
.red()
.bold()
);
emit_gui_error("No data available in this region.");
emit_gui_error("API returned no data. Please try again!");
}
if debug {

View File

@@ -1,4 +1,3 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::progress::emit_gui_progress_update;
use colored::Colorize;
@@ -6,10 +5,12 @@ use fastanvil::Region;
use fastnbt::{LongArray, Value};
use fnv::FnvHashMap;
use indicatif::{ProgressBar, ProgressStyle};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -226,23 +227,21 @@ impl WorldToModify {
}
}
pub struct WorldEditor<'a> {
pub struct WorldEditor {
region_dir: String,
world: WorldToModify,
scale_factor_x: f64,
scale_factor_z: f64,
args: &'a Args,
}
impl<'a> WorldEditor<'a> {
impl WorldEditor {
/// Initializes the WorldEditor with the region directory and template region path.
pub fn new(region_dir: &str, scale_factor_x: f64, scale_factor_z: f64, args: &'a Args) -> Self {
pub fn new(region_dir: &str, scale_factor_x: f64, scale_factor_z: f64) -> Self {
Self {
region_dir: region_dir.to_string(),
world: WorldToModify::default(),
scale_factor_x,
scale_factor_z,
args,
}
}
@@ -271,12 +270,11 @@ impl<'a> WorldEditor<'a> {
(self.scale_factor_x as i32, self.scale_factor_x as i32)
}
// Unused and not tested
/*pub fn block_at(&self, x: i32, y: i32, z: i32) -> bool {
pub fn block_at(&self, x: i32, y: i32, z: i32) -> bool {
self.world.get_block(x, y, z).is_some()
}*/
}
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_arguments, dead_code)]
pub fn set_sign(
&mut self,
line1: String,
@@ -432,15 +430,95 @@ impl<'a> WorldEditor<'a> {
false
}
/// Helper function to create a base chunk with grass blocks at Y -62
fn create_base_chunk(abs_chunk_x: i32, abs_chunk_z: i32) -> (Vec<u8>, bool) {
let mut chunk = ChunkToModify::default();
// Fill the bottom layer with grass blocks at Y -62
for x in 0..16 {
for z in 0..16 {
chunk.set_block(x, -62, z, GRASS_BLOCK);
}
}
// Prepare chunk data
let chunk_data = Chunk {
sections: chunk.sections().collect(),
x_pos: abs_chunk_x,
z_pos: abs_chunk_z,
is_light_on: 0,
other: chunk.other,
};
// Create the Level wrapper
let level_data = HashMap::from([(
"Level".to_string(),
Value::Compound(HashMap::from([
("xPos".to_string(), Value::Int(abs_chunk_x)),
("zPos".to_string(), Value::Int(abs_chunk_z)),
("isLightOn".to_string(), Value::Byte(0)),
(
"sections".to_string(),
Value::List(
chunk_data
.sections
.iter()
.map(|section| {
Value::Compound(HashMap::from([
("Y".to_string(), Value::Byte(section.y)),
(
"block_states".to_string(),
Value::Compound(HashMap::from([
(
"palette".to_string(),
Value::List(
section
.block_states
.palette
.iter()
.map(|item| {
Value::Compound(HashMap::from([(
"Name".to_string(),
Value::String(item.name.clone()),
)]))
})
.collect(),
),
),
(
"data".to_string(),
Value::LongArray(
section
.block_states
.data
.clone()
.unwrap_or_else(|| LongArray::new(vec![])),
),
),
])),
),
]))
})
.collect(),
),
),
])),
)]);
// Serialize the chunk with Level wrapper
let mut ser_buffer = Vec::with_capacity(8192);
fastnbt::to_writer(&mut ser_buffer, &level_data).unwrap();
(ser_buffer, true)
}
/// Saves all changes made to the world by writing modified chunks to the appropriate region files.
pub fn save(&mut self) {
println!("{} Saving world...", "[5/5]".bold());
emit_gui_progress_update(90.0, "Saving world...");
let _debug: bool = self.args.debug;
let total_regions: u64 = self.world.regions.len() as u64;
let save_pb: ProgressBar = ProgressBar::new(total_regions);
let total_regions = self.world.regions.len() as u64;
let save_pb = ProgressBar::new(total_regions);
save_pb.set_style(
ProgressStyle::default_bar()
.template(
@@ -452,50 +530,223 @@ impl<'a> WorldEditor<'a> {
let total_steps: f64 = 9.0;
let progress_increment_save: f64 = total_steps / total_regions as f64;
let mut current_progress_save: f64 = 90.0;
let mut last_emitted_progress: f64 = current_progress_save;
let current_progress = AtomicU64::new(900);
let regions_processed = AtomicU64::new(0);
for ((region_x, region_z), region_to_modify) in &self.world.regions {
let mut region: Region<File> = self.create_region(*region_x, *region_z);
self.world
.regions
.par_iter()
.for_each(|((region_x, region_z), region_to_modify)| {
let mut region = self.create_region(*region_x, *region_z);
let mut ser_buffer = Vec::with_capacity(8192);
for chunk_x in 0..32 {
for chunk_z in 0..32 {
let data: Vec<u8> = region
.read_chunk(chunk_x as usize, chunk_z as usize)
.unwrap()
.unwrap();
for (&(chunk_x, chunk_z), chunk_to_modify) in &region_to_modify.chunks {
if !chunk_to_modify.sections.is_empty() || !chunk_to_modify.other.is_empty() {
// Read existing chunk data if it exists
let existing_data = region
.read_chunk(chunk_x as usize, chunk_z as usize)
.unwrap()
.unwrap_or_default();
let mut chunk: Chunk = fastnbt::from_bytes(&data).unwrap();
// Parse existing chunk or create new one
let mut chunk: Chunk = if !existing_data.is_empty() {
fastnbt::from_bytes(&existing_data).unwrap()
} else {
Chunk {
sections: Vec::new(),
x_pos: chunk_x + (region_x * 32),
z_pos: chunk_z + (region_z * 32),
is_light_on: 0,
other: FnvHashMap::default(),
}
};
if let Some(chunk_to_modify) = region_to_modify.get_chunk(chunk_x, chunk_z) {
chunk.sections = chunk_to_modify.sections().collect();
chunk.other.extend(chunk_to_modify.other.clone());
// Update sections while preserving existing data
let new_sections: Vec<Section> = chunk_to_modify.sections().collect();
for new_section in new_sections {
if let Some(existing_section) =
chunk.sections.iter_mut().find(|s| s.y == new_section.y)
{
// Merge block states
existing_section.block_states.palette =
new_section.block_states.palette;
existing_section.block_states.data = new_section.block_states.data;
} else {
// Add new section if it doesn't exist
chunk.sections.push(new_section);
}
}
// Preserve existing block entities and merge with new ones
if let Some(existing_entities) = chunk.other.get_mut("block_entities") {
if let Some(new_entities) = chunk_to_modify.other.get("block_entities")
{
if let (Value::List(existing), Value::List(new)) =
(existing_entities, new_entities)
{
// Remove old entities that are replaced by new ones
existing.retain(|e| {
if let Value::Compound(map) = e {
let (x, y, z) = get_entity_coords(map);
!new.iter().any(|new_e| {
if let Value::Compound(new_map) = new_e {
let (nx, ny, nz) = get_entity_coords(new_map);
x == nx && y == ny && z == nz
} else {
false
}
})
} else {
true
}
});
// Add new entities
existing.extend(new.clone());
}
}
} else {
// If no existing entities, just add the new ones
if let Some(new_entities) = chunk_to_modify.other.get("block_entities")
{
chunk
.other
.insert("block_entities".to_string(), new_entities.clone());
}
}
// Update chunk coordinates and flags
chunk.x_pos = chunk_x + (region_x * 32);
chunk.z_pos = chunk_z + (region_z * 32);
// Create Level wrapper and save
let level_data = create_level_wrapper(&chunk);
ser_buffer.clear();
fastnbt::to_writer(&mut ser_buffer, &level_data).unwrap();
region
.write_chunk(chunk_x as usize, chunk_z as usize, &ser_buffer)
.unwrap();
}
chunk.x_pos = chunk_x + region_x * 32;
chunk.z_pos = chunk_z + region_z * 32;
chunk.is_light_on = 0; // Force minecraft to recompute
let ser: Vec<u8> = fastnbt::to_bytes(&chunk).unwrap();
// Write chunk data back to the correct location, ensuring correct chunk coordinates
let expected_chunk_location: (usize, usize) =
((chunk_x as usize) & 31, (chunk_z as usize) & 31);
region
.write_chunk(expected_chunk_location.0, expected_chunk_location.1, &ser)
.unwrap();
}
}
save_pb.inc(1);
// Second pass: ensure all chunks exist
for chunk_x in 0..32 {
for chunk_z in 0..32 {
let abs_chunk_x = chunk_x + (region_x * 32);
let abs_chunk_z = chunk_z + (region_z * 32);
current_progress_save += progress_increment_save;
if (current_progress_save - last_emitted_progress).abs() > 0.25 {
emit_gui_progress_update(current_progress_save, "Saving world...");
last_emitted_progress = current_progress_save;
}
}
// Check if chunk exists in our modifications
let chunk_exists =
region_to_modify.chunks.contains_key(&(chunk_x, chunk_z));
// If chunk doesn't exist, create it with base layer
if !chunk_exists {
let (ser_buffer, _) = Self::create_base_chunk(abs_chunk_x, abs_chunk_z);
region
.write_chunk(chunk_x as usize, chunk_z as usize, &ser_buffer)
.unwrap();
}
}
}
// Update progress
let regions_done = regions_processed.fetch_add(1, Ordering::SeqCst);
let new_progress = (90.0 + (regions_done as f64 * progress_increment_save)) * 10.0;
let prev_progress =
current_progress.fetch_max(new_progress as u64, Ordering::SeqCst);
if new_progress as u64 - prev_progress > 1 {
emit_gui_progress_update(new_progress / 10.0, "Saving world...");
}
save_pb.inc(1);
});
save_pb.finish();
}
}
// Helper function to get entity coordinates
fn get_entity_coords(entity: &HashMap<String, Value>) -> (i32, i32, i32) {
let x = if let Value::Int(x) = entity.get("x").unwrap_or(&Value::Int(0)) {
*x
} else {
0
};
let y = if let Value::Int(y) = entity.get("y").unwrap_or(&Value::Int(0)) {
*y
} else {
0
};
let z = if let Value::Int(z) = entity.get("z").unwrap_or(&Value::Int(0)) {
*z
} else {
0
};
(x, y, z)
}
fn create_level_wrapper(chunk: &Chunk) -> HashMap<String, Value> {
HashMap::from([(
"Level".to_string(),
Value::Compound(HashMap::from([
("xPos".to_string(), Value::Int(chunk.x_pos)),
("zPos".to_string(), Value::Int(chunk.z_pos)),
(
"isLightOn".to_string(),
Value::Byte(i8::try_from(chunk.is_light_on).unwrap()),
),
(
"sections".to_string(),
Value::List(
chunk
.sections
.iter()
.map(|section| {
Value::Compound(HashMap::from([
("Y".to_string(), Value::Byte(section.y)),
(
"block_states".to_string(),
Value::Compound(HashMap::from([
(
"palette".to_string(),
Value::List(
section
.block_states
.palette
.iter()
.map(|item| {
let mut palette_item = HashMap::from([(
"Name".to_string(),
Value::String(item.name.clone()),
)]);
if let Some(props) = &item.properties {
palette_item.insert(
"Properties".to_string(),
props.clone(),
);
}
Value::Compound(palette_item)
})
.collect(),
),
),
(
"data".to_string(),
Value::LongArray(
section
.block_states
.data
.clone()
.unwrap_or_else(|| LongArray::new(vec![])),
),
),
])),
),
]))
})
.collect(),
),
),
])),
)])
}

View File

@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Arnis",
"version": "2.1.3",
"version": "2.2.0",
"identifier": "com.louisdev.arnis",
"build": {
"frontendDist": "gui-src"