Compare commits

..

216 Commits

Author SHA1 Message Date
louis-e
7a42f011de Fix fmt 2025-05-05 00:25:25 +02:00
louis-e
106214c8ea WIP: Add subway 2025-05-05 00:21:58 +02:00
Louis Erbkamm
922e752684 Merge pull request #425 from GMart/Update-block-types
Update leisure and highway element processing
2025-05-03 16:37:09 +02:00
Garrett M
873f6aa995 Merge branch 'louis-e:main' into Update-block-types 2025-05-02 11:17:34 -04:00
Garrett M
0cd4c0e28d Add comments and dirt block option
Add comments to code, add dirt to option for dog park, playground, etc.
2025-05-02 11:16:44 -04:00
Garrett M
97eebbb977 Fixes for stairs and unneeded tag
In Leisure, soccer golf is used less than 1000 time worldwide. Removed since it will rarely be used.
in highways, changes stairs to be GRAY_CONCRETE for now, until they are properly added.
2025-05-02 11:06:59 -04:00
Louis Erbkamm
7ae6dc8143 Merge pull request #430 from Oleg4260/main
Implement wetlands
2025-05-02 17:04:52 +02:00
Oleg4260
a112cda485 Merge branch 'louis-e:main' into main 2025-05-02 12:44:40 +03:00
Garrett M
116f753e45 Merge branch 'louis-e:main' into Update-block-types 2025-05-01 18:36:46 -04:00
Louis Erbkamm
3c41be1ad0 Merge pull request #416 from benjamin051000/separate-gui-logic
Move GUI logic to its own file
2025-05-01 23:51:39 +02:00
Louis Erbkamm
7ad15c70c3 main.rs: fix fmt 2025-05-01 23:03:47 +02:00
Louis Erbkamm
bf53f4bb2f gui.rs: fix fmt 2025-05-01 23:01:15 +02:00
Louis Erbkamm
be819c01a0 Update gui.rs with latest changes 2025-05-01 22:59:47 +02:00
Louis Erbkamm
899cb2ee16 Merge branch 'main' into separate-gui-logic 2025-05-01 22:58:49 +02:00
Louis Erbkamm
b63b3ae05a pr-benchmark.yml: add memory annotation 2025-05-01 22:01:07 +02:00
Oleg4260
48c2e93292 Merge branch 'main' into main 2025-05-01 18:34:58 +03:00
Garrett M
4395eb6dd6 Merge branch 'louis-e:main' into Update-block-types 2025-05-01 09:11:31 -04:00
Louis Erbkamm
e8bbbec0f9 pr-benchmark.yml: add more stats 2025-05-01 15:07:07 +02:00
Garrett M
b16c0f84ac Merge branch 'louis-e:main' into Update-block-types 2025-05-01 09:03:48 -04:00
Louis Erbkamm
6efee57cbc pr-benchmark.yml: fix reference time 2025-05-01 14:52:10 +02:00
Louis Erbkamm
41ae099887 pr-benchmark.yml: enable terrain 2025-05-01 14:46:58 +02:00
Louis Erbkamm
781bb79ae5 Merge pull request #434 from louis-e/dependabot/cargo/once_cell-1.21.3
Bump once_cell from 1.20.2 to 1.21.3
2025-05-01 14:40:27 +02:00
Louis Erbkamm
3b378296a3 Merge pull request #433 from louis-e/dependabot/cargo/windows-0.61.1
Bump windows from 0.59.0 to 0.61.1
2025-05-01 14:40:15 +02:00
Louis Erbkamm
703b83a2fd Merge pull request #432 from louis-e/dependabot/cargo/colored-3.0.0
Bump colored from 2.2.0 to 3.0.0
2025-05-01 14:39:49 +02:00
Louis Erbkamm
c7e1b5bf67 Merge pull request #431 from louis-e/dependabot/cargo/flate2-1.1.1
Bump flate2 from 1.0.35 to 1.1.1
2025-05-01 14:39:40 +02:00
Garrett M
b8f45ac178 Merge branch 'louis-e:main' into Update-block-types 2025-05-01 08:34:10 -04:00
Louis Erbkamm
e9133c136a pr-benchmark.yml: fix reference time 2025-05-01 14:23:40 +02:00
Louis Erbkamm
92881cf3b3 pr-benchmark.yml: fix new line 2025-05-01 14:19:42 +02:00
Louis Erbkamm
421fe47ecf pr-benchmark.yml: fix summary 2025-05-01 14:13:55 +02:00
Louis Erbkamm
0c2c99544e pr-benchmark.yml: fix summary 2025-05-01 14:12:22 +02:00
Louis Erbkamm
491716f0fc pr-benchmark.yml: fix summary 2025-05-01 14:10:48 +02:00
Louis Erbkamm
96f9bc736e pr-benchmark.yml: more detailed comment 2025-05-01 14:05:38 +02:00
Louis Erbkamm
ffe694f9d8 pr-benchmark.yml: add detailed comment 2025-05-01 14:00:34 +02:00
Louis Erbkamm
c7b6df92ab Update pr-benchmark.yml 2025-05-01 13:53:13 +02:00
Louis Erbkamm
5b67f8ee84 pr-benchmark.yml: update bbox arg input 2025-05-01 13:49:52 +02:00
Louis Erbkamm
179cb6fa2d pr-benchmark.yml: Create dummy world 2025-05-01 13:46:00 +02:00
Louis Erbkamm
15c8265a21 pr-benchmark.yml: run on command 2025-05-01 13:40:27 +02:00
Louis Erbkamm
7ec0b9aa03 Run pr-benchmark.yml on opened PR 2025-05-01 13:33:51 +02:00
dependabot[bot]
c1ac1774fb Bump once_cell from 1.20.2 to 1.21.3
Bumps [once_cell](https://github.com/matklad/once_cell) from 1.20.2 to 1.21.3.
- [Changelog](https://github.com/matklad/once_cell/blob/master/CHANGELOG.md)
- [Commits](https://github.com/matklad/once_cell/compare/v1.20.2...v1.21.3)

---
updated-dependencies:
- dependency-name: once_cell
  dependency-version: 1.21.3
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-01 02:14:14 +00:00
dependabot[bot]
b46cd17ff4 Bump windows from 0.59.0 to 0.61.1
Bumps [windows](https://github.com/microsoft/windows-rs) from 0.59.0 to 0.61.1.
- [Release notes](https://github.com/microsoft/windows-rs/releases)
- [Commits](https://github.com/microsoft/windows-rs/commits)

---
updated-dependencies:
- dependency-name: windows
  dependency-version: 0.61.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-01 02:13:54 +00:00
dependabot[bot]
2789a40fd0 Bump colored from 2.2.0 to 3.0.0
Bumps [colored](https://github.com/mackwic/colored) from 2.2.0 to 3.0.0.
- [Release notes](https://github.com/mackwic/colored/releases)
- [Changelog](https://github.com/colored-rs/colored/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mackwic/colored/compare/v2.2.0...v3.0.0)

---
updated-dependencies:
- dependency-name: colored
  dependency-version: 3.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-01 02:13:40 +00:00
dependabot[bot]
6f71bc3fdb Bump flate2 from 1.0.35 to 1.1.1
Bumps [flate2](https://github.com/rust-lang/flate2-rs) from 1.0.35 to 1.1.1.
- [Release notes](https://github.com/rust-lang/flate2-rs/releases)
- [Commits](https://github.com/rust-lang/flate2-rs/compare/1.0.35...1.1.1)

---
updated-dependencies:
- dependency-name: flate2
  dependency-version: 1.1.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-01 02:13:26 +00:00
Garrett M
7a102dec51 Fix extra match and typo
Fix GRASS to GRASS_BLOCK
Remove ladder type as it would have to have special properties to work properly
2025-04-30 19:24:39 -04:00
Oleg4260
320acac80d More wetland types 2025-04-30 17:33:53 +03:00
Oleg4260
0cad9fa307 fix forest generating over roads 2025-04-30 16:41:18 +03:00
Garrett M
b03202ac71 Update leisure.rs
Fix nature_reserve
Add more leisure values.
2025-04-29 14:11:01 -04:00
Oleg4260
32ae0778e2 Implement wetlands
Implement wetlands

cargo fmt; implement bog

Better bog
2025-04-29 20:49:16 +03:00
Garrett M
faef164abe Fix marina and add more blocks to highways.rs
Remove marina from water. It was making entire marina areas water, which was not intended. Add some block types to highways
2025-04-28 23:39:04 -04:00
Garrett M
d9930c2b44 Merge branch 'louis-e:main' into Update-block-types 2025-04-28 17:35:38 -04:00
Louis Erbkamm
1a0fc291b0 Merge pull request #426 from Oleg4260/main
Fixes for pull/423
2025-04-28 21:21:40 +02:00
Oleg4260
bb14b1da49 fix fmt 2025-04-28 12:55:10 +03:00
Oleg4260
c0edbaa92c cargo fmt 2025-04-28 12:48:49 +03:00
Oleg4260
bf69996427 Fix crash caused by unicode characters in area_name 2025-04-28 12:45:34 +03:00
Oleg4260
1c734cdd7c Fix generation of ground layers, remove unnecessary function 2025-04-28 12:10:57 +03:00
Garrett M
ed529071ae Merge branch 'louis-e:main' into Update-block-types 2025-04-27 21:08:27 -04:00
Louis Erbkamm
9a288e3966 Merge pull request #423 from louis-e/simplify-elevation
Simplify elevation retrieval in each element processor
2025-04-27 23:48:54 +02:00
louis-e
e5f0717838 Fix bedrock layer 2025-04-27 23:39:08 +02:00
louis-e
c258892b45 Fix cargo fmt 2025-04-27 23:23:37 +02:00
louis-e
151ced7625 Assign persistent property to birch leaves 2025-04-27 23:21:38 +02:00
louis-e
73e8bab4a0 Resolve merge conflicts 2025-04-27 23:18:12 +02:00
Garrett M
3dfa2ca62e leisure.rs cargo fmt
Cargo fmt
2025-04-27 16:48:30 -04:00
Louis Erbkamm
f1d3c0b980 Merge pull request #421 from Oleg4260/main
Optimize ground generation + new natural elements
2025-04-27 22:36:52 +02:00
louis-e
bcc986969f Merge branch 'simplify-elevation' of https://github.com/louis-e/arnis into simplify-elevation 2025-04-27 22:28:35 +02:00
Louis Erbkamm
2d07e9c2b9 Fix cargo fmt 2025-04-27 22:27:11 +02:00
Louis Erbkamm
a213bace19 Fix clippy 2025-04-27 22:18:50 +02:00
Louis Erbkamm
7552a99a34 Fix clippy 2025-04-27 22:16:28 +02:00
Louis Erbkamm
ec3f5825b4 Fix formatting 2025-04-27 22:08:09 +02:00
louis-e
1294c3ef3c Fix formatting for CI 2025-04-27 22:06:52 +02:00
Louis Erbkamm
ca2fd0b1c6 Merge branch 'main' into simplify-elevation 2025-04-27 21:58:13 +02:00
louis-e
b5596548db Optimize WorldEditor performance with strategic #[inline] attributes 2025-04-27 21:57:01 +02:00
Oleg4260
6167466b2f Less vegetation in heathland 2025-04-27 22:56:03 +03:00
louis-e
5e18402017 Add location name to world name 2025-04-27 21:47:25 +02:00
Oleg4260
ec76a5f2e2 Add heath and orchard generation 2025-04-27 22:14:49 +03:00
Oleg4260
349f15807a Final adjustments 2025-04-27 21:27:19 +03:00
Oleg4260
6fdf28ab81 Add beach surface material processing, dead bushes in sand, plants in scrub and grassland 2025-04-27 19:15:30 +03:00
louis-e
c961287290 Adapt code comments 2025-04-27 16:59:56 +02:00
louis-e
1fefb20f71 Fix formatting 2025-04-27 16:52:37 +02:00
louis-e
022c44a7d4 Remove unused code 2025-04-27 16:52:13 +02:00
louis-e
6b8a8ad666 Patch amenities.rs to new relative block setter logic 2025-04-27 16:51:49 +02:00
louis-e
c0e1d0e3b4 Patch buildings.rs to new relative block setter logic 2025-04-27 16:38:17 +02:00
louis-e
fb64d0c360 Add absolute setter support in world_editor.rs 2025-04-27 16:10:13 +02:00
Oleg4260
19cac3ea81 Minor reformatting 2025-04-27 15:18:16 +03:00
Oleg4260
8bad88bdca Refactor editor.check_for_block() 2025-04-27 15:00:42 +03:00
Oleg4260
e62ba6a95a Merge branch 'louis-e:main' into main 2025-04-27 13:46:02 +03:00
Garrett M
d1b18871ce Update leisure generation and fix typo
Fix 'Mincraft' typo (Code still works so not sure what that prefix did)
Add additional types for leisure
2025-04-27 00:07:58 -04:00
Benjamin Wheeler
d4b74fc48a Move GUI logic to its own file. Simplify main fn. 2025-04-26 23:13:32 -04:00
louis-e
38752f2666 Fix fmt for elevation retrieval simplification 2025-04-27 03:35:52 +02:00
louis-e
77a9c23ed3 Simplify elevation retrieval 2025-04-27 03:32:44 +02:00
Louis Erbkamm
987b8b3d74 Merge pull request #422 from louis-e/simplification-refactoring
Remove winter mode as discussed in issues/415
2025-04-27 01:29:06 +02:00
Louis Erbkamm
f398c7e6b8 Removed dirt reference 2025-04-27 01:26:40 +02:00
louis-e
9a759c39db Fix fmt for winter mode removal 2025-04-27 00:51:36 +02:00
louis-e
856cba162e Remove winter mode as discussed in issues/415 2025-04-27 00:48:56 +02:00
Louis Erbkamm
55d0208a32 Merge pull request #411 from HelleBenjamin/main
Update Finnish translation
2025-04-27 00:01:18 +02:00
Louis Erbkamm
b1d20cbd1a Patch --all-features discussed in pull/417 2025-04-26 23:59:07 +02:00
Louis Erbkamm
cca4d1a361 Merge pull request #417 from benjamin051000/ci-cache
CI: Add cache action to preserve build artifacts.
2025-04-26 23:57:11 +02:00
Oleg4260
ae5a838fa3 Optimize ground generation 2025-04-26 19:05:17 +03:00
Louis Erbkamm
06974e2bf7 Arch Linux AUR package 2025-04-26 16:13:17 +02:00
Louis Erbkamm
b769ff34de Merge pull request #113 from adamperkowski/docs/aur
docs(README): add Arch Linux installation instructions
2025-04-26 16:11:18 +02:00
Louis Erbkamm
0f8e302aff Merge branch 'main' into docs/aur 2025-04-26 16:10:45 +02:00
Louis Erbkamm
597051303c Merge pull request #360 from louis-e/dependabot/cargo/dirs-6.0.0
Bump dirs from 5.0.1 to 6.0.0
2025-04-26 16:06:19 +02:00
Louis Erbkamm
08bdc64999 Merge branch 'main' into dependabot/cargo/dirs-6.0.0 2025-04-26 16:06:12 +02:00
Louis Erbkamm
3723127132 Resolve open discussion in pull/354 2025-04-26 15:43:59 +02:00
Louis Erbkamm
f8a1da1967 Merge pull request #354 from TheComputerGuy96/desktop-file
Add a XDG desktop file
2025-04-26 15:43:09 +02:00
Louis Erbkamm
9352ee62b7 Merge pull request #420 from louis-e/revert-line
Revert to second dirt addition line
2025-04-26 15:19:53 +02:00
Louis Erbkamm
8816af5c75 Revert to second dirt addition line 2025-04-26 15:19:38 +02:00
Louis Erbkamm
2fb09d1fba Merge pull request #377 from benjamin051000/formalize-bbox
Formal BBox struct
2025-04-26 15:00:09 +02:00
Benjamin Wheeler
c3ce8829f3 Update GUI bbox to use comma delim. Add gui bbox errors. 2025-04-25 20:28:11 -04:00
Benjamin Wheeler
a3f0d5e367 Formal bounding box type BBox.
`BBox` represents a *valid* bounding box.

It's only possible to have a BBox object that's valid.
2025-04-25 20:28:06 -04:00
Benjamin Helle
d93b771422 Merge branch 'main' into main 2025-04-24 15:47:41 +03:00
Louis Erbkamm
4271dc3b7d Merge pull request #414 from Oleg4260/main
Minor improvements to farmland code
2025-04-22 22:39:49 +02:00
Oleg4260
6732697f46 Use args.ground_level instead of MIN_Y with terrain enabled 2025-04-22 17:56:12 +03:00
Benjamin Helle
4d94ab98a4 Merge branch 'main' into main 2025-04-22 01:34:39 +03:00
Benjamin Wheeler
2c8418bf90 Add cache action to preserve build artifacts.
Github Copilot made this... so who knows if it actually works.
2025-04-21 18:17:08 -04:00
Oleg4260
a1ed2b9dd2 Clean up farmland code 2025-04-20 23:17:35 +03:00
Oleg4260
9b7cabc549 Fix space between water blocks (meant to be 8) 2025-04-20 16:05:45 +03:00
Louis Erbkamm
db47f6ab20 Merge pull request #412 from louis-e/revert-improvement
Revert improvement
2025-04-19 15:13:55 +02:00
louis-e
ef261a24e4 Revert benches in leisure, discussion in pull/406 2025-04-19 15:13:22 +02:00
louis-e
898457e06c Revert improvement, discussion in pull/406 2025-04-19 15:10:04 +02:00
Benjamin Helle
0f84c8a38c Update Finnish translation 2025-04-19 15:39:21 +03:00
Benjamin Helle
f416f650c2 Update Finnish translation 2025-04-19 15:38:28 +03:00
Louis Erbkamm
b98c043bb8 Merge pull request #376 from benjamin051000/ci-cargo-test
ci: run cargo test
2025-04-13 00:45:35 +02:00
Louis Erbkamm
2a1233c463 Merge pull request #374 from benjamin051000/fix-terrain-flag
Set `terrain` arg to store true.
2025-04-13 00:44:37 +02:00
Louis Erbkamm
e1869fbbbc Merge pull request #340 from benjamin051000/refactor-block-defs
Change functions returning vecs to global arrays.
2025-04-13 00:43:11 +02:00
Benjamin Wheeler
bfba692aaf Change functions returning vecs to global arrays.
I'm not sure why these were initally functions. I think they are better
off as global arrays, since the function would initialize a new vec
every time its called, whereas this only initializes it once.
2025-04-10 16:57:29 -04:00
Benjamin Wheeler
1382e05e25 Add cargo test to CI 2025-04-10 16:25:02 -04:00
Benjamin Wheeler
642928057a Add unit tests for --winter, --debug, --terrain flags. 2025-04-10 16:23:09 -04:00
Benjamin Wheeler
1749f6a1f2 Set terrain arg to SetTrue.
This was erroneously set to `SetFalse`, which means it's impossible to
enable the terrain from the cli.

According to clap docs, the default action for a bool arg is SetTrue,
and the default value is false. (https://docs.rs/clap/latest/clap/_derive/index.html#arg-types)

So we don't need to provide any additional args here.
2025-04-10 16:23:09 -04:00
Louis Erbkamm
4c08c5fe72 Patch arabic translation 2025-04-10 22:19:35 +02:00
Louis Erbkamm
8a4961a0a6 Merge pull request #287 from Salmonings/main
Add Arabic language
2025-04-10 22:18:43 +02:00
Louis Erbkamm
05569fb0fc fr-FR.json adaptions from pull/318/ 2025-04-10 22:15:47 +02:00
Louis Erbkamm
f203ad1c09 Merge pull request #396 from Phantomwise/translation-french
Add translation for French (France)
2025-04-10 22:13:39 +02:00
Louis Erbkamm
4d123211ee Merge pull request #398 from xCipHanD/ChineseTranslation
Update Chinese translation
2025-04-10 22:10:35 +02:00
Louis Erbkamm
8a191e563d Merge pull request #407 from louis-e/dependabot/cargo/cargo-6f59152c2a
Bump the cargo group with 5 updates
2025-04-10 22:05:07 +02:00
Louis Erbkamm
9c0db6f1c7 Update README.md 2025-04-10 21:59:07 +02:00
dependabot[bot]
a7638d971a Bump the cargo group with 5 updates
Bumps the cargo group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [tauri-plugin-shell](https://github.com/tauri-apps/plugins-workspace) | `2.2.0` | `2.2.1` |
| [tokio](https://github.com/tokio-rs/tokio) | `1.44.1` | `1.44.2` |
| [crossbeam-channel](https://github.com/crossbeam-rs/crossbeam) | `0.5.14` | `0.5.15` |
| [openssl](https://github.com/sfackler/rust-openssl) | `0.10.70` | `0.10.72` |
| [ring](https://github.com/briansmith/ring) | `0.17.8` | `0.17.14` |


Updates `tauri-plugin-shell` from 2.2.0 to 2.2.1
- [Release notes](https://github.com/tauri-apps/plugins-workspace/releases)
- [Commits](https://github.com/tauri-apps/plugins-workspace/compare/os-v2.2.0...os-v2.2.1)

Updates `tokio` from 1.44.1 to 1.44.2
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.44.1...tokio-1.44.2)

Updates `crossbeam-channel` from 0.5.14 to 0.5.15
- [Release notes](https://github.com/crossbeam-rs/crossbeam/releases)
- [Changelog](https://github.com/crossbeam-rs/crossbeam/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crossbeam-rs/crossbeam/compare/crossbeam-channel-0.5.14...crossbeam-channel-0.5.15)

Updates `openssl` from 0.10.70 to 0.10.72
- [Release notes](https://github.com/sfackler/rust-openssl/releases)
- [Commits](https://github.com/sfackler/rust-openssl/compare/openssl-v0.10.70...openssl-v0.10.72)

Updates `ring` from 0.17.8 to 0.17.14
- [Changelog](https://github.com/briansmith/ring/blob/main/RELEASES.md)
- [Commits](https://github.com/briansmith/ring/commits)

---
updated-dependencies:
- dependency-name: tauri-plugin-shell
  dependency-version: 2.2.1
  dependency-type: direct:production
  dependency-group: cargo
- dependency-name: tokio
  dependency-version: 1.44.2
  dependency-type: direct:production
  dependency-group: cargo
- dependency-name: crossbeam-channel
  dependency-version: 0.5.15
  dependency-type: indirect
  dependency-group: cargo
- dependency-name: openssl
  dependency-version: 0.10.72
  dependency-type: indirect
  dependency-group: cargo
- dependency-name: ring
  dependency-version: 0.17.14
  dependency-type: indirect
  dependency-group: cargo
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-10 19:51:16 +00:00
Louis Erbkamm
fa6a023b7c Merge pull request #406 from louis-e/pull403-adaptions
Minor adaptions for PR 403
2025-04-10 21:50:09 +02:00
Louis Erbkamm
2ac4cacd2d Merge pull request #363 from louis-e/dependabot/cargo/cargo-2c68f0befb
Bump openssl from 0.10.68 to 0.10.70 in the cargo group
2025-04-10 21:49:17 +02:00
Louis Erbkamm
b334212667 Merge pull request #391 from louis-e/dependabot/cargo/tauri-plugin-log-2.2.2
Bump tauri-plugin-log from 2.2.0 to 2.2.2
2025-04-10 21:48:58 +02:00
Louis Erbkamm
dc7f3f973e Merge pull request #402 from louis-e/dependabot/cargo/tokio-1.44.1
Bump tokio from 1.42.0 to 1.44.1
2025-04-10 21:48:42 +02:00
Louis Erbkamm
44f58dcd22 Merge pull request #401 from louis-e/dependabot/cargo/log-0.4.27
Bump log from 0.4.22 to 0.4.27
2025-04-10 21:48:38 +02:00
louis-e
4c1643281d fmt: Fix formatting 2025-04-10 21:47:35 +02:00
louis-e
6e113746d4 Minor adaptions for PR 403 2025-04-10 21:41:35 +02:00
Louis Erbkamm
6a1d6d32ff Merge pull request #403 from Oleg4260/main
Some improvements for the generation
2025-04-10 21:39:09 +02:00
Oleg4260
8d6d10fc47 Remove ugly "benches" 2025-04-09 17:23:18 +03:00
Oleg4260
c022611d08 Add custom layers for some landuse and natural objects, use stone as a marker not to generate dirt 2025-04-07 18:21:57 +03:00
Oleg4260
5a15ba3a62 Clarify comment 2025-04-07 12:34:02 +03:00
Oleg4260
c526f295c3 cargo fmt 2025-04-07 12:23:43 +03:00
Oleg4260
0e0a08cfc9 Remove stone filling under quarries (doesn't work anymore) 2025-04-07 12:22:58 +03:00
Oleg4260
d992e5eb87 Remove BASE_HEIGHT_SCALE, remove scale.sqrt to match X and Z scale 2025-04-07 10:59:56 +03:00
Oleg4260
5c0e24ee73 fix fmt 2025-04-06 18:29:35 +03:00
Oleg4260
9d85de61a3 Replace water grid with dot grid in farmlands 2025-04-06 18:27:42 +03:00
Oleg4260
b23749b330 Change scale to 1.0 2025-04-05 20:56:35 +03:00
Oleg4260
77debbbc20 Fix clippy error 2025-04-05 15:24:25 +03:00
Oleg4260
8970ce5ffe Remove trees from farmlands 2025-04-05 15:06:47 +03:00
Oleg4260
7a36ac9c3f Improve winter mode 2025-04-05 14:40:19 +03:00
Oleg4260
4363dfd558 Add more natural surfaces 2025-04-05 13:22:52 +03:00
Oleg4260
1aac2e3068 Increase max_y to 319 2025-04-05 01:31:59 +03:00
dependabot[bot]
d16cedde9a Bump tokio from 1.42.0 to 1.44.1
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.42.0 to 1.44.1.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.42.0...tokio-1.44.1)

---
updated-dependencies:
- dependency-name: tokio
  dependency-version: 1.44.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-01 03:04:46 +00:00
dependabot[bot]
59b71ebd84 Bump log from 0.4.22 to 0.4.27
Bumps [log](https://github.com/rust-lang/log) from 0.4.22 to 0.4.27.
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.22...0.4.27)

---
updated-dependencies:
- dependency-name: log
  dependency-version: 0.4.27
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-01 03:03:02 +00:00
xciphand
2e01c8c710 Update Chinese Translation 2025-03-26 12:03:17 +08:00
Louis Erbkamm
bff58b39fd Fix cargo fmt 2025-03-23 17:14:13 +01:00
Louis Erbkamm
887e622428 Added fillground if wrapping around bedrock generation 2025-03-23 17:11:01 +01:00
Louis Erbkamm
931f03a784 Merge pull request #337 from Oleg4260/main
Added ores generation in quarries + other changes
2025-03-23 17:09:08 +01:00
Oleg4260
c1c43d9244 Fix stone bricks in rural area 2025-03-22 19:25:06 +02:00
Phantomwise
8a84a08316 Add translation for French (France) 2025-03-20 04:25:32 +01:00
Oleg4260
2c72a61324 sync 2025-03-09 23:09:06 +02:00
Oleg4260
bf263a4f8c fix conflict 2025-03-09 22:56:35 +02:00
Louis Erbkamm
50ba0bad6e Merge pull request #346 from Xatresu/hutranslation
Add Hungarian translation
2025-03-09 21:47:44 +01:00
Louis Erbkamm
1d80e6e047 Merge pull request #378 from benjamin051000/clippy-warnings
Fix clippy warnings
2025-03-09 21:43:35 +01:00
Louis Erbkamm
b5e9bb885d Merge pull request #335 from benjamin051000/refactor-tree
Refactor tree generation
2025-03-09 21:40:38 +01:00
dependabot[bot]
665b8f095b Bump tauri-plugin-log from 2.2.0 to 2.2.2
Bumps [tauri-plugin-log](https://github.com/tauri-apps/plugins-workspace) from 2.2.0 to 2.2.2.
- [Release notes](https://github.com/tauri-apps/plugins-workspace/releases)
- [Commits](https://github.com/tauri-apps/plugins-workspace/compare/os-v2.2.0...log-v2.2.2)

---
updated-dependencies:
- dependency-name: tauri-plugin-log
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-09 20:33:13 +00:00
Louis Erbkamm
75bee6ca97 Merge pull request #321 from benjamin051000/remove-more-gui-deps
Remove gui-only deps when building cli
2025-03-09 21:31:52 +01:00
Oleg4260
41055825ef Replace iron blocks under railways with gravel 2025-03-08 13:56:34 +02:00
Benjamin Wheeler
6fd3a8eda7 Fix clippy warnings 2025-02-21 22:42:44 -05:00
Oleg4260
c578a436b4 Replace light concrete with dirt path for highway:path 2025-02-11 23:52:10 +02:00
Oleg4260
211ac4ed72 Merge branch 'main' of https://github.com/Oleg4260/arnis 2025-02-04 17:02:12 +02:00
Oleg4260
3d0a1c3c4d cargo fmt 2025-02-04 17:02:10 +02:00
Oleg4260
0c9c8e1366 Merge branch 'main' of https://github.com/Oleg4260/arnis 2025-02-04 17:00:15 +02:00
Oleg4260
0e28d34224 Use editor.fill_blocks() instead of loop 2025-02-04 16:59:09 +02:00
Oleg4260
3b1425cd30 Merge branch 'main' of https://github.com/Oleg4260/arnis 2025-02-04 16:08:20 +02:00
Oleg4260
ce0bce99fb Added feature to fill ground with stone
Trying to fix compilation error
2025-02-04 16:08:09 +02:00
Oleg4260
cde0042b85 Trying to fix compilation error 2025-02-04 00:22:49 +02:00
Oleg4260
622edaff07 Added feature to fill ground with stone 2025-02-04 00:06:09 +02:00
dependabot[bot]
ca760563d1 Bump openssl from 0.10.68 to 0.10.70 in the cargo group
Bumps the cargo group with 1 update: [openssl](https://github.com/sfackler/rust-openssl).


Updates `openssl` from 0.10.68 to 0.10.70
- [Release notes](https://github.com/sfackler/rust-openssl/releases)
- [Commits](https://github.com/sfackler/rust-openssl/compare/openssl-v0.10.68...openssl-v0.10.70)

---
updated-dependencies:
- dependency-name: openssl
  dependency-type: indirect
  dependency-group: cargo
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-03 18:51:25 +00:00
dependabot[bot]
f278d629eb Bump dirs from 5.0.1 to 6.0.0
Bumps [dirs](https://github.com/soc/dirs-rs) from 5.0.1 to 6.0.0.
- [Commits](https://github.com/soc/dirs-rs/commits)

---
updated-dependencies:
- dependency-name: dirs
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-01 02:40:47 +00:00
Echo J
2c319bae5d Add a XDG desktop file
This allows proper packaging of the application for Linux distros
2025-01-29 20:55:49 +02:00
Xatres
809ff2793d Add files via upload 2025-01-27 03:35:52 +01:00
Benjamin Wheeler
3ba9c58f85 element_processing/tree: Make all trees conform to a struct.
This decouples the data that each tree has with the block-placing
procedure. Now, all the data about a tree is stored in `struct Tree`,
and the `Tree::create()` function handles all paths accordingly.
2025-01-25 23:39:38 -05:00
Benjamin Wheeler
66b7f47e32 element_processing/tree: Update create_tree signature
x, y, z -> (x, y, z)

Also some small variable renames
2025-01-25 23:39:38 -05:00
Benjamin Wheeler
a96911e112 element_processing/tree: DRY on fill calls, use j with y.
This commit is a little messy:
- It reduces repitition of the block fill calls and the snow layer calls
- It also replaces previous usage of `y + i` with `y + j` to keep the
  variable conventions the same.
2025-01-25 23:39:35 -05:00
Benjamin Wheeler
112481f36f Remove gui-only deps when building cli
It looks like these are only GUI dependencies. I still need to test that
it compiles, but these give unused warnings when compiling with the gui
disabled.
2025-01-25 22:03:16 -05:00
Benjamin Wheeler
65cd0d453a element_processing/tree: replace round{1,2,3} with generic round
round takes a parameter which is a reference to an array of patterns.
The patterns are defined at the top of the file as `[(i32, i32, i32)]`.
2025-01-25 21:33:13 -05:00
Benjamin Wheeler
febd1b7a3e element_processing/tree: Use loops to reduce repitition 2025-01-25 21:33:13 -05:00
Oleg4260
6b527855e4 cargo fmt 2025-01-25 20:07:03 +02:00
Oleg4260
cc1e28b80a Added ores generation in quarries 2025-01-25 20:03:16 +02:00
Louis Erbkamm
a969d65ae4 Trigger ci-build.yml only when files in src/ have changed 2025-01-25 14:15:23 +01:00
Louis Erbkamm
acf123488a Merge pull request #333 from Oleg4260/main
Add landuse for quarry and landfills + add one advice in FAQ
2025-01-25 14:10:08 +01:00
Louis Erbkamm
938a2d74ad Merge pull request #334 from wielandb/hedge-fix
Make leaves persistent to stop hedges from decaying
2025-01-25 14:09:02 +01:00
Louis Erbkamm
33144a149c Merge pull request #336 from TheComputerGuy96/lt-update
Update Lithuanian translation
2025-01-25 14:07:18 +01:00
Echo J
fbb0f845cd Update Lithuanian translation 2025-01-25 12:20:30 +02:00
Wieland
c71cd111ca Make leaves persistent 2025-01-24 22:41:30 +01:00
Oleg4260
04d9d5269f Put changes back again (i messed up with merging lmao) 2025-01-24 20:29:43 +02:00
Oleg4260
f53e4d65e3 Merge branch 'main' of https://github.com/Oleg4260/arnis 2025-01-24 20:20:27 +02:00
Oleg4260
c39d6fc1ef Merge branch 'louis-e:main' into main 2025-01-24 20:12:53 +02:00
Oleg4260
a1c69b4cb0 Did cargo fmt 2025-01-24 20:11:10 +02:00
Louis Erbkamm
b57719b0f4 Merge pull request #317 from krvstek/main
Update Polish translation
2025-01-24 17:21:41 +01:00
Louis Erbkamm
893945b98a Merge pull request #324 from Denisskas/main
Update Russian translation
2025-01-24 17:19:19 +01:00
Oleg4260
a57c5f1f1b Add landuse for quarry and landfill 2025-01-23 23:37:28 +02:00
Oleg4260
718389e88d Revert "Replaced iron blocks under railways with gravel"
This reverts commit 3f4536e04f.
2025-01-23 20:50:33 +02:00
Oleg4260
3f4536e04f Replaced iron blocks under railways with gravel 2025-01-23 19:43:57 +02:00
Oleg4260
1f79285e83 Update README.md
I had an issue of the program not opening when I switched to KDE and removed some gtk libraries i don't need, I found out that webkit2gtk-4.1 is required, so I think this should be in the FAQ as this might help others with the same issue
2025-01-23 18:11:45 +02:00
Adham Hakki
31dca8b0b7 Merge branch 'main' into main 2025-01-22 21:26:37 +02:00
Denisskas
54791388d1 Update ru.json 2025-01-22 13:18:47 +04:00
krvstek.
7fa05d3e7b Update Polish translation 2025-01-21 23:02:33 +00:00
Adham Hakki
7ae9ac35d1 Add Arabic language
Just love the idea and the project so a little bit of contributing might help! Here's the Arabic locales for the program! Just be careful as Arabic is a RTL language so it might go wrong/weird
2025-01-13 21:32:29 +02:00
Adam Perkowski
8e29b1422e docs(README): add Arch Linux installation instructions 2025-01-01 18:17:26 +01:00
49 changed files with 2551 additions and 1804 deletions

View File

@@ -1,13 +1,21 @@
name: CI Build
# Trigger on pull request creation, update, and on pushes to the main branch
# Trigger CI on pull requests and pushes to main, when relevant files change
on:
pull_request:
branches:
- main
paths:
- 'src/**'
- 'Cargo.toml'
- 'Cargo.lock'
push:
branches:
- main
paths:
- 'src/**'
- 'Cargo.toml'
- 'Cargo.lock'
workflow_dispatch:
jobs:
@@ -39,6 +47,17 @@ jobs:
sudo apt install -y libgtk-3-dev build-essential pkg-config libglib2.0-dev libsoup-3.0-dev libwebkit2gtk-4.1-dev
echo "PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig" >> $GITHUB_ENV
- name: Set up cache for Cargo
uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-
- name: Check formatting
run: cargo fmt -- --check
@@ -48,5 +67,8 @@ jobs:
- name: Install Rust dependencies
run: cargo fetch
- name: Build
run: cargo build --release
- name: Build (all targets, all features)
run: cargo build --all-targets --all-features --release
- name: Run unit tests
run: cargo test --all-targets --all-features

103
.github/workflows/pr-benchmark.yml vendored Normal file
View File

@@ -0,0 +1,103 @@
name: PR Benchmark
on:
pull_request:
types: [opened, reopened]
issue_comment:
types: [created]
jobs:
benchmark:
if: |
github.event_name == 'pull_request' ||
(github.event_name == 'issue_comment' &&
github.event.issue.pull_request != null &&
contains(github.event.comment.body, 'retrigger-benchmark'))
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Rust
uses: dtolnay/rust-toolchain@v1
with:
toolchain: stable
components: clippy
- name: Create dummy Minecraft world directory
run: |
mkdir -p "./world/region"
- name: Start timer
id: start_time
run: echo "start_time=$(date +%s)" >> $GITHUB_OUTPUT
- name: Run benchmark command with memory tracking
id: benchmark
run: |
/usr/bin/time -v cargo run --release --no-default-features -- --path="./world" --terrain --bbox="48.117861,11.541996,48.154520,11.604824" 2> benchmark_log.txt
grep "Maximum resident set size" benchmark_log.txt | awk '{print $6}' > peak_mem_kb.txt
peak_kb=$(cat peak_mem_kb.txt)
peak_mb=$((peak_kb / 1024))
echo "peak_memory=${peak_mb}" >> $GITHUB_OUTPUT
- name: End timer and calculate duration
id: end_time
run: |
end_time=$(date +%s)
start_time=${{ steps.start_time.outputs.start_time }}
duration=$((end_time - start_time))
echo "duration=$duration" >> $GITHUB_OUTPUT
- name: Format duration and generate summary
id: comment_body
run: |
duration=${{ steps.end_time.outputs.duration }}
minutes=$((duration / 60))
seconds=$((duration % 60))
peak_mem=${{ steps.benchmark.outputs.peak_memory }}
baseline_time=130
diff=$((duration - baseline_time))
abs_diff=${diff#-}
if [ "$diff" -lt -10 ]; then
verdict="✅ This PR **improves generation time**."
elif [ "$abs_diff" -le 7 ]; then
verdict="🟢 Generation time is unchanged."
elif [ "$diff" -le 25 ]; then
verdict="⚠️ This PR **slightly worsens generation time**."
else
verdict="🚨 This PR **drastically worsens generation time**."
fi
baseline_mem=1960
mem_annotation=""
if [ "$peak_mem" -gt 2000 ]; then
mem_diff=$((peak_mem - baseline_mem))
mem_percent=$((mem_diff * 100 / baseline_mem))
mem_annotation=" (↗ ${mem_percent}% more)"
fi
{
echo "summary<<EOF"
echo "⏱️ Benchmark run finished in **${minutes}m ${seconds}s**"
echo "🧠 Peak memory usage: **${peak_mem} MB**${mem_annotation}"
echo ""
echo "📈 Compared against baseline: **${baseline_time}s**"
echo "🧮 Delta: **${diff}s**"
echo "🔢 Commit: [\`${GITHUB_SHA:0:7}\`](https://github.com/${GITHUB_REPOSITORY}/commit/${GITHUB_SHA})"
echo ""
echo "${verdict}"
echo ""
echo "_You can retrigger the benchmark by commenting \`retrigger-benchmark\`._"
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Comment build time on PR
uses: thollander/actions-comment-pull-request@v3
with:
message: ${{ steps.comment_body.outputs.summary }}
comment-tag: benchmark-report
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -26,7 +26,7 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Set up Rust
uses: dtolnay/rust-toolchain@v1
@@ -83,7 +83,7 @@ jobs:
shell: powershell
- name: Upload artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v3
with:
name: ${{ matrix.os }}-build
path: target/release/${{ matrix.asset_name }}
@@ -96,19 +96,19 @@ jobs:
uses: actions/checkout@v3
- name: Download Windows build artifact
uses: actions/download-artifact@v4
uses: actions/download-artifact@v3
with:
name: windows-latest-build
path: ./builds/windows
- name: Download Linux build artifact
uses: actions/download-artifact@v4
uses: actions/download-artifact@v3
with:
name: ubuntu-latest-build
path: ./builds/linux
- name: Download macOS build artifact
uses: actions/download-artifact@v4
uses: actions/download-artifact@v3
with:
name: macos-latest-build
path: ./builds/macos
@@ -119,11 +119,11 @@ jobs:
chmod +x ./builds/macos/arnis-mac
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v1
with:
files: |
builds/windows/arnis-windows.exe
builds/linux/arnis-linux
builds/macos/arnis-mac
env:
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}

262
Cargo.lock generated
View File

@@ -168,11 +168,11 @@ dependencies = [
[[package]]
name = "arnis"
version = "2.2.1"
version = "2.2.0"
dependencies = [
"clap",
"colored",
"dirs",
"dirs 6.0.0",
"fastanvil",
"fastnbt",
"flate2",
@@ -196,7 +196,7 @@ dependencies = [
"tauri-plugin-log",
"tauri-plugin-shell",
"tokio",
"windows 0.59.0",
"windows 0.61.1",
]
[[package]]
@@ -686,9 +686,9 @@ dependencies = [
[[package]]
name = "cc"
version = "1.2.7"
version = "1.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a012a0df96dd6d06ba9a1b29d6402d1a5d77c6befd2566afdc26e10603dc93d7"
checksum = "525046617d8376e3db1deffb079e91cef90a89fc3ca5c185bbf8c9ecdd15cd5c"
dependencies = [
"shlex",
]
@@ -829,11 +829,10 @@ checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"
[[package]]
name = "colored"
version = "2.2.0"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e"
dependencies = [
"lazy_static",
"windows-sys 0.59.0",
]
@@ -955,9 +954,9 @@ dependencies = [
[[package]]
name = "crossbeam-channel"
version = "0.5.14"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06ba6d68e24814cb8de6bb986db8222d3a027d15872cabc0d18817bc3c0e4471"
checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2"
dependencies = [
"crossbeam-utils",
]
@@ -1114,7 +1113,16 @@ version = "5.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"
dependencies = [
"dirs-sys",
"dirs-sys 0.4.1",
]
[[package]]
name = "dirs"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
dependencies = [
"dirs-sys 0.5.0",
]
[[package]]
@@ -1125,10 +1133,22 @@ checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"
dependencies = [
"libc",
"option-ext",
"redox_users",
"redox_users 0.4.6",
"windows-sys 0.48.0",
]
[[package]]
name = "dirs-sys"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
dependencies = [
"libc",
"option-ext",
"redox_users 0.5.0",
"windows-sys 0.59.0",
]
[[package]]
name = "dispatch"
version = "0.2.0"
@@ -1449,9 +1469,9 @@ dependencies = [
[[package]]
name = "flate2"
version = "1.0.35"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c936bfdafb507ebbf50b8074c54fa31c5be9a1e7e5f467dd659697041407d07c"
checksum = "7ced92e76e966ca2fd84c8f7aa01a4aea65b0eb6648d72f7c8f3e2764a67fece"
dependencies = [
"crc32fast",
"miniz_oxide",
@@ -2771,9 +2791,9 @@ dependencies = [
[[package]]
name = "log"
version = "0.4.22"
version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
dependencies = [
"value-bag",
]
@@ -2836,9 +2856,9 @@ checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "miniz_oxide"
version = "0.8.2"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ffbe83022cedc1d264172192511ae958937694cd57ce297164951b8b3568394"
checksum = "3be647b768db090acb35d5ec5db2b0e1f1de11133ca123b9eacf5137868f892a"
dependencies = [
"adler2",
"simd-adler32",
@@ -3290,9 +3310,9 @@ dependencies = [
[[package]]
name = "once_cell"
version = "1.20.2"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "open"
@@ -3308,9 +3328,9 @@ dependencies = [
[[package]]
name = "openssl"
version = "0.10.68"
version = "0.10.72"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6174bc48f102d208783c2c84bf931bb75927a617866870de8a4ea85597f871f5"
checksum = "fedfea7d58a1f73118430a55da6a286e7b044961736ce96a16a17068ea25e5da"
dependencies = [
"bitflags 2.6.0",
"cfg-if",
@@ -3340,9 +3360,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "openssl-sys"
version = "0.9.104"
version = "0.9.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45abf306cbf99debc8195b66b7346498d7b10c210de50418b5ccd7ceba08c741"
checksum = "8288979acd84749c744a9014b4382d42b8f7b2592847b5afb2ed29e5d16ede07"
dependencies = [
"cc",
"libc",
@@ -3935,6 +3955,17 @@ dependencies = [
"thiserror 1.0.69",
]
[[package]]
name = "redox_users"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b"
dependencies = [
"getrandom 0.2.15",
"libredox",
"thiserror 2.0.9",
]
[[package]]
name = "regex"
version = "1.11.1"
@@ -4046,15 +4077,14 @@ dependencies = [
[[package]]
name = "ring"
version = "0.17.8"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.15",
"libc",
"spin",
"untrusted",
"windows-sys 0.52.0",
]
@@ -4605,12 +4635,6 @@ dependencies = [
"smallvec",
]
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
@@ -4827,7 +4851,7 @@ checksum = "2e2e3349fbb2be7af9fad1b43d61ac83ba55ab48d47fbe1b2732f0c8211610a9"
dependencies = [
"anyhow",
"bytes",
"dirs",
"dirs 5.0.1",
"dunce",
"embed_plist",
"futures-util",
@@ -4877,7 +4901,7 @@ checksum = "b274ec7239ada504deb615f1c8abd7ba99631e879709e6f10e5d17217058d976"
dependencies = [
"anyhow",
"cargo_toml",
"dirs",
"dirs 5.0.1",
"glob",
"heck 0.5.0",
"json-patch",
@@ -4951,16 +4975,16 @@ dependencies = [
[[package]]
name = "tauri-plugin-log"
version = "2.2.0"
version = "2.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd784c138c08a43954bc3e735402e6b2b2ee8d8c254a7391f4e77c01273dd5"
checksum = "4e106ce75445f592879022757789ccd41c6d2829cd3043f2bf24379b52dc8710"
dependencies = [
"android_logger",
"byte-unit",
"cocoa",
"fern",
"log",
"objc",
"objc2",
"objc2-foundation",
"serde",
"serde_json",
"serde_repr",
@@ -4973,9 +4997,9 @@ dependencies = [
[[package]]
name = "tauri-plugin-shell"
version = "2.2.0"
version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb2c50a63e60fb8925956cc5b7569f4b750ac197a4d39f13b8dd46ea8e2bad79"
checksum = "69d5eb3368b959937ad2aeaf6ef9a8f5d11e01ffe03629d3530707bbcb27ff5d"
dependencies = [
"encoding_rs",
"log",
@@ -5226,9 +5250,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.42.0"
version = "1.44.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cec9b21b0450273377fc97bd4c33a8acffc8c996c987a7c5b319a0083707551"
checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48"
dependencies = [
"backtrace",
"bytes",
@@ -5244,9 +5268,9 @@ dependencies = [
[[package]]
name = "tokio-macros"
version = "2.4.0"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752"
checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8"
dependencies = [
"proc-macro2",
"quote",
@@ -5422,7 +5446,7 @@ checksum = "d48a05076dd272615d03033bf04f480199f7d1b66a8ac64d75c625fc4a70c06b"
dependencies = [
"core-graphics",
"crossbeam-channel",
"dirs",
"dirs 5.0.1",
"libappindicator",
"muda",
"objc2",
@@ -5977,12 +6001,24 @@ dependencies = [
[[package]]
name = "windows"
version = "0.59.0"
version = "0.61.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f919aee0a93304be7f62e8e5027811bbba96bcb1de84d6618be56e43f8a32a1"
checksum = "c5ee8f3d025738cb02bad7868bbb5f8a6327501e870bf51f1b455b0a2454a419"
dependencies = [
"windows-core 0.59.0",
"windows-targets 0.53.0",
"windows-collections",
"windows-core 0.61.0",
"windows-future",
"windows-link",
"windows-numerics",
]
[[package]]
name = "windows-collections"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"
dependencies = [
"windows-core 0.61.0",
]
[[package]]
@@ -6009,15 +6045,25 @@ dependencies = [
[[package]]
name = "windows-core"
version = "0.59.0"
version = "0.61.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "810ce18ed2112484b0d4e15d022e5f598113e220c53e373fb31e67e21670c1ce"
checksum = "4763c1de310c86d75a878046489e2e5ba02c649d185f21c67d4cf8a56d098980"
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",
"windows-implement 0.60.0",
"windows-interface 0.59.1",
"windows-link",
"windows-result 0.3.2",
"windows-strings 0.4.0",
]
[[package]]
name = "windows-future"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a1d6bbefcb7b60acd19828e1bc965da6fcf18a7e39490c5f8be71e54a19ba32"
dependencies = [
"windows-core 0.61.0",
"windows-link",
]
[[package]]
@@ -6033,9 +6079,9 @@ dependencies = [
[[package]]
name = "windows-implement"
version = "0.59.0"
version = "0.60.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83577b051e2f49a058c308f17f273b570a6a758386fc291b5f6a934dd84e48c1"
checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836"
dependencies = [
"proc-macro2",
"quote",
@@ -6055,15 +6101,31 @@ dependencies = [
[[package]]
name = "windows-interface"
version = "0.59.0"
version = "0.59.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb26fd936d991781ea39e87c3a27285081e3c0da5ca0fcbc02d368cc6f52ff01"
checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.95",
]
[[package]]
name = "windows-link"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38"
[[package]]
name = "windows-numerics"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"
dependencies = [
"windows-core 0.61.0",
"windows-link",
]
[[package]]
name = "windows-registry"
version = "0.2.0"
@@ -6086,11 +6148,11 @@ dependencies = [
[[package]]
name = "windows-result"
version = "0.3.0"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d08106ce80268c4067c0571ca55a9b4e9516518eaa1a1fe9b37ca403ae1d1a34"
checksum = "c64fd11a4fd95df68efcfee5f44a294fe71b8bc6a91993e2791938abcc712252"
dependencies = [
"windows-targets 0.53.0",
"windows-link",
]
[[package]]
@@ -6105,11 +6167,11 @@ dependencies = [
[[package]]
name = "windows-strings"
version = "0.3.0"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b888f919960b42ea4e11c2f408fadb55f78a9f236d5eef084103c8ce52893491"
checksum = "7a2ba9642430ee452d5a7aa78d72907ebe8cfda358e8cb7918a2050581322f97"
dependencies = [
"windows-targets 0.53.0",
"windows-link",
]
[[package]]
@@ -6187,29 +6249,13 @@ dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm 0.52.6",
"windows_i686_gnullvm",
"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"
@@ -6237,12 +6283,6 @@ 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"
@@ -6261,12 +6301,6 @@ 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"
@@ -6285,24 +6319,12 @@ 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"
@@ -6321,12 +6343,6 @@ 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"
@@ -6345,12 +6361,6 @@ 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"
@@ -6369,12 +6379,6 @@ 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"
@@ -6393,12 +6397,6 @@ 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"

View File

@@ -1,6 +1,6 @@
[package]
name = "arnis"
version = "2.2.1"
version = "2.2.0"
edition = "2021"
description = "Arnis - Generate real life cities in Minecraft"
homepage = "https://github.com/louis-e/arnis"
@@ -13,37 +13,37 @@ lto = "thin"
[features]
default = ["gui"]
gui = ["dep:tauri", "dep:tauri-plugin-log", "dep:tauri-plugin-shell"]
gui = ["tauri", "tauri-plugin-log", "tauri-plugin-shell", "tokio", "rfd", "dirs", "tauri-build"]
[build-dependencies]
tauri-build = "2"
tauri-build = {version = "2", optional = true}
[dependencies]
clap = { version = "4.1", features = ["derive"] }
colored = "2.1.0"
dirs = "5.0.1"
colored = "3.0.0"
dirs = {version = "6.0.0", optional = true }
fastanvil = "0.31.0"
fastnbt = "2.5.0"
flate2 = "1.0"
flate2 = "1.1"
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"
log = "0.4.27"
once_cell = "1.21.3"
rand = "0.8.5"
rayon = "1.10.0"
reqwest = { version = "0.12.7", features = ["blocking", "json"] }
rfd = "0.15.1"
rfd = { version = "0.15.1", optional = true }
semver = "1.0.23"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tauri = { version = "2", optional = true }
tauri-plugin-log = { version = "2.2.0", optional = true }
tauri-plugin-log = { version = "2.2.2", optional = true }
tauri-plugin-shell = { version = "2", optional = true }
tokio = { version = "1.42.0", features = ["full"] }
tokio = { version = "1.44.2", features = ["full"], optional = true }
[target.'cfg(windows)'.dependencies]
windows = { version = "0.59.0", features = ["Win32_System_Console"] }
windows = { version = "0.61.1", features = ["Win32_System_Console"] }

View File

@@ -4,29 +4,27 @@
# Arnis [![CI Build Status](https://github.com/louis-e/arnis/actions/workflows/ci-build.yml/badge.svg)](https://github.com/louis-e/arnis/actions) [<img alt="GitHub Release" src="https://img.shields.io/github/v/release/louis-e/arnis" />](https://github.com/louis-e/arnis/releases) [<img alt="GitHub Downloads (all assets, all releases" src="https://img.shields.io/github/downloads/louis-e/arnis/total" />](https://github.com/louis-e/arnis/releases)
This open source project written in Rust generates any chosen location from the real world in Minecraft Java Edition with a high level of detail.
Arnis creates complex and accurate Minecraft Java Edition worlds that reflect real-world geography and architecture using OpenStreetMap.
###### ⚠️ This Github page is the official project website. Do not download Arnis from any other website.
## :desktop_computer: Example
![Minecraft Preview](https://github.com/louis-e/arnis/blob/main/gitassets/mc.gif?raw=true)
By leveraging geospatial data from OpenStreetMap and utilizing the powerful capabilities of Rust, Arnis provides an efficient and robust solution for creating complex and accurate Minecraft worlds that reflect real-world geography and architecture.
Arnis is designed to handle large-scale data and generate rich, immersive environments that bring real-world cities, landmarks, and natural features into the Minecraft universe. Whether you're looking to replicate your hometown, explore urban environments, or simply build something unique and realistic, Arnis generates your vision.
Arnis is designed to handle large-scale data and generate rich, immersive environments that bring real-world cities, landmarks, and natural features into Minecraft. Whether you're looking to replicate your hometown, explore urban environments, or simply build something unique and realistic, Arnis generates your vision.
## :keyboard: Usage
<img width="60%" src="https://github.com/louis-e/arnis/blob/main/gitassets/gui.png?raw=true"><br>
Download the [latest release](https://github.com/louis-e/arnis/releases/) or [compile](#trophy-open-source) the project on your own.
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.
Choose your area using the rectangle tool and select your Minecraft world - then simply click on 'Start Generation'!
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.
> 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.
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 or above.
If you choose to select an own world, be aware that Arnis will overwrite certain areas.
[[Arch Linux AUR package](https://aur.archlinux.org/packages/arnis)]
## :floppy_disk: How it works
![CLI Generation](https://github.com/louis-e/arnis/blob/main/gitassets/cli.gif?raw=true)
@@ -52,14 +50,15 @@ The project is named after the smallest city in Germany, Arnis[^2]. The city's s
- *I don't have Minecraft installed but want to generate a world for my kids. How?*<br>
When selecting a world, click on 'Select existing world' and choose a directory. The world will be generated there.
- *Arnis instantly closes again or the window is empty!*<br>
If you're on Windows, please install the [Evergreen Bootstrapper from Microsoft](https://developer.microsoft.com/en-us/microsoft-edge/webview2/?form=MA13LH#download).
If you're on Windows, please install the [Evergreen Bootstrapper from Microsoft](https://developer.microsoft.com/en-us/microsoft-edge/webview2/?form=MA13LH#download).
If you're on Linux, your system might be missing the webkit2gtk-4.1 library, install the corresponding package using your distro's package manager.
- *What Minecraft version should I use?*<br>
Please use Minecraft version 1.21.4 for the best results. Minecraft version 1.16.5 and below is currently not supported, but we are working on it!
- *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>
**Floodfill-Timeout (Sec):** This setting determines the maximum time the floodfill algorithm is allowed to run before being terminated. Increasing this value may improve the generation of large water areas but may also increase processing time.<br>
@@ -67,14 +66,14 @@ Make sure to teleport to the generation starting point (/tp 0 0 0). If there is
## :memo: ToDo and Known Bugs
Feel free to choose an item from the To-Do or Known Bugs list, or bring your own idea to the table. Bug reports shall be raised as a Github issue. Contributions are highly welcome and appreciated!
- [ ] Fix compilation for Linux
- [ ] Rotate maps (https://github.com/louis-e/arnis/issues/97)
- [ ] Fix compilation for Linux and Mac
- [ ] Fix coastal cities generation duration time (water_areas.rs)
- [ ] Add street names as signs
- [ ] Rotate maps (https://github.com/louis-e/arnis/issues/97)
- [ ] Add support for older Minecraft versions (<=1.16.5) (https://github.com/louis-e/arnis/issues/124, https://github.com/louis-e/arnis/issues/137)
- [ ] Mapping real coordinates to Minecraft coordinates (https://github.com/louis-e/arnis/issues/29)
- [ ] Add interior to buildings
- [ ] Implement house roof types
- [ ] Add street names as signs
- [ ] Add support for inner attribute in multipolygons and multipolygon elements other than buildings
- [ ] Refactor bridges implementation
- [ ] Better code documentation
@@ -95,17 +94,19 @@ Feel free to choose an item from the To-Do or Known Bugs list, or bring your own
## :trophy: Open Source
#### Key objectives of this project
- **Modularity**: Ensure that all components (e.g., data fetching, processing, and world generation) are cleanly separated into distinct modules for better maintainability and scalability.
- **Performance Optimization**: Utilize Rusts memory safety and concurrency features to optimize the performance of the world generation process.
- **Performance Optimization**: We aim to keep a good performance and speed of the world generation process.
- **Comprehensive Documentation**: Detailed in-code documentation for a clear structure and logic.
- **User-Friendly Experience**: Focus on making the project easy to use for end users.
- **Cross-Platform Support**: Ensure the project runs smoothly on Windows, macOS, and Linux.
- **Cross-Platform Support**: We want this project to run smoothly on Windows, macOS, and Linux.
#### 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.
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. Please respect the above mentioned key objectives. Contributions of all levels are appreciated, and your efforts help improve this tool for everyone.
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>
> You can use the parameter --debug to get a more detailed output of the processed values, which can be helpful for debugging and development.
After your pull request was merged, I will take care of regularly creating update releases which will include your changes.
## :star: Star History

15
gui-src/arnis.desktop vendored Normal file
View File

@@ -0,0 +1,15 @@
[Desktop Entry]
Type=Application
Name=Arnis
Comment=Generate cities from real life in Minecraft
Comment[lt]=Sugeneruokite tikrovės miestus „Minecraft“ žaidime
Comment[de]=Generiere echte Städte in Minecraft
Comment[fr]=Générez des villes réelles dans Minecraft
Comment[es]=Genera ciudades reales en Minecraft
Comment[pt]=Gere cidades reais no Minecraft
Comment[zh_CN]=在 Minecraft 中生成现实城市
Icon=icon
Exec=arnis
Categories=Game;Education;Geoscience
Keywords=OSM;OpenStreetMap;Minecraft
StartupWMClass=arnis

View File

@@ -251,11 +251,11 @@ button:hover {
margin: 15px 0;
}
#winter-toggle {
#fillground-toggle {
accent-color: #fecc44;
}
.winter-toggle-container, .scale-slider-container {
.fillground-toggle-container, .scale-slider-container {
margin: 15px 0;
}

11
gui-src/index.html vendored
View File

@@ -89,13 +89,12 @@
<!-- 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">
<input type="checkbox" id="terrain-toggle" name="terrain-toggle" checked>
</div>
<!-- Winter Mode Toggle Button -->
<div class="winter-toggle-container">
<label for="winter-toggle" data-localize="winter_mode">Winter Mode:</label>
<input type="checkbox" id="winter-toggle" name="winter-toggle">
<!-- Fill ground Toggle Button -->
<div class="fillground-toggle-container">
<label for="fillground-toggle" data-localize="fillground">Fill Ground:</label>
<input type="checkbox" id="fillground-toggle" name="fillground-toggle">
</div>
<!-- World Scale Slider -->

85
gui-src/js/bbox.js vendored
View File

@@ -322,7 +322,7 @@ function addLayer(layer, name, title, zIndex, on) {
}
link.innerHTML = name;
link.title = title;
link.onclick = function (e) {
link.onclick = function(e) {
e.preventDefault();
e.stopPropagation();
@@ -456,19 +456,13 @@ $(document).ready(function () {
** on top of your DOM
**
*/
// init the projection input box as it is used to format the initial values
$('input[type="textarea"]').on('click', function (evt) { this.select() });
// Have to init the projection input box as it is used to format the initial values
$("#projection").val(currentproj);
// Initialize map with OpenStreetMap tiles
map = L.map('map').setView([50.114768, 8.687322], 4);
// Add OpenStreetMap tile layer (free to use with attribution)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; Map data from <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
maxZoom: 19
}).addTo(map);
L.mapbox.accessToken = 'pk.eyJ1IjoiY3Vnb3MiLCJhIjoiY2p4Nm43MzA3MDFmZDQwcGxsMjB4Z3hnNiJ9.SQbnMASwdqZe6G4n6OMvVw';
map = L.mapbox.map('map').setView([50.114768, 8.687322], 4).addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11'));
rsidebar = L.control.sidebar('rsidebar', {
position: 'right',
@@ -504,25 +498,14 @@ $(document).ready(function () {
// Initialize the FeatureGroup to store editable layers
drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems); // Initialize the draw control and pass it the FeatureGroup of editable layers
map.addLayer(drawnItems);
// Initialize the draw control and pass it the FeatureGroup of editable layers
drawControl = new L.Control.Draw({
edit: {
featureGroup: drawnItems
},
draw: {
rectangle: {
shapeOptions: {
color: '#fe57a1',
opacity: 0.6,
weight: 3,
fillColor: '#fe57a1',
fillOpacity: 0.1,
dashArray: '10, 10',
lineCap: 'round',
lineJoin: 'round'
},
repeatMode: false
},
polyline: false,
polygon: false,
circle: false,
@@ -530,6 +513,7 @@ $(document).ready(function () {
}
});
map.addControl(drawControl);
/*
**
** create bounds layer
@@ -539,22 +523,17 @@ $(document).ready(function () {
**
*/
startBounds = new L.LatLngBounds([0.0, 0.0], [0.0, 0.0]);
var bounds = new L.Rectangle(startBounds, {
color: '#3778d4',
opacity: 1.0,
weight: 3,
fill: '#3778d4',
lineCap: 'round',
lineJoin: 'round'
});
bounds.on('bounds-set', function (e) {
// move it to the end of the parent if renderer exists
if (e.target._renderer && e.target._renderer._container) {
var parent = e.target._renderer._container.parentElement;
$(parent).append(e.target._renderer._container);
var bounds = new L.Rectangle(startBounds,
{
fill: false,
opacity: 1.0,
color: '#000'
}
);
bounds.on('bounds-set', function (e) {
// move it to the end of the parent
var parent = e.target._renderer._container.parentElement;
$(parent).append(e.target._renderer._container);
// Set the hash
var southwest = this.getBounds().getSouthWest();
var northeast = this.getBounds().getNorthEast();
@@ -564,21 +543,8 @@ $(document).ready(function () {
var ymax = northeast.lat.toFixed(6);
location.hash = ymin + ',' + xmin + ',' + ymax + ',' + xmax;
});
map.addLayer(bounds);
map.addLayer(bounds)
map.on('draw:created', function (e) {
// Check if it's a rectangle and set proper styles before adding it to the layer
if (e.layerType === 'rectangle') {
e.layer.setStyle({
color: '#3778d4',
opacity: 1.0,
weight: 3,
fill: '#3778d4',
lineCap: 'round',
lineJoin: 'round'
});
}
drawnItems.addLayer(e.layer);
bounds.setBounds(drawnItems.getBounds())
$('#boxbounds').text(formatBounds(bounds.getBounds(), '4326'));
@@ -663,14 +629,7 @@ $(document).ready(function () {
var splitBounds = initialBBox.split(',');
startBounds = new L.LatLngBounds([splitBounds[0], splitBounds[1]],
[splitBounds[2], splitBounds[3]]);
var lyr = new L.Rectangle(startBounds, {
color: '#3778d4',
opacity: 1.0,
weight: 3,
fill: '#3778d4',
lineCap: 'round',
lineJoin: 'round'
});
var lyr = new L.Rectangle(startBounds);
var evt = {
layer: lyr,
layerType: "polygon",
@@ -695,4 +654,4 @@ $(document).ready(function () {
function notifyBboxUpdate() {
const bboxText = document.getElementById('boxbounds').textContent;
window.parent.postMessage({ bboxText: bboxText }, '*');
}
}

View File

@@ -10,7 +10,7 @@ RedAuburn<br>
daniil2327<br>
benjamin051000<br>
<p>For a full list of contributors, please refer to the <a href="https://github.com/louis-e/arnis" style="color: inherit;" target="_blank">Github page</a>. Logo made by nxfx21. Map data from <a href="https://www.openstreetmap.org/copyright" style="color: inherit;" target="_blank">OpenStreetMap</a>.</p>
<p>For a full list of contributors, please refer to the <a href="https://github.com/louis-e/arnis" style="color: inherit;" target="_blank">Github page</a>. Logo made by nxfx21.</p>
<p style="color: #ff7070;"><b>Download Arnis only from the official source:</b> <a href="https://github.com/louis-e/arnis" style="color: inherit;" target="_blank">https://github.com/louis-e/arnis/</a>. Every other website providing a download and claiming to be affiliated with the project is unofficial and may be malicious.</p>

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

@@ -96,7 +96,6 @@ async function applyLocalization(localization) {
"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",
@@ -313,8 +312,8 @@ function handleBboxInput() {
lat2 >= -90 && lat2 <= 90 &&
lng2 >= -180 && lng2 <= 180
) {
// Input is valid; trigger the event
const bboxText = `${lat1} ${lng1} ${lat2} ${lng2}`;
// Input is valid; trigger the event with consistent comma-separated format
const bboxText = `${lat1},${lng1},${lat2},${lng2}`;
window.dispatchEvent(new MessageEvent('message', { data: { bboxText } }));
// Show custom bbox on the map
@@ -416,11 +415,14 @@ function displayBboxInfoText(bboxText) {
}
let worldPath = "";
let isNewWorld = false;
async function selectWorld(generate_new_world) {
try {
const worldName = await invoke('gui_select_world', { generateNew: generate_new_world } );
if (worldName) {
worldPath = worldName;
isNewWorld = generate_new_world;
const lastSegment = worldName.split(/[\\/]/).pop();
document.getElementById('selected-world').textContent = lastSegment;
document.getElementById('selected-world').style.color = "#fecc44";
@@ -479,7 +481,7 @@ async function startGeneration() {
}
var terrain = document.getElementById("terrain-toggle").checked;
var winter_mode = document.getElementById("winter-toggle").checked;
var fill_ground = document.getElementById("fillground-toggle").checked;
var scale = parseFloat(document.getElementById("scale-value-slider").value);
var floodfill_timeout = parseInt(document.getElementById("floodfill-timeout").value, 10);
var ground_level = parseInt(document.getElementById("ground-level").value, 10);
@@ -494,9 +496,10 @@ async function startGeneration() {
selectedWorld: worldPath,
worldScale: scale,
groundLevel: ground_level,
winterMode: winter_mode,
floodfillTimeout: floodfill_timeout,
terrainEnabled: terrain
terrainEnabled: terrain,
fillgroundEnabled: fill_ground,
isNewWorld: isNewWorld
});
console.log("Generation process started.");

66
gui-src/js/maps/mapbox.v3.2.0.js vendored Normal file
View File

File diff suppressed because one or more lines are too long

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

@@ -0,0 +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": "خطأ: الإحداثيات خارج النطاق أو مرتبة بشكل غير صحيح (مطلوب خط العرض قبل خط الطول).",
"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} من 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": "خطأ غير معروف",
"license_and_credits": "الرخصة والمساهمون",
"placeholder_bbox": "الصيغة: lat,lng,lat,lng",
"placeholder_floodfill": "ثوانٍ",
"placeholder_ground": "مستوى الأرض"
}

View File

@@ -30,9 +30,9 @@
"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"
}
"unknown_error": "Tuntematon virhe",
"license_and_credits": "Lisenssi ja krediitit",
"placeholder_bbox": "Formaatti: lat,lng,lat,lng",
"placeholder_floodfill": "Sekuntia",
"placeholder_ground": "Maataso"
}

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

@@ -0,0 +1,38 @@
{
"select_location": "Sélectionner une localisation",
"zoom_in_and_choose": "Zoomez et choisissez une zone avec l'outil de sélection rectangulaire",
"select_world": "Sélectionner un monde",
"choose_world": "Choisir un monde",
"no_world_selected": "Aucun monde sélectionné",
"start_generation": "Commencer la génération",
"progress": "Progrès",
"custom_selection_confirmed": "Sélection personnalisée confirmée !",
"error_coordinates_out_of_range": "Erreur: Coordonnées hors de portée ou dans un ordre incorrect (besoin de la latitude avant la longitude).",
"invalid_format": "Format invalide. Utilisez 'lat,lng,lat,lng' ou 'lat lng lat lng'.",
"generation_process_started": "Processus de génération commencé.",
"winter_mode": "Mode hiver:",
"world_scale": "Échelle du monde:",
"custom_bounding_box": "Cadre de délimitation personnalisé:",
"floodfill_timeout": "Expiration du délai de remplissage (en secondes):",
"ground_level": "Niveau du sol:",
"choose_world_modal_title": "Choisir un monde",
"select_existing_world": "Sélectionner un monde existant",
"generate_new_world": "Générer un nouveau monde",
"customization_settings": "Paramètres de personnalisation",
"footer_text": "© {year} Arnis v{version} par louis-e",
"new_version_available": "Une nouvelle version est disponible ! Cliquez ici pour la télécharger.",
"minecraft_directory_not_found": "Répertoire Minecraft introuvable",
"world_in_use": "Le monde sélectionné est en cours d'utilisation",
"failed_to_create_world": "Échec de la création du nouveau monde",
"no_world_selected_error": "Aucun monde sélectionné",
"select_minecraft_world_first": "Sélectionnez d'abord un monde Minecraft !",
"select_location_first": "Sélectionnez d'abord une localisation !",
"area_too_large": "Cette zone est très grande et pourrait dépasser les limites de calcul courantes.",
"area_extensive": "Cette zone est très étendue et pourrait nécessiter beaucoup de ressources et de temps.",
"selection_confirmed": "Sélection confirmée !",
"unknown_error": "Erreur inconnue",
"license_and_credits": "Licence et crédits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Secondes",
"placeholder_ground": "Niveau du sol"
}

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

@@ -0,0 +1,38 @@
{
"select_location": "Hely kiválasztása",
"zoom_in_and_choose": "Közelíts és válaszd ki a területet a téglalap eszköz segítségével",
"select_world": "Világ kijelölése",
"choose_world": "Világ kiválasztása",
"no_world_selected": "Nincs világ kiválasztva",
"start_generation": "Generálás indítása",
"progress": "Haladás",
"custom_selection_confirmed": "Egyéni kiválasztás megerősítve",
"error_coordinates_out_of_range": "Hiba: A koordináták tartományon kívül vannak vagy hibásan rendezettek (a szélességi foknak a hosszúsági fok előtt kell lennie)",
"invalid_format": "Érvénytelen formátum. Kérjük, használja a 'lat,lng,lat,lng' vagy a 'lat lng lat lng' formátumot.'.",
"generation_process_started": "Generálási folyamat elkezdődött",
"winter_mode": "Téli mód",
"world_scale": "Világ nagysága",
"custom_bounding_box": "Egyéni határoló keret",
"floodfill_timeout": "Floodfill Timeout (sec):",
"ground_level": "Földszint",
"choose_world_modal_title": "Világ kiválasztása",
"select_existing_world": "Már létező világ kiválasztása",
"generate_new_world": "Új világ generálása",
"customization_settings": "Testreszabási lehetőségek",
"footer_text": "© {year} Arnis v{version} by louis-e",
"new_version_available": "Egy új verzió elérhető kattints ide hogy letöltsd",
"minecraft_directory_not_found": "Minecraft mappa nem található",
"world_in_use": "A kiválasztott világ már használatban van",
"failed_to_create_world": "Nem sikerült új világot létrehozni",
"no_world_selected_error": "Nincs kiválasztott világ",
"select_minecraft_world_first": "Válassz ki egy Minecraft világot először!",
"select_location_first": "Válassz egy helyet először!",
"area_too_large": "Ez a terület nagyon nagy, és meghaladhatja a szokásos számítási korlátokat.",
"area_extensive": "A terület meglehetősen kiterjedt, és jelentős időt és erőforrásokat igényelhet.",
"selection_confirmed": "Kiválasztás megerősítve",
"unknown_error": "Ismeretlen hiba",
"license_and_credits": "Licenc és elismerés.",
"placeholder_bbox": "Formátum: lat,lng,lat,lng",
"placeholder_floodfill": "Másodpercek",
"placeholder_ground": "Földszint"
}

View File

@@ -10,6 +10,7 @@
"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.",
"terrain": "Reljefas:",
"winter_mode": "Žiemos režimas:",
"world_scale": "Pasaulio mastelis:",
"custom_bounding_box": "Pasirinktinis ribos rėmas:",

View File

@@ -10,6 +10,7 @@
"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.",
"terrain": "Teren:",
"winter_mode": "Tryb Zimowy:",
"world_scale": "Skala świata:",
"custom_bounding_box": "Niestandardowy obszar:",
@@ -30,9 +31,9 @@
"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"
"unknown_error": "Nieznany błąd",
"license_and_credits": "Licencja i autorzy",
"placeholder_bbox": "Format: szer,dł,szer,dł",
"placeholder_floodfill": "Sekundy",
"placeholder_ground": "Wysokość"
}

View File

@@ -10,6 +10,7 @@
"error_coordinates_out_of_range": "Ошибка: Координаты находятся вне зоны действия или указаны в неправильном порядке (сначала широта, затем долгота)",
"invalid_format": "Неверный формат. Используйте 'широта,долгота,широта,долгота' или 'широта долгота широта долгота'",
"generation_process_started": "Процесс генерации начат",
"terrain": "Рельеф",
"winter_mode": "Зимний режим:",
"world_scale": "Масштаб мира:",
"custom_bounding_box": "Пользовательская ограничивающая рамка:",
@@ -30,9 +31,9 @@
"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"
}
"unknown_error": "Неизвестная ошибка",
"license_and_credits": "Лицензия и авторы",
"placeholder_bbox": "Формат: широта,долгота,широта,долгота",
"placeholder_floodfill": "Секунды",
"placeholder_ground": "Уровень земли"
}

View File

@@ -30,9 +30,9 @@
"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"
"unknown_error": "未知错误",
"license_and_credits": "许可证和致谢",
"placeholder_bbox": "格式: lat,lng,lat,lng",
"placeholder_floodfill": "",
"placeholder_ground": "地面高度"
}

2
gui-src/maps.html vendored
View File

@@ -7,11 +7,13 @@
<link rel="stylesheet" href="css/maps/leaflet.css" />
<link rel="stylesheet" href="css/maps/leaflet.draw.css" />
<link rel="stylesheet" href="css/maps/leaflet.sidebar.css" />
<link rel="stylesheet" href="css/maps/mapbox.v3.2.0.css" />
<link rel="stylesheet" href="css/bbox.css" />
<script src="js/libs/jquery-1.9.1.min.js"></script>
<script src="js/libs/jquery-ui-1.10.3.custom.js"></script>
<script src="js/maps/leaflet.js"></script>
<script src="js/maps/mapbox.v3.2.0.js"></script>
<script src="js/maps/leaflet.draw.js"></script>
<script src="js/maps/leaflet.sidebar.js"></script>
<script src="js/maps/wkt.parser.js"></script>

View File

@@ -1,4 +1,5 @@
use clap::{ArgGroup, Parser};
use crate::bbox::BBox;
use clap::Parser;
use colored::Colorize;
use std::path::Path;
use std::process::exit;
@@ -7,22 +8,17 @@ use std::time::Duration;
/// Command-line arguments parser
#[derive(Parser, Debug)]
#[command(author, version, about)]
#[command(group(
ArgGroup::new("location")
.required(true)
.args(&["bbox", "file"])
))]
pub struct Args {
/// Bounding box of the area (min_lng,min_lat,max_lng,max_lat) (required)
#[arg(long, allow_hyphen_values = true)]
pub bbox: Option<String>,
#[arg(long, allow_hyphen_values = true, value_parser = BBox::from_str)]
pub bbox: BBox,
/// JSON file containing OSM data (optional)
#[arg(long)]
#[arg(long, group = "location")]
pub file: Option<String>,
/// Path to the Minecraft world (required)
#[arg(long, required = true)]
#[arg(long)]
pub path: String,
/// Downloader method (requests/curl/wget) (optional)
@@ -30,23 +26,21 @@ pub struct Args {
pub downloader: String,
/// World scale to use, in blocks per meter
#[arg(long, default_value = "1.0")]
#[arg(long, default_value_t = 1.0)]
pub scale: f64,
/// Ground level to use in the Minecraft world
#[arg(long, default_value_t = -62)]
pub ground_level: i32,
/// Enable winter mode (default: false)
#[arg(long, default_value_t = false)]
pub winter: bool,
/// Enable terrain (optional)
#[arg(long, default_value_t = false, action = clap::ArgAction::SetFalse)]
#[arg(long)]
pub terrain: bool,
/// Enable filling ground (optional)
#[arg(long, default_value_t = false, action = clap::ArgAction::SetFalse)]
pub fillground: bool,
/// Enable debug mode (optional)
#[arg(long, default_value_t = false, action = clap::ArgAction::SetTrue)]
#[arg(long)]
pub debug: bool,
/// Set floodfill timeout (seconds) (optional)
@@ -67,41 +61,53 @@ impl Args {
);
exit(1);
}
// Validating bbox if provided
if let Some(bbox) = &self.bbox {
if !validate_bounding_box(bbox) {
eprintln!("{}", "Error! Invalid bbox input".red().bold());
exit(1);
}
}
}
}
/// Validates the bounding box string
fn validate_bounding_box(bbox: &str) -> bool {
let parts: Vec<&str> = bbox.split(',').collect();
if parts.len() != 4 {
return false;
}
let min_lng: f64 = parts[0].parse().ok().unwrap_or(0.0);
let min_lat: f64 = parts[1].parse().ok().unwrap_or(0.0);
let max_lng: f64 = parts[2].parse().ok().unwrap_or(0.0);
let max_lat: f64 = parts[3].parse().ok().unwrap_or(0.0);
if !(-180.0..=180.0).contains(&min_lng) || !(-180.0..=180.0).contains(&max_lng) {
return false;
}
if !(-90.0..=90.0).contains(&min_lat) || !(-90.0..=90.0).contains(&max_lat) {
return false;
}
min_lng < max_lng && min_lat < max_lat
}
fn parse_duration(arg: &str) -> Result<std::time::Duration, std::num::ParseIntError> {
let seconds = arg.parse()?;
Ok(std::time::Duration::from_secs(seconds))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_flags() {
// Test that terrain/debug are SetTrue
let cmd = [
"arnis",
"--path",
"",
"--bbox",
"1,2,3,4",
"--terrain",
"--debug",
];
let args = Args::parse_from(cmd.iter());
assert!(args.debug);
assert!(args.terrain);
let cmd = ["arnis", "--path", "", "--bbox", "1,2,3,4"];
let args = Args::parse_from(cmd.iter());
assert!(!args.debug);
assert!(!args.terrain);
}
#[test]
fn test_required_options() {
let cmd = ["arnis"];
assert!(Args::try_parse_from(cmd.iter()).is_err());
let cmd = ["arnis", "--path", "", "--bbox", "1,2,3,4"];
assert!(Args::try_parse_from(cmd.iter()).is_ok());
let cmd = ["arnis", "--path", "", "--file", ""];
assert!(Args::try_parse_from(cmd.iter()).is_err());
// The --gui flag isn't used here, ugh. TODO clean up main.rs and its argparse usage.
// let cmd = ["arnis", "--gui"];
// assert!(Args::try_parse_from(cmd.iter()).is_ok());
}
}

101
src/bbox.rs Normal file
View File

@@ -0,0 +1,101 @@
use crate::geo_coord::GeoCoord;
/// A checked Bounding Box.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct BBox {
/// The "bottom-left" vertex of the rectangle
min: GeoCoord,
/// The "top-right" vertex of the rectangle
max: GeoCoord,
}
impl BBox {
pub fn new(min_lat: f64, min_lng: f64, max_lat: f64, max_lng: f64) -> Result<Self, String> {
let vals_in_order = min_lng < max_lng && min_lat < max_lat;
if !vals_in_order {
return Err("Invalid BBox".to_string());
}
let min = GeoCoord::new(min_lat, min_lng)?;
let max = GeoCoord::new(max_lat, max_lng)?;
Ok(Self { min, max })
}
pub fn from_str(s: &str) -> Result<Self, String> {
let [min_lat, min_lng, max_lat, max_lng]: [f64; 4] = s
.split([',', ' '])
.map(|e| e.parse().unwrap())
.collect::<Vec<_>>()
.try_into()
.unwrap();
// So, the GUI does Lat/Lng and no GDAL (comma-sep values), which is the exact opposite of
// what bboxfinder.com does. :facepalm: (bboxfinder is wrong here: Lat comes first!)
// DO NOT MODIFY THIS! It's correct. The CLI/GUI is passing you the numbers incorrectly.
Self::new(min_lat, min_lng, max_lat, max_lng)
}
pub fn min(&self) -> GeoCoord {
self.min
}
pub fn max(&self) -> GeoCoord {
self.max
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_input() {
assert!(BBox::new(0., 0., 1., 1.).is_ok());
assert!(BBox::new(1., 2., 3., 4.).is_ok());
// Arnis, Germany
assert!(BBox::new(9.927928, 54.627053, 9.937563, 54.634902).is_ok());
}
#[test]
fn test_from_str_commas() {
const ARNIS_STR: &str = "9.927928,54.627053,9.937563,54.634902";
let bbox_result = BBox::from_str(ARNIS_STR);
assert!(bbox_result.is_ok());
let arnis_correct: BBox = BBox {
min: GeoCoord::new(9.927928, 54.627053).unwrap(),
max: GeoCoord::new(9.937563, 54.634902).unwrap(),
};
assert_eq!(bbox_result.unwrap(), arnis_correct);
}
#[test]
fn test_from_str_spaces() {
const ARNIS_SPACE_STR: &str = "9.927928 54.627053 9.937563 54.634902";
let bbox_result = BBox::from_str(ARNIS_SPACE_STR);
assert!(bbox_result.is_ok());
let arnis_correct: BBox = BBox {
min: GeoCoord::new(9.927928, 54.627053).unwrap(),
max: GeoCoord::new(9.937563, 54.634902).unwrap(),
};
assert_eq!(bbox_result.unwrap(), arnis_correct);
}
#[test]
fn test_out_of_order() {
// Violates values in vals_in_order
assert!(BBox::new(0., 0., 0., 0.).is_err());
assert!(BBox::new(1., 0., 0., 1.).is_err());
assert!(BBox::new(0., 1., 1., 0.).is_err());
}
}

View File

@@ -22,7 +22,7 @@ impl Block {
}
pub fn namespace(&self) -> &str {
"mincraft"
"minecraft"
}
pub fn name(&self) -> &str {
@@ -56,7 +56,7 @@ impl Block {
26 => "glowstone",
27 => "granite",
28 => "grass_block",
29 => "tall_grass",
29 => "short_grass",
30 => "gravel",
31 => "gray_concrete",
32 => "gray_terracotta",
@@ -144,12 +144,36 @@ impl Block {
114 => "andesite_wall",
115 => "stone_brick_wall",
116..=125 => "rail",
126 => "coarse_dirt",
127 => "iron_ore",
128 => "coal_ore",
129 => "gold_ore",
130 => "copper_ore",
131 => "clay",
132 => "dirt_path",
133 => "ice",
134 => "packed_ice",
135 => "mud",
136 => "dead_bush",
137..=138 => "tall_grass",
_ => panic!("Invalid id"),
}
}
pub fn properties(&self) -> Option<Value> {
match self.id {
3 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("persistent".to_string(), Value::String("true".to_string()));
map
})),
49 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("persistent".to_string(), Value::String("true".to_string()));
map
})),
105 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("age".to_string(), Value::String("7".to_string()));
@@ -264,6 +288,16 @@ impl Block {
map.insert("shape".to_string(), Value::String("south_west".to_string()));
map
})),
137 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert("half".to_string(), Value::String("lower".to_string()));
map
})),
138 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert("half".to_string(), Value::String("upper".to_string()));
map
})),
_ => None,
}
}
@@ -400,96 +434,104 @@ 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);
pub const COARSE_DIRT: Block = Block::new(126);
pub const IRON_ORE: Block = Block::new(127);
pub const COAL_ORE: Block = Block::new(128);
pub const GOLD_ORE: Block = Block::new(129);
pub const COPPER_ORE: Block = Block::new(130);
pub const CLAY: Block = Block::new(131);
pub const DIRT_PATH: Block = Block::new(132);
pub const ICE: Block = Block::new(133);
pub const PACKED_ICE: Block = Block::new(134);
pub const MUD: Block = Block::new(135);
pub const DEAD_BUSH: Block = Block::new(136);
pub const TALL_GRASS_BOTTOM: Block = Block::new(137);
pub const TALL_GRASS_TOP: Block = Block::new(138);
// Variations for building corners
pub fn building_corner_variations() -> Vec<Block> {
vec![
STONE_BRICKS,
COBBLESTONE,
BRICK,
MOSSY_COBBLESTONE,
SANDSTONE,
RED_NETHER_BRICKS,
BLACKSTONE,
SMOOTH_QUARTZ,
CHISELED_STONE_BRICKS,
POLISHED_BASALT,
CUT_SANDSTONE,
POLISHED_BLACKSTONE_BRICKS,
ANDESITE,
GRANITE,
DIORITE,
CRACKED_STONE_BRICKS,
PRISMARINE,
BLUE_TERRACOTTA,
NETHER_BRICK,
QUARTZ_BRICKS,
]
}
pub static BUILDING_CORNER_VARIATIONS: [Block; 20] = [
STONE_BRICKS,
COBBLESTONE,
BRICK,
MOSSY_COBBLESTONE,
SANDSTONE,
RED_NETHER_BRICKS,
BLACKSTONE,
SMOOTH_QUARTZ,
CHISELED_STONE_BRICKS,
POLISHED_BASALT,
CUT_SANDSTONE,
POLISHED_BLACKSTONE_BRICKS,
ANDESITE,
GRANITE,
DIORITE,
CRACKED_STONE_BRICKS,
PRISMARINE,
BLUE_TERRACOTTA,
NETHER_BRICK,
QUARTZ_BRICKS,
];
// Variations for building walls
pub fn building_wall_variations() -> Vec<Block> {
building_wall_color_map()
BUILDING_WALL_COLOR_MAP
.into_iter()
.map(|(_, block)| block)
.collect()
}
// https://wiki.openstreetmap.org/wiki/Key:building:colour
pub fn building_wall_color_map() -> Vec<(RGBTuple, Block)> {
vec![
((233, 107, 57), BRICK),
((18, 12, 13), CRACKED_POLISHED_BLACKSTONE_BRICKS),
((76, 127, 153), CYAN_CONCRETE),
((0, 0, 0), DEEPSLATE_BRICKS),
((186, 195, 142), END_STONE_BRICKS),
((57, 41, 35), GRAY_TERRACOTTA),
((112, 108, 138), LIGHT_BLUE_TERRACOTTA),
((122, 92, 66), MUD_BRICKS),
((24, 13, 14), NETHER_BRICKS),
((159, 82, 36), ORANGE_TERRACOTTA),
((128, 128, 128), POLISHED_ANDESITE),
((174, 173, 174), POLISHED_DIORITE),
((141, 101, 142), PURPUR_PILLAR),
((142, 60, 46), RED_TERRACOTTA),
((153, 83, 28), SMOOTH_RED_SANDSTONE),
((224, 216, 175), SMOOTH_SANDSTONE),
((188, 182, 179), SMOOTH_STONE),
((35, 86, 85), WARPED_PLANKS),
((255, 255, 255), WHITE_CONCRETE),
((209, 177, 161), WHITE_TERRACOTTA),
((191, 147, 42), YELLOW_TERRACOTTA),
]
}
pub static BUILDING_WALL_COLOR_MAP: [(RGBTuple, Block); 21] = [
((233, 107, 57), BRICK),
((18, 12, 13), CRACKED_POLISHED_BLACKSTONE_BRICKS),
((76, 127, 153), CYAN_CONCRETE),
((0, 0, 0), DEEPSLATE_BRICKS),
((186, 195, 142), END_STONE_BRICKS),
((57, 41, 35), GRAY_TERRACOTTA),
((112, 108, 138), LIGHT_BLUE_TERRACOTTA),
((122, 92, 66), MUD_BRICKS),
((24, 13, 14), NETHER_BRICKS),
((159, 82, 36), ORANGE_TERRACOTTA),
((128, 128, 128), POLISHED_ANDESITE),
((174, 173, 174), POLISHED_DIORITE),
((141, 101, 142), PURPUR_PILLAR),
((142, 60, 46), RED_TERRACOTTA),
((153, 83, 28), SMOOTH_RED_SANDSTONE),
((224, 216, 175), SMOOTH_SANDSTONE),
((188, 182, 179), SMOOTH_STONE),
((35, 86, 85), WARPED_PLANKS),
((255, 255, 255), WHITE_CONCRETE),
((209, 177, 161), WHITE_TERRACOTTA),
((191, 147, 42), YELLOW_TERRACOTTA),
];
// Variations for building floors
pub fn building_floor_variations() -> Vec<Block> {
building_wall_color_map()
BUILDING_WALL_COLOR_MAP
.into_iter()
.map(|(_, block)| block)
.collect()
}
pub fn building_floor_color_map() -> Vec<(RGBTuple, Block)> {
vec![
((181, 101, 59), ACACIA_PLANKS),
((22, 15, 16), BLACKSTONE),
((104, 51, 74), CRIMSON_PLANKS),
((82, 55, 26), DARK_OAK_PLANKS),
((182, 133, 99), JUNGLE_PLANKS),
((33, 128, 185), LIGHT_BLUE_CONCRETE),
((78, 103, 43), MOSS_BLOCK),
((171, 138, 88), OAK_PLANKS),
((0, 128, 0), OXIDIZED_COPPER),
((18, 12, 13), POLISHED_BLACKSTONE),
((64, 64, 64), POLISHED_DEEPSLATE),
((255, 255, 255), POLISHED_DIORITE),
((143, 96, 79), POLISHED_GRANITE),
((141, 101, 142), PURPUR_BLOCK),
((128, 0, 0), RED_NETHER_BRICKS),
((153, 83, 28), SMOOTH_RED_SANDSTONE),
((128, 96, 57), SPRUCE_PLANKS),
((128, 128, 128), STONE_BRICKS),
((150, 93, 68), TERRACOTTA),
((35, 86, 85), WARPED_PLANKS),
]
}
pub static BUILDING_FLOOR_COLOR_MAP: [(RGBTuple, Block); 20] = [
((181, 101, 59), ACACIA_PLANKS),
((22, 15, 16), BLACKSTONE),
((104, 51, 74), CRIMSON_PLANKS),
((82, 55, 26), DARK_OAK_PLANKS),
((182, 133, 99), JUNGLE_PLANKS),
((33, 128, 185), LIGHT_BLUE_CONCRETE),
((78, 103, 43), MOSS_BLOCK),
((171, 138, 88), OAK_PLANKS),
((0, 128, 0), OXIDIZED_COPPER),
((18, 12, 13), POLISHED_BLACKSTONE),
((64, 64, 64), POLISHED_DEEPSLATE),
((255, 255, 255), POLISHED_DIORITE),
((143, 96, 79), POLISHED_GRANITE),
((141, 101, 142), PURPUR_BLOCK),
((128, 0, 0), RED_NETHER_BRICKS),
((153, 83, 28), SMOOTH_RED_SANDSTONE),
((128, 96, 57), SPRUCE_PLANKS),
((128, 128, 128), STONE_BRICKS),
((150, 93, 68), TERRACOTTA),
((35, 86, 85), WARPED_PLANKS),
];

View File

@@ -37,11 +37,11 @@ fn short_hex_color_to_rgb_tuple(text: &str) -> Option<RGBTuple> {
return None;
}
let r: u8 = u8::from_str_radix(&text[1..2], 16).unwrap();
let r: u8 = r | r << 4;
let r: u8 = r | (r << 4);
let g: u8 = u8::from_str_radix(&text[2..3], 16).unwrap();
let g: u8 = g | g << 4;
let g: u8 = g | (g << 4);
let b: u8 = u8::from_str_radix(&text[3..4], 16).unwrap();
let b: u8 = b | b << 4;
let b: u8 = b | (b << 4);
Some((r, g, b))
}

View File

@@ -1,6 +1,5 @@
use crate::args::Args;
use crate::block_definitions::{DIRT, GRASS_BLOCK, SNOW_BLOCK};
use crate::cartesian::XZPoint;
use crate::block_definitions::{BEDROCK, DIRT, GRASS_BLOCK, STONE};
use crate::element_processing::*;
use crate::ground::Ground;
use crate::osm_parser::ProcessedElement;
@@ -9,7 +8,7 @@ use crate::world_editor::WorldEditor;
use colored::Colorize;
use indicatif::{ProgressBar, ProgressStyle};
const MIN_Y: i32 = -64;
pub const MIN_Y: i32 = -64;
pub fn generate_world(
elements: Vec<ProcessedElement>,
@@ -26,6 +25,9 @@ pub fn generate_world(
}
let ground: Ground = Ground::new(args);
// Set ground reference in the editor to enable elevation-aware block placement
editor.set_ground(&ground);
emit_gui_progress_update(11.0, "Processing terrain...");
// Process data
@@ -61,56 +63,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, args, None);
buildings::generate_buildings(&mut editor, way, args, None);
} else if way.tags.contains_key("highway") {
highways::generate_highways(&mut editor, element, &ground, args);
highways::generate_highways(&mut editor, element, args);
} else if way.tags.contains_key("landuse") {
landuse::generate_landuse(&mut editor, way, &ground, args);
landuse::generate_landuse(&mut editor, way, args);
} else if way.tags.contains_key("natural") {
natural::generate_natural(&mut editor, element, &ground, args);
natural::generate_natural(&mut editor, element, args);
} else if way.tags.contains_key("amenity") {
amenities::generate_amenities(&mut editor, element, &ground, args);
amenities::generate_amenities(&mut editor, element, args);
} else if way.tags.contains_key("leisure") {
leisure::generate_leisure(&mut editor, way, &ground, args);
leisure::generate_leisure(&mut editor, way, args);
} else if way.tags.contains_key("barrier") {
barriers::generate_barriers(&mut editor, element, &ground);
barriers::generate_barriers(&mut editor, element);
} else if way.tags.contains_key("waterway") {
waterways::generate_waterways(&mut editor, way, &ground);
waterways::generate_waterways(&mut editor, way);
} 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);
} else if way.tags.contains_key("railway") || way.tags.contains_key("subway") {
railways::generate_railways(&mut editor, way);
} else if way.tags.contains_key("aeroway") || way.tags.contains_key("area:aeroway")
{
highways::generate_aeroway(&mut editor, way, &ground);
highways::generate_aeroway(&mut editor, way);
} else if way.tags.get("service") == Some(&"siding".to_string()) {
highways::generate_siding(&mut editor, way, &ground);
highways::generate_siding(&mut editor, way);
}
}
ProcessedElement::Node(node) => {
if node.tags.contains_key("door") || node.tags.contains_key("entrance") {
doors::generate_doors(&mut editor, node, &ground);
doors::generate_doors(&mut editor, node);
} else if node.tags.contains_key("natural")
&& node.tags.get("natural") == Some(&"tree".to_string())
{
natural::generate_natural(&mut editor, element, &ground, args);
natural::generate_natural(&mut editor, element, args);
} else if node.tags.contains_key("amenity") {
amenities::generate_amenities(&mut editor, element, &ground, args);
amenities::generate_amenities(&mut editor, element, args);
} else if node.tags.contains_key("barrier") {
barriers::generate_barriers(&mut editor, element, &ground);
barriers::generate_barriers(&mut editor, element);
} else if node.tags.contains_key("highway") {
highways::generate_highways(&mut editor, element, &ground, args);
highways::generate_highways(&mut editor, element, args);
} else if node.tags.contains_key("tourism") {
tourisms::generate_tourisms(&mut editor, node, &ground);
tourisms::generate_tourisms(&mut editor, node);
}
}
ProcessedElement::Relation(rel) => {
if rel.tags.contains_key("building") || rel.tags.contains_key("building:part") {
buildings::generate_building_from_relation(&mut editor, rel, &ground, args);
buildings::generate_building_from_relation(&mut editor, rel, args);
} else if rel.tags.contains_key("water") {
water_areas::generate_water_areas(&mut editor, rel, &ground);
water_areas::generate_water_areas(&mut editor, rel);
} else if rel.tags.get("leisure") == Some(&"park".to_string()) {
leisure::generate_leisure_from_relation(&mut editor, rel, &ground, args);
leisure::generate_leisure_from_relation(&mut editor, rel, args);
}
}
}
@@ -141,72 +143,44 @@ pub fn generate_world(
let total_iterations_grnd: f64 = (scale_factor_x + 1.0) * (scale_factor_z + 1.0);
let progress_increment_grnd: f64 = 30.0 / total_iterations_grnd;
let groundlayer_block = if args.winter { SNOW_BLOCK } else { GRASS_BLOCK };
let groundlayer_block = GRASS_BLOCK;
// 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)));
for x in 0..=(scale_factor_x as i32) {
for z in 0..=(scale_factor_z as i32) {
// Add default dirt and grass layer if there isn't a stone layer already
if !editor.check_for_block(x, 0, z, Some(&[STONE])) {
editor.set_block(groundlayer_block, x, 0, z, None, None);
editor.set_block(DIRT, x, -1, z, None, None);
editor.set_block(DIRT, x, -2, z, None, None);
}
ground_levels.push(row);
}
// 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;
}
// Fill underground with stone
if args.fillground {
// Fill from bedrock+1 to 3 blocks below ground with stone
editor.fill_blocks_absolute(
STONE,
x,
MIN_Y + 1,
z,
x,
editor.get_absolute_y(x, -3, z),
z,
None,
None,
);
}
}
// Generate a bedrock level at MIN_Y
editor.set_block_absolute(BEDROCK, x, MIN_Y, z, None, Some(&[BEDROCK]));
// 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);
block_counter += 1;
if block_counter % batch_size == 0 {
ground_pb.inc(batch_size);
}
}
} 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;
}
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;
}
}
}

View File

@@ -3,16 +3,10 @@ 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: &Ground,
args: &Args,
) {
pub fn generate_amenities(editor: &mut WorldEditor, element: &ProcessedElement, args: &Args) {
// 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 {
@@ -35,15 +29,13 @@ pub fn generate_amenities(
"waste_disposal" | "waste_basket" => {
// Place a cauldron for waste disposal or waste basket
if let Some(pt) = first_node {
editor.set_block(CAULDRON, pt.x, ground.level(pt) + 1, pt.z, None, None);
editor.set_block(CAULDRON, pt.x, 1, pt.z, None, None);
}
}
"vending_machine" | "atm" => {
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);
editor.set_block(IRON_BLOCK, pt.x, 1, pt.z, None, None);
editor.set_block(IRON_BLOCK, pt.x, 2, pt.z, None, None);
}
}
"bicycle_parking" => {
@@ -54,61 +46,50 @@ pub fn generate_amenities(
.nodes()
.map(|n: &crate::osm_parser::ProcessedNode| (n.x, n.z))
.collect();
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() {
if polygon_coords.is_empty() {
return;
}
let y_min = ground.min_level(pts.iter().cloned()).unwrap();
let roof_y = ground.max_level(pts.iter().cloned()).unwrap() + 5;
let floor_area: Vec<(i32, i32)> =
flood_fill_area(&polygon_coords, args.timeout.as_ref());
// Fill the floor area
for (x, z) in floor_area.iter() {
editor.set_block(ground_block, *x, y_min, *z, None, None);
editor.set_block(ground_block, *x, 0, *z, None, None);
}
// Place fences and roof slabs at each corner node directly
// Place fences and roof slabs at each corner node
for node in element.nodes() {
let x: i32 = node.x;
let z: i32 = node.z;
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);
// Set ground block and fences
editor.set_block(ground_block, x, 0, z, None, None);
for y in 1..=4 {
editor.set_block(OAK_FENCE, x, y, z, None, None);
}
editor.set_block(roof_block, x, roof_y, z, None, None);
editor.set_block(roof_block, x, 5, z, None, None);
}
// Flood fill the roof area
for (x, z) in floor_area.iter() {
editor.set_block(roof_block, *x, roof_y, *z, None, None);
editor.set_block(roof_block, *x, 5, *z, None, None);
}
}
"bench" => {
// Place a bench
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);
editor.set_block(SMOOTH_STONE, pt.x, 1, pt.z, None, None);
editor.set_block(OAK_LOG, pt.x + 1, 1, pt.z, None, None);
editor.set_block(OAK_LOG, pt.x - 1, 1, pt.z, None, None);
}
}
"vending" => {
// Place vending machine blocks
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);
editor.set_block(IRON_BLOCK, pt.x, 1, pt.z, None, None);
editor.set_block(IRON_BLOCK, pt.x, 2, pt.z, None, None);
}
}
"shelter" => {
@@ -126,24 +107,15 @@ pub fn generate_amenities(
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(OAK_FENCE, x, fence_height, z, None, None);
}
editor.set_block(roof_block, x, y + 5, z, None, None);
editor.set_block(roof_block, x, 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);
editor.set_block(roof_block, *x, 5, *z, None, None);
}
}
"parking" | "fountain" => {
@@ -160,15 +132,13 @@ pub fn generate_amenities(
for node in element.nodes() {
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.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);
bresenham_line(prev.x, 0, prev.z, pt.x, 0, pt.z);
for (bx, _, bz) in bresenham_points {
editor.set_block(block_type, bx, 0, bz, Some(&[BLACK_CONCRETE]), None);
// Decorative border around fountains
if amenity_type == "fountain" {
@@ -178,7 +148,7 @@ pub fn generate_amenities(
editor.set_block(
LIGHT_GRAY_CONCRETE,
bx + dx,
by,
0,
bz + dz,
None,
None,
@@ -204,12 +174,10 @@ 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,
y,
0,
z,
Some(&[BLACK_CONCRETE, GRAY_CONCRETE]),
None,
@@ -220,7 +188,7 @@ pub fn generate_amenities(
editor.set_block(
LIGHT_GRAY_CONCRETE,
x,
y,
0,
z,
Some(&[BLACK_CONCRETE, GRAY_CONCRETE]),
None,

View File

@@ -1,11 +1,9 @@
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: &Ground) {
pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement) {
// Default values
let mut barrier_material: Block = COBBLESTONE_WALL;
let mut barrier_height: i32 = 2;
@@ -13,15 +11,8 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement, g
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(node.xz()) + 1,
node.z,
None,
None,
);
// Place bollard
// Place bollard one above ground
editor.set_block(COBBLESTONE_WALL, node.x, 1, node.z, None, None);
}
return;
}
@@ -96,22 +87,13 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement, g
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) {
for y in 1..=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
editor.set_block(STONE_BRICK_SLAB, bx, wall_height + 1, bz, None, None);
}
}
}

View File

@@ -1,19 +1,18 @@
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
//use crate::ground::Ground;
use crate::osm_parser::ProcessedWay;
use crate::world_editor::WorldEditor;
// TODO FIX
#[allow(dead_code)]
pub fn generate_bridges(editor: &mut WorldEditor, element: &ProcessedWay, ground_level: i32) {
pub fn generate_bridges(editor: &mut WorldEditor, element: &ProcessedWay) {
if let Some(_bridge_type) = element.tags.get("bridge") {
let bridge_height = 3; // Fixed height
for i in 1..element.nodes.len() {
let prev = &element.nodes[i - 1];
let cur = &element.nodes[i];
let points = bresenham_line(prev.x, ground_level, prev.z, cur.x, ground_level, cur.z);
let points = bresenham_line(prev.x, 0, prev.z, cur.x, 0, cur.z);
let total_length = points.len();
let ramp_length = 6; // Length of ramp at each end
@@ -30,11 +29,9 @@ pub fn generate_bridges(editor: &mut WorldEditor, element: &ProcessedWay, ground
bridge_height
};
let bridge_y = ground_level + height as i32;
// Place bridge blocks
for dx in -2..=2 {
editor.set_block(LIGHT_GRAY_CONCRETE, *x + dx, bridge_y, *z, None, None);
editor.set_block(LIGHT_GRAY_CONCRETE, *x + dx, height as i32, *z, None, None);
}
}
}

View File

@@ -1,10 +1,8 @@
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;
@@ -14,14 +12,9 @@ use std::time::Duration;
pub fn generate_buildings(
editor: &mut WorldEditor,
element: &ProcessedWay,
ground: &Ground,
args: &Args,
relation_levels: Option<i32>,
) {
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)
@@ -29,8 +22,8 @@ pub fn generate_buildings(
0
};
// Calculate starting level using base_y and min_level
let start_level = base_y + (min_level * 4);
// Calculate starting y-offset from min_level
let start_y_offset = min_level * 4;
let mut previous_node: Option<(i32, i32)> = None;
let mut corner_addup: (i32, i32, i32) = (0, 0, 0);
@@ -38,17 +31,17 @@ pub fn generate_buildings(
// Randomly select block variations for corners, walls, and floors
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
let variation_index_corner: usize = rng.gen_range(0..building_corner_variations().len());
let variation_index_corner: usize = rng.gen_range(0..BUILDING_CORNER_VARIATIONS.len());
let variation_index_wall: usize = rng.gen_range(0..building_wall_variations().len());
let variation_index_floor: usize = rng.gen_range(0..building_floor_variations().len());
let corner_block: Block = building_corner_variations()[variation_index_corner];
let corner_block: Block = BUILDING_CORNER_VARIATIONS[variation_index_corner];
let wall_block: Block = element
.tags
.get("building:colour")
.and_then(|building_colour: &String| {
color_text_to_rgb_tuple(building_colour).map(|rgb: (u8, u8, u8)| {
find_nearest_block_in_color_map(&rgb, building_wall_color_map())
find_nearest_block_in_color_map(&rgb, &BUILDING_WALL_COLOR_MAP)
})
})
.flatten()
@@ -58,7 +51,7 @@ pub fn generate_buildings(
.get("roof:colour")
.and_then(|roof_colour: &String| {
color_text_to_rgb_tuple(roof_colour).map(|rgb: (u8, u8, u8)| {
find_nearest_block_in_color_map(&rgb, building_floor_color_map())
find_nearest_block_in_color_map(&rgb, &BUILDING_FLOOR_COLOR_MAP)
})
})
.flatten()
@@ -140,24 +133,15 @@ pub fn generate_buildings(
let x: i32 = node.x;
let z: i32 = node.z;
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(OAK_FENCE, x, shelter_y, z, None, None);
}
editor.set_block(roof_block, x, y + 5, z, None, None);
editor.set_block(roof_block, x, 5, z, None, None);
}
// Flood fill the roof area
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);
editor.set_block(roof_block, *x, 5, *z, None, None);
}
return;
@@ -182,13 +166,9 @@ 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, y, *z, None, None);
editor.set_block(ground_block, *x, 0, *z, None, None);
}
// Place fences and roof slabs at each corner node directly
@@ -197,15 +177,14 @@ pub fn generate_buildings(
let z: i32 = node.z;
for dy in 1..=4 {
editor.set_block(OAK_FENCE, x, y + dy, z, None, None);
editor.set_block(OAK_FENCE, x, dy, z, None, None);
}
editor.set_block(roof_block, x, y + 5, z, None, None);
editor.set_block(roof_block, x, 5, z, None, None);
}
// Flood fill the roof area
let roof_height: i32 = y + 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, 5, *z, None, None);
}
return;
@@ -229,12 +208,8 @@ 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;
let current_level_y = level * 4;
// Build walls
for node in &element.nodes {
@@ -242,7 +217,7 @@ pub fn generate_buildings(
let z: i32 = node.z;
// Build walls up to the current level
for y in (current_level + 1)..=(current_level + 4) {
for y in (current_level_y + 1)..=(current_level_y + 4) {
editor.set_block(STONE_BRICKS, x, y, z, None, None);
}
}
@@ -250,16 +225,16 @@ pub fn generate_buildings(
// Fill the floor area for each level
for (x, z) in &floor_area {
if level == 0 {
editor.set_block(SMOOTH_STONE, *x, current_level, *z, None, None);
editor.set_block(SMOOTH_STONE, *x, current_level_y, *z, None, None);
} else {
editor.set_block(COBBLESTONE, *x, current_level, *z, None, None);
editor.set_block(COBBLESTONE, *x, current_level_y, *z, None, None);
}
}
}
// Outline for each level
for level in 0..=(building_height / 4) {
let current_level = ground_level + level * 4;
let current_level_y = level * 4;
// Use the nodes to create the outline
let mut prev_outline = None;
@@ -269,12 +244,12 @@ pub fn generate_buildings(
if let Some((prev_x, prev_z)) = prev_outline {
let outline_points =
bresenham_line(prev_x, current_level, prev_z, x, current_level, z);
bresenham_line(prev_x, current_level_y, prev_z, x, current_level_y, z);
for (bx, _, bz) in outline_points {
editor.set_block(
SMOOTH_STONE,
bx,
current_level,
current_level_y,
bz,
Some(&[COBBLESTONE, COBBLESTONE_WALL]),
None,
@@ -282,7 +257,7 @@ pub fn generate_buildings(
editor.set_block(
STONE_BRICK_SLAB,
bx,
current_level + 2,
current_level_y + 2,
bz,
None,
None,
@@ -291,7 +266,7 @@ pub fn generate_buildings(
editor.set_block(
COBBLESTONE_WALL,
bx,
current_level + 1,
current_level_y + 1,
bz,
None,
None,
@@ -305,10 +280,7 @@ 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;
let roof_height: i32 = 5;
// Iterate through the nodes to create the roof edges using Bresenham's line algorithm
for node in &element.nodes {
@@ -324,7 +296,7 @@ pub fn generate_buildings(
}
}
for y in (ground_level + 1)..=(roof_height - 1) {
for y in 1..=(roof_height - 1) {
editor.set_block(COBBLESTONE_WALL, x, y, z, None, None);
}
@@ -358,7 +330,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, args.timeout.as_ref());
generate_bridge(editor, element, args.timeout.as_ref());
return;
}
}
@@ -370,15 +342,16 @@ pub fn generate_buildings(
if let Some(prev) = previous_node {
// Calculate walls and corners using Bresenham line
let bresenham_points = bresenham_line(prev.0, start_level, prev.1, x, start_level, z);
let bresenham_points =
bresenham_line(prev.0, start_y_offset, prev.1, x, start_y_offset, z);
for (bx, _, bz) in bresenham_points {
for h in (start_level + 1)..=(start_level + building_height) {
for h in (start_y_offset + 1)..=(start_y_offset + building_height) {
if element.nodes[0].x == bx && element.nodes[0].x == bz {
// 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 {
if h > start_y_offset + 1 && h % 4 != 0 && (bx + bz) % 6 < 3 {
editor.set_block(window_block, bx, h, bz, None, None);
} else {
editor.set_block(wall_block, bx, h, bz, None, None);
@@ -389,23 +362,12 @@ pub fn generate_buildings(
editor.set_block(
COBBLESTONE,
bx,
start_level + building_height + 1,
start_y_offset + building_height + 1,
bz,
None,
None,
);
if args.winter {
editor.set_block(
SNOW_LAYER,
bx,
start_level + building_height + 2,
bz,
None,
None,
);
}
current_building.push((bx, bz));
corner_addup = (corner_addup.0 + bx, corner_addup.1 + bz, corner_addup.2 + 1);
}
@@ -425,12 +387,12 @@ pub fn generate_buildings(
for (x, z) in floor_area {
if processed_points.insert((x, z)) {
// Set floor at start_level
editor.set_block(floor_block, x, start_level, z, None, None);
// Set floor at start_y_offset
editor.set_block(floor_block, x, start_y_offset, 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) {
for h in (start_y_offset + 2 + 4..start_y_offset + building_height).step_by(4) {
if x % 6 == 0 && z % 6 == 0 {
// Light fixtures
editor.set_block(GLOWSTONE, x, h, z, None, None);
@@ -439,29 +401,25 @@ pub fn generate_buildings(
}
}
} else if x % 6 == 0 && z % 6 == 0 {
editor.set_block(GLOWSTONE, x, start_level + building_height, z, None, None);
editor.set_block(
GLOWSTONE,
x,
start_y_offset + building_height,
z,
None,
None,
);
}
// Set ceiling at proper height
editor.set_block(
floor_block,
x,
start_level + building_height + 1,
start_y_offset + building_height + 1,
z,
None,
None,
);
if args.winter {
editor.set_block(
SNOW_LAYER,
x,
start_level + building_height + 2,
z,
None,
None,
);
}
}
}
}
@@ -470,7 +428,6 @@ pub fn generate_buildings(
pub fn generate_building_from_relation(
editor: &mut WorldEditor,
relation: &ProcessedRelation,
ground: &Ground,
args: &Args,
) {
// Extract levels from relation tags
@@ -483,7 +440,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, args, Some(relation_levels));
generate_buildings(editor, &member.way, args, Some(relation_levels));
}
}
@@ -505,19 +462,19 @@ pub fn generate_building_from_relation(
fn find_nearest_block_in_color_map(
rgb: &RGBTuple,
color_map: Vec<(RGBTuple, Block)>,
color_map: &[(RGBTuple, Block)],
) -> Option<Block> {
color_map
.into_iter()
.iter()
.min_by_key(|(entry_rgb, _)| rgb_distance(entry_rgb, rgb))
.map(|(_, block)| block)
.copied()
}
/// Generates a bridge structure, paying attention to the "level" tag.
fn generate_bridge(
editor: &mut WorldEditor,
element: &ProcessedWay,
ground: &Ground,
floodfill_timeout: Option<&Duration>,
) {
let floor_block: Block = STONE;
@@ -529,20 +486,21 @@ 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") {
// Calculate bridge level based on the "level" tag
let bridge_y_offset = if let Some(level_str) = element.tags.get("level") {
if let Ok(level) = level_str.parse::<i32>() {
bridge_level += (level * 3) + 1;
(level * 3) + 1
} else {
1 // Default elevation
}
}
} else {
1 // Default elevation
};
// 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);
bresenham_line(prev.0, bridge_y_offset, prev.1, x, bridge_y_offset, z);
for (bx, by, bz) in bridge_points {
// Place railing blocks
@@ -555,30 +513,23 @@ fn generate_bridge(
}
// Flood fill the area between the bridge path nodes
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();
let polygon_coords: Vec<(i32, i32)> = element.nodes.iter().map(|n| (n.x, n.z)).collect();
for pt in bridge_area {
// Calculate the bridge's floor level dynamically
let mut bridge_level = ground.level(pt);
let bridge_area: Vec<(i32, i32)> = flood_fill_area(&polygon_coords, floodfill_timeout);
// 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;
}
// Calculate bridge level based on the "level" tag
let bridge_y_offset = if let Some(level_str) = element.tags.get("level") {
if let Ok(level) = level_str.parse::<i32>() {
(level * 3) + 1
} else {
1 // Default elevation
}
} else {
1 // Default elevation
};
// Place floor blocks
editor.set_block(floor_block, pt.x, bridge_level, pt.z, None, None);
// Place floor blocks
for (x, z) in bridge_area {
editor.set_block(floor_block, x, bridge_y_offset, z, None, None);
}
}

View File

@@ -1,10 +1,8 @@
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: &Ground) {
pub fn generate_doors(editor: &mut WorldEditor, element: &ProcessedNode) {
// 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
@@ -19,12 +17,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);
editor.set_block(DARK_OAK_DOOR_UPPER, x, ground_level + 2, z, None, None);
editor.set_block(GRAY_CONCRETE, x, 0, z, None, None);
editor.set_block(DARK_OAK_DOOR_LOWER, x, 1, z, None, None);
editor.set_block(DARK_OAK_DOOR_UPPER, x, 2, z, None, None);
}
}

View File

@@ -3,27 +3,20 @@ 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: &Ground,
args: &Args,
) {
pub fn generate_highways(editor: &mut WorldEditor, element: &ProcessedElement, args: &Args) {
if let Some(highway_type) = element.tags().get("highway") {
if highway_type == "street_lamp" {
// 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 dy in 1..=4 {
editor.set_block(OAK_FENCE, x, y + dy, z, None, None);
editor.set_block(OAK_FENCE, x, dy, z, None, None);
}
editor.set_block(GLOWSTONE, x, y + 5, z, None, None);
editor.set_block(GLOWSTONE, x, 5, z, None, None);
}
} else if highway_type == "crossing" {
// Handle traffic signals for crossings
@@ -31,20 +24,15 @@ 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 dy in 1..=3 {
editor.set_block(COBBLESTONE_WALL, x, y + dy, z, None, None);
editor.set_block(COBBLESTONE_WALL, x, dy, 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, y + 7, z, None, None);
}
editor.set_block(GREEN_WOOL, x, 4, z, None, None);
editor.set_block(YELLOW_WOOL, x, 5, z, None, None);
editor.set_block(RED_WOOL, x, 6, z, None, None);
}
}
}
@@ -52,14 +40,13 @@ pub fn generate_highways(
// Handle bus stops
if let ProcessedElement::Node(node) = element {
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(COBBLESTONE_WALL, x, dy, 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);
editor.set_block(WHITE_WOOL, x, 4, z, None, None);
editor.set_block(WHITE_WOOL, x + 1, 4, z, None, None);
}
} else if element
.tags()
@@ -81,14 +68,8 @@ pub fn generate_highways(
"wood" => OAK_PLANKS,
"asphalt" => BLACK_CONCRETE,
"gravel" | "fine_gravel" => GRAVEL,
"grass" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"dirt" => DIRT,
"grass" => GRASS_BLOCK,
"dirt" | "ground" | "earth" => DIRT,
"sand" => SAND,
"concrete" => LIGHT_GRAY_CONCRETE,
_ => STONE, // Default to stone for unknown surfaces
@@ -105,14 +86,7 @@ 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(XZPoint::new(x, z)),
z,
None,
None,
);
editor.set_block(surface_block, x, 0, z, None, None);
}
} else {
let mut previous_node: Option<(i32, i32)> = None;
@@ -140,7 +114,7 @@ pub fn generate_highways(
block_range = 1;
}
"path" => {
block_type = LIGHT_GRAY_CONCRETE;
block_type = DIRT_PATH;
block_range = 1;
}
"motorway" | "primary" => {
@@ -157,6 +131,22 @@ pub fn generate_highways(
block_type = GRAY_CONCRETE;
block_range = 2;
}
"secondary_link" | "tertiary_link" => {
//Exit ramps, sliproads
block_type = BLACK_CONCRETE;
block_range = 1;
}
"escape" => {
// Sand trap for vehicles on mountainous roads
block_type = SAND;
block_range = 1;
}
"steps" => {
//TODO: Add correct stairs respecting height, step_count, etc.
block_type = GRAY_CONCRETE;
block_range = 1;
}
_ => {
if let Some(lanes) = element.tags().get("lanes") {
if lanes == "2" {
@@ -210,7 +200,7 @@ pub fn generate_highways(
editor.set_block(
WHITE_CONCRETE,
set_x,
ground.level(XZPoint::new(set_x, set_z)),
0,
set_z,
Some(&[BLACK_CONCRETE]),
None,
@@ -219,7 +209,7 @@ pub fn generate_highways(
editor.set_block(
BLACK_CONCRETE,
set_x,
ground.level(XZPoint::new(set_x, set_z)),
0,
set_z,
None,
None,
@@ -229,7 +219,7 @@ pub fn generate_highways(
editor.set_block(
WHITE_CONCRETE,
set_x,
ground.level(XZPoint::new(set_x, set_z)),
0,
set_z,
Some(&[BLACK_CONCRETE]),
None,
@@ -238,7 +228,7 @@ pub fn generate_highways(
editor.set_block(
BLACK_CONCRETE,
set_x,
ground.level(XZPoint::new(set_x, set_z)),
0,
set_z,
None,
None,
@@ -248,7 +238,7 @@ pub fn generate_highways(
editor.set_block(
block_type,
set_x,
ground.level(XZPoint::new(set_x, set_z)),
0,
set_z,
None,
Some(&[BLACK_CONCRETE, WHITE_CONCRETE]),
@@ -265,7 +255,7 @@ pub fn generate_highways(
editor.set_block(
WHITE_CONCRETE,
stripe_x,
ground.level(XZPoint::new(stripe_x, stripe_z)),
0,
stripe_z,
Some(&[BLACK_CONCRETE]),
None,
@@ -287,7 +277,7 @@ pub fn generate_highways(
}
/// Generates a siding using stone brick slabs
pub fn generate_siding(editor: &mut WorldEditor, element: &ProcessedWay, ground: &Ground) {
pub fn generate_siding(editor: &mut WorldEditor, element: &ProcessedWay) {
let mut previous_node: Option<XZPoint> = None;
let siding_block: Block = STONE_BRICK_SLAB;
@@ -306,16 +296,8 @@ pub fn generate_siding(editor: &mut WorldEditor, element: &ProcessedWay, ground:
);
for (bx, _, bz) in bresenham_points {
let ground_level = ground.level(XZPoint::new(bx, bz)) + 1;
if !editor.check_for_block(
bx,
ground_level - 1,
bz,
None,
Some(&[BLACK_CONCRETE, WHITE_CONCRETE]),
) {
editor.set_block(siding_block, bx, ground_level, bz, None, None);
if !editor.check_for_block(bx, 0, bz, Some(&[BLACK_CONCRETE, WHITE_CONCRETE])) {
editor.set_block(siding_block, bx, 1, bz, None, None);
}
}
}
@@ -325,7 +307,7 @@ pub fn generate_siding(editor: &mut WorldEditor, element: &ProcessedWay, ground:
}
/// Generates an aeroway
pub fn generate_aeroway(editor: &mut WorldEditor, way: &ProcessedWay, ground: &Ground) {
pub fn generate_aeroway(editor: &mut WorldEditor, way: &ProcessedWay) {
let mut previous_node: Option<(i32, i32)> = None;
let surface_block = LIGHT_GRAY_CONCRETE;
@@ -341,8 +323,7 @@ pub fn generate_aeroway(editor: &mut WorldEditor, way: &ProcessedWay, ground: &G
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);
editor.set_block(surface_block, set_x, 0, set_z, None, None);
}
}
}

View File

@@ -1,56 +1,46 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::cartesian::XZPoint;
use crate::element_processing::tree::create_tree;
use crate::element_processing::tree::Tree;
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::ProcessedWay;
use crate::world_editor::WorldEditor;
use rand::Rng;
pub fn generate_landuse(
editor: &mut WorldEditor,
element: &ProcessedWay,
ground: &Ground,
args: &Args,
) {
pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args: &Args) {
// Determine block type based on landuse tag
let binding: String = "".to_string();
let landuse_tag: &String = element.tags.get("landuse").unwrap_or(&binding);
let block_type = match landuse_tag.as_str() {
"greenfield" | "meadow" | "grass" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"greenfield" | "meadow" | "grass" | "orchard" | "forest" => GRASS_BLOCK,
"farmland" => FARMLAND,
"forest" => {
if args.winter {
SNOW_BLOCK
} else {
"cemetery" => PODZOL,
"construction" => COARSE_DIRT,
"traffic_island" => STONE_BLOCK_SLAB,
"residential" => {
let residential_tag = element.tags.get("residential").unwrap_or(&binding);
if residential_tag == "rural" {
GRASS_BLOCK
} else {
STONE_BRICKS
}
}
"cemetery" => PODZOL,
"beach" => SAND,
"construction" => DIRT,
"traffic_island" => STONE_BLOCK_SLAB,
"residential" => STONE_BRICKS,
"commercial" => SMOOTH_STONE,
"education" => LIGHT_GRAY_CONCRETE,
"industrial" => COBBLESTONE,
"military" => GRAY_CONCRETE,
"railway" => GRAVEL,
_ => {
if args.winter {
SNOW_BLOCK
"landfill" => {
// Gravel if man_made = spoil_heap or heap, coarse dirt else
let manmade_tag = element.tags.get("man_made").unwrap_or(&binding);
if manmade_tag == "spoil_heap" || manmade_tag == "heap" {
GRAVEL
} else {
GRASS_BLOCK
COARSE_DIRT
}
}
"quarry" => STONE,
_ => GRASS_BLOCK,
};
// Get the area of the landuse element
@@ -60,13 +50,12 @@ pub fn generate_landuse(
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
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);
editor.set_block(block_type, x, 1, z, None, None);
} else if landuse_tag == "construction" || landuse_tag == "railway" {
editor.set_block(block_type, x, ground_level, z, None, Some(&[SPONGE]));
editor.set_block(block_type, x, 0, z, None, Some(&[SPONGE]));
} else {
editor.set_block(block_type, x, ground_level, z, None, None);
editor.set_block(block_type, x, 0, z, None, None);
}
// Add specific features for different landuse types
@@ -76,103 +65,33 @@ pub fn generate_landuse(
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 editor.check_for_block(x, 0, z, Some(&[PODZOL])) {
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,
);
editor.set_block(COBBLESTONE, x - 1, 1, z, None, None);
editor.set_block(STONE_BRICK_SLAB, x - 1, 2, z, None, None);
editor.set_block(STONE_BRICK_SLAB, x, 1, z, None, None);
editor.set_block(STONE_BRICK_SLAB, x + 1, 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,
);
editor.set_block(COBBLESTONE, x, 1, z - 1, None, None);
editor.set_block(STONE_BRICK_SLAB, x, 2, z - 1, None, None);
editor.set_block(STONE_BRICK_SLAB, x, 1, z, None, None);
editor.set_block(STONE_BRICK_SLAB, x, 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);
if editor.check_for_block(x, 0, z, Some(&[PODZOL])) {
editor.set_block(RED_FLOWER, x, 1, z, None, None);
}
} else if random_choice < 33 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
Tree::create(editor, (x, 1, z));
}
}
}
"forest" => {
if !editor.check_for_block(x, ground_level, z, None, Some(&[WATER])) {
let random_choice: i32 = rng.gen_range(0..21);
if editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
let random_choice: i32 = rng.gen_range(0..30);
if random_choice == 20 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
Tree::create(editor, (x, 1, z));
} else if random_choice == 2 {
let flower_block: Block = match rng.gen_range(1..=4) {
1 => RED_FLOWER,
@@ -180,67 +99,30 @@ pub fn generate_landuse(
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);
editor.set_block(flower_block, x, 1, z, None, None);
} else if random_choice <= 12 {
editor.set_block(GRASS, x, 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,
Some(&[SPONGE]),
);
} else {
editor.set_block(
OAK_LEAVES,
x,
ground_level + 1,
z,
None,
Some(&[SPONGE]),
);
}
if !editor.check_for_block(x, 0, z, Some(&[WATER])) {
if x % 9 == 0 && z % 9 == 0 {
// Place water in dot pattern
editor.set_block(WATER, x, 0, z, Some(&[FARMLAND]), None);
} else if rng.gen_range(0..76) == 0 {
let special_choice: i32 = rng.gen_range(1..=10);
if special_choice <= 4 {
editor.set_block(HAY_BALE, x, 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);
}
editor.set_block(OAK_LEAVES, x, 1, z, None, Some(&[SPONGE]));
}
} else {
// Set crops only if the block below is farmland
if editor.check_for_block(x, 0, z, Some(&[FARMLAND])) {
let crop_choice = [WHEAT, CARROTS, POTATOES][rng.gen_range(0..3)];
editor.set_block(crop_choice, x, 1, z, None, None);
}
}
}
@@ -248,22 +130,22 @@ pub fn generate_landuse(
"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);
editor.set_block(SCAFFOLDING, x, 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);
editor.set_block(SCAFFOLDING, x, 2, z, None, None);
editor.set_block(SCAFFOLDING, x, 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);
editor.set_block(SCAFFOLDING, x, 2, z, None, None);
editor.set_block(SCAFFOLDING, x, 3, z, None, None);
editor.set_block(SCAFFOLDING, x, 4, z, None, None);
editor.set_block(SCAFFOLDING, x, 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);
editor.set_block(SCAFFOLDING, x, 2, z, None, None);
editor.set_block(SCAFFOLDING, x, 3, z, None, None);
editor.set_block(SCAFFOLDING, x, 4, z, None, None);
editor.set_block(SCAFFOLDING, x, 5, z, None, None);
editor.set_block(SCAFFOLDING, x - 1, 1, z, None, None);
editor.set_block(SCAFFOLDING, x + 1, 1, z - 1, None, None);
}
} else if random_choice < 30 {
let construction_items: [Block; 11] = [
@@ -282,60 +164,64 @@ pub fn generate_landuse(
editor.set_block(
construction_items[rng.gen_range(0..construction_items.len())],
x,
ground_level + 1,
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);
editor.set_block(DIRT, x, 1, z, None, None);
editor.set_block(DIRT, x, 2, z, None, None);
editor.set_block(DIRT, x + 1, 1, z, None, None);
editor.set_block(DIRT, x, 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);
editor.set_block(DIRT, x, 1, z, None, None);
editor.set_block(DIRT, x, 2, z, None, None);
editor.set_block(DIRT, x - 1, 1, z, None, None);
editor.set_block(DIRT, x, 1, z - 1, None, None);
}
} else if random_choice < 150 {
editor.set_block(AIR, x, ground_level, z, None, Some(&[SPONGE]));
editor.set_block(AIR, x, 0, 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,
)
{
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
if rng.gen_bool(0.85) && editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
"meadow" => {
if editor.check_for_block(
x,
ground_level,
z,
Some(&[GRASS_BLOCK, SNOW_BLOCK]),
None,
) {
if editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
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,
);
Tree::create(editor, (x, 1, z));
} else if random_choice < 800 {
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
editor.set_block(GRASS, x, 1, z, None, None);
}
}
}
"orchard" => {
if x % 18 == 0 && z % 10 == 0 {
Tree::create(editor, (x, 1, z));
}
}
"quarry" => {
// Add stone layer under it
editor.set_block(STONE, x, -1, z, Some(&[STONE]), None);
editor.set_block(STONE, x, -2, z, Some(&[STONE]), None);
// Generate ore blocks
if let Some(resource) = element.tags.get("resource") {
let ore_block = match resource.as_str() {
"iron_ore" => IRON_ORE,
"coal" => COAL_ORE,
"copper" => COPPER_ORE,
"gold" => GOLD_ORE,
"clay" | "kaolinite" => CLAY,
_ => STONE,
};
let random_choice: i32 = rng.gen_range(0..100 + editor.get_absolute_y(x, 0, z)); // The deeper it is the more resources are there
if random_choice < 5 {
editor.set_block(ore_block, x, 0, z, Some(&[STONE]), None);
}
}
}

View File

@@ -1,20 +1,13 @@
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::element_processing::tree::Tree;
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;
pub fn generate_leisure(
editor: &mut WorldEditor,
element: &ProcessedWay,
ground: &Ground,
args: &Args,
) {
pub fn generate_leisure(editor: &mut WorldEditor, element: &ProcessedWay, args: &Args) {
if let Some(leisure_type) = element.tags.get("leisure") {
let mut previous_node: Option<(i32, i32)> = None;
let mut corner_addup: (i32, i32, i32) = (0, 0, 0);
@@ -22,40 +15,30 @@ pub fn generate_leisure(
// Determine block type based on leisure type
let block_type: Block = match leisure_type.as_str() {
"park" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
"park" | "nature_reserve" | "garden" | "disc_golf_course" | "golf_course" => {
GRASS_BLOCK
}
"playground" | "recreation_ground" | "pitch" => {
"playground" | "recreation_ground" | "pitch" | "beach_resort" | "dog_park" => {
if let Some(surface) = element.tags.get("surface") {
match surface.as_str() {
"clay" => TERRACOTTA,
"sand" => SAND,
"tartan" => RED_TERRACOTTA,
"grass" => GRASS_BLOCK,
"dirt" => DIRT,
"pebblestone" | "cobblestone" | "unhewn_cobblestone" => COBBLESTONE,
_ => GREEN_STAINED_HARDENED_CLAY,
}
} else {
GREEN_STAINED_HARDENED_CLAY
}
}
"garden" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"swimming_pool" => WATER,
_ => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"swimming_pool" | "swimming_area" => WATER, //Swimming area: Area in a larger body of water for swimming
"bathing_place" => SMOOTH_SANDSTONE, // Could be sand or concrete
"outdoor_seating" => SMOOTH_STONE, //Usually stone or stone bricks
"water_park" | "slipway" => LIGHT_GRAY_CONCRETE, // Water park area, not the pool. Usually is concrete
"ice_rink" => PACKED_ICE, // TODO: Ice for Ice Rink, needs building defined
_ => GRASS_BLOCK,
};
// Process leisure area nodes
@@ -68,7 +51,7 @@ pub fn generate_leisure(
editor.set_block(
block_type,
bx,
ground.level(XZPoint::new(bx, bz)),
0,
bz,
Some(&[
GRASS_BLOCK,
@@ -101,47 +84,33 @@ 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);
editor.set_block(block_type, x, 0, z, Some(&[GRASS_BLOCK]), None);
// Add decorative elements for parks and gardens
if matches!(leisure_type.as_str(), "park" | "garden")
&& editor.check_for_block(x, ground_level, z, Some(&[GRASS_BLOCK]), None)
if matches!(leisure_type.as_str(), "park" | "garden" | "nature_reserve")
&& editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK]))
{
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
let random_choice: i32 = rng.gen_range(0..1000);
match random_choice {
0 => {
// Benches
editor.set_block(OAK_LOG, 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);
}
1..=30 => {
0..40 => {
// Flowers
let flower_choice = match rng.gen_range(0..4) {
0 => RED_FLOWER,
1 => YELLOW_FLOWER,
2 => BLUE_FLOWER,
let flower_choice = match random_choice {
0..10 => RED_FLOWER,
10..20 => YELLOW_FLOWER,
20..30 => BLUE_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_choice, x, ground_level + 1, z, None, None);
editor.set_block(flower_choice, x, 1, z, None, None);
}
31..=70 => {
40..80 => {
// Grass
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
editor.set_block(GRASS, x, 1, z, None, None);
}
71..=80 => {
80..90 => {
// Tree
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
Tree::create(editor, (x, 1, z));
}
_ => {}
}
@@ -153,36 +122,36 @@ pub fn generate_leisure(
let random_choice: i32 = rng.gen_range(0..5000);
match random_choice {
0..=10 => {
0..10 => {
// Swing set
for y in 1..=4 {
editor.set_block(OAK_FENCE, x - 1, ground_level + y, z, None, None);
editor.set_block(OAK_FENCE, x + 1, ground_level + y, z, None, None);
editor.set_block(OAK_FENCE, x - 1, y, z, None, None);
editor.set_block(OAK_FENCE, x + 1, y, z, None, None);
}
editor.set_block(OAK_FENCE, x, ground_level + 4, z, None, None);
editor.set_block(STONE_BLOCK_SLAB, x, ground_level + 2, z, None, None);
editor.set_block(OAK_FENCE, x, 4, z, None, None);
editor.set_block(STONE_BLOCK_SLAB, x, 2, z, None, None);
}
11..=20 => {
10..20 => {
// Slide
editor.set_block(OAK_SLAB, x, ground_level + 1, z, None, None);
editor.set_block(OAK_SLAB, x + 1, ground_level + 2, z, None, None);
editor.set_block(OAK_SLAB, x + 2, ground_level + 3, z, None, None);
editor.set_block(OAK_SLAB, x, 1, z, None, None);
editor.set_block(OAK_SLAB, x + 1, 2, z, None, None);
editor.set_block(OAK_SLAB, x + 2, 3, z, None, None);
editor.set_block(OAK_PLANKS, x + 2, ground_level + 2, z, None, None);
editor.set_block(OAK_PLANKS, x + 2, ground_level + 1, z, None, None);
editor.set_block(OAK_PLANKS, x + 2, 2, z, None, None);
editor.set_block(OAK_PLANKS, x + 2, 1, z, None, None);
editor.set_block(LADDER, x + 2, ground_level + 2, z - 1, None, None);
editor.set_block(LADDER, x + 2, ground_level + 1, z - 1, None, None);
editor.set_block(LADDER, x + 2, 2, z - 1, None, None);
editor.set_block(LADDER, x + 2, 1, z - 1, None, None);
}
21..=30 => {
20..30 => {
// Sandpit
editor.fill_blocks(
SAND,
x - 3,
ground_level,
0,
z - 3,
x + 3,
ground_level,
0,
z + 3,
Some(&[GREEN_STAINED_HARDENED_CLAY]),
None,
@@ -199,14 +168,13 @@ 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);
generate_leisure(editor, &member.way, args);
}
}
@@ -226,6 +194,6 @@ pub fn generate_leisure_from_relation(
};
// Generate leisure area from combined way
generate_leisure(editor, &combined_way, ground, args);
generate_leisure(editor, &combined_way, args);
}
}

View File

@@ -1,66 +1,44 @@
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::element_processing::tree::Tree;
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::ProcessedElement;
use crate::world_editor::WorldEditor;
use rand::Rng;
pub fn generate_natural(
editor: &mut WorldEditor,
element: &ProcessedElement,
ground: &Ground,
args: &Args,
) {
pub fn generate_natural(editor: &mut WorldEditor, element: &ProcessedElement, args: &Args) {
if let Some(natural_type) = element.tags().get("natural") {
if natural_type == "tree" {
if let ProcessedElement::Node(node) = element {
let x: i32 = node.x;
let z: i32 = node.z;
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
create_tree(
editor,
x,
ground.level(node.xz()) + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
Tree::create(editor, (x, 1, z));
}
} else {
let mut previous_node: Option<(i32, i32)> = None;
let mut corner_addup: (i32, i32, i32) = (0, 0, 0);
let mut current_natural: Vec<(i32, i32)> = vec![];
let binding: String = "".to_string();
// Determine block type based on natural tag
let block_type: Block = match natural_type.as_str() {
"scrub" | "grassland" | "wood" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"beach" | "sand" => SAND,
"tree_row" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"wetland" | "water" => WATER,
_ => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
"scrub" | "grassland" | "wood" | "heath" | "tree_row" => GRASS_BLOCK,
"sand" | "dune" => SAND,
"beach" | "shoal" => {
let surface = element.tags().get("natural").unwrap_or(&binding);
match surface.as_str() {
"gravel" => GRAVEL,
_ => SAND,
}
}
"water" | "reef" => WATER,
"bare_rock" => STONE,
"blockfield" => COBBLESTONE,
"glacier" => PACKED_ICE,
"mud" | "wetland" => MUD,
_ => GRASS_BLOCK,
};
let ProcessedElement::Way(way) = element else {
@@ -77,14 +55,7 @@ pub fn generate_natural(
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.0, 0, prev.1, x, 0, z);
for (bx, _, bz) in bresenham_points {
editor.set_block(
block_type,
bx,
ground.level(XZPoint::new(bx, bz)),
bz,
None,
None,
);
editor.set_block(block_type, bx, 0, bz, None, None);
}
current_natural.push((x, z));
@@ -107,30 +78,181 @@ pub fn generate_natural(
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
for (x, z) in filled_area {
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, y, z, None, Some(&[WATER])) {
continue;
editor.set_block(block_type, x, 0, z, None, None);
// Generate custom layer instead of dirt, must be stone on the lowest level
match natural_type.as_str() {
"beach" | "sand" | "dune" | "shoal" => {
editor.set_block(SAND, x, -1, z, None, None);
editor.set_block(STONE, x, -2, z, None, None);
}
let random_choice: i32 = rng.gen_range(0..26);
if random_choice == 25 {
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,
2 => BLUE_FLOWER,
3 => YELLOW_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_block, x, y + 1, z, None, None);
} else if random_choice <= 1 {
editor.set_block(GRASS, x, y + 1, z, None, None);
"glacier" => {
editor.set_block(PACKED_ICE, x, -1, z, None, None);
editor.set_block(STONE, x, -2, z, None, None);
}
"bare_rock" => {
editor.set_block(STONE, x, -1, z, None, None);
editor.set_block(STONE, x, -2, z, None, None);
}
_ => {}
}
// Generate surface elements
if editor.check_for_block(x, 0, z, Some(&[WATER])) {
continue;
}
match natural_type.as_str() {
"grassland" => {
if !editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
continue;
}
if rng.gen_bool(0.6) {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
"heath" => {
if !editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
continue;
}
let random_choice = rng.gen_range(0..500);
if random_choice < 30 {
if random_choice < 3 {
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
} else {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
}
"scrub" => {
if !editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
continue;
}
let random_choice = rng.gen_range(0..500);
if random_choice == 0 {
Tree::create(editor, (x, 1, z));
} else if random_choice == 1 {
let flower_block = match rng.gen_range(1..=4) {
1 => RED_FLOWER,
2 => BLUE_FLOWER,
3 => YELLOW_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_block, x, 1, z, None, None);
} else if random_choice < 40 {
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
if random_choice < 15 {
editor.set_block(OAK_LEAVES, x, 2, z, None, None);
}
} else if random_choice < 300 {
if random_choice < 250 {
editor.set_block(GRASS, x, 1, z, None, None);
} else {
editor.set_block(TALL_GRASS_BOTTOM, x, 1, z, None, None);
editor.set_block(TALL_GRASS_TOP, x, 2, z, None, None);
}
}
}
"tree_row" | "wood" => {
if !editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
continue;
}
let random_choice: i32 = rng.gen_range(0..30);
if random_choice == 0 {
Tree::create(editor, (x, 1, z));
} else if random_choice == 1 {
let flower_block = match rng.gen_range(1..=4) {
1 => RED_FLOWER,
2 => BLUE_FLOWER,
3 => YELLOW_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_block, x, 1, z, None, None);
} else if random_choice <= 12 {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
"sand" => {
if editor.check_for_block(x, 0, z, Some(&[SAND]))
&& rng.gen_range(0..100) == 1
{
editor.set_block(DEAD_BUSH, x, 1, z, None, None);
}
}
"shoal" => {
if rng.gen_bool(0.05) {
editor.set_block(WATER, x, 0, z, Some(&[SAND, GRAVEL]), None);
}
}
"wetland" => {
if let Some(wetland_type) = element.tags().get("wetland") {
// Wetland without water blocks
if matches!(wetland_type.as_str(), "wet_meadow" | "fen") {
if rng.gen_bool(0.3) {
editor.set_block(GRASS_BLOCK, x, 0, z, Some(&[MUD]), None);
}
editor.set_block(GRASS, x, 1, z, None, None);
continue;
}
// All the other types of wetland
if rng.gen_bool(0.3) {
editor.set_block(
WATER,
x,
0,
z,
Some(&[MUD, GRASS_BLOCK]),
None,
);
continue;
}
if !editor.check_for_block(x, 0, z, Some(&[MUD, MOSS_BLOCK])) {
continue;
}
match wetland_type.as_str() {
"reedbed" => {
editor.set_block(TALL_GRASS_BOTTOM, x, 1, z, None, None);
editor.set_block(TALL_GRASS_TOP, x, 2, z, None, None);
}
"swamp" | "mangrove" => {
// TODO implement mangrove
let random_choice: i32 = rng.gen_range(0..40);
if random_choice == 0 {
Tree::create(editor, (x, 1, z));
} else if random_choice < 35 {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
"bog" => {
if rng.gen_bool(0.2) {
editor.set_block(
MOSS_BLOCK,
x,
0,
z,
Some(&[MUD]),
None,
);
}
if rng.gen_bool(0.15) {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
"tidalflat" => {
continue; // No vegetation here
}
_ => {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
} else {
// Generic natural=wetland without wetland=... tag
if rng.gen_bool(0.3) {
editor.set_block(WATER, x, 0, z, Some(&[MUD]), None);
continue;
}
editor.set_block(GRASS, x, 1, z, None, None);
}
}
_ => {}
}
}
}

View File

@@ -1,16 +1,30 @@
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: &Ground) {
pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay) {
if let Some(railway_type) = element.tags.get("railway") {
// Check for underground railways (negative level or layer)
let is_underground = element
.tags
.get("level")
.map_or(false, |level| level.parse::<i32>().map_or(false, |l| l < 0))
|| element
.tags
.get("layer")
.map_or(false, |layer| layer.parse::<i32>().map_or(false, |l| l < 0));
// Also check for tunnel=yes tag
let is_tunnel = element
.tags
.get("tunnel")
.map_or(false, |tunnel| tunnel == "yes");
// Skip certain railway types
if [
"proposed",
"abandoned",
"subway",
"construction",
"razed",
"turntable",
@@ -20,18 +34,13 @@ pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay, groun
return;
}
if let Some(subway) = element.tags.get("subway") {
if subway == "yes" {
return;
}
}
if let Some(tunnel) = element.tags.get("tunnel") {
if tunnel == "yes" {
return;
}
// Process as subway if it's a subway, underground by level/layer tag, or a tunnel
if element.tags.get("subway").map_or(false, |v| v == "yes") || is_underground || is_tunnel {
generate_subway(editor, element);
return;
}
// Regular surface railways
for i in 1..element.nodes.len() {
let prev_node = element.nodes[i - 1].xz();
let cur_node = element.nodes[i].xz();
@@ -41,9 +50,8 @@ pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay, groun
for j in 0..smoothed_points.len() {
let (bx, _, bz) = smoothed_points[j];
let ground_level = ground.level(XZPoint::new(bx, bz));
editor.set_block(IRON_BLOCK, bx, ground_level, bz, None, None);
editor.set_block(GRAVEL, bx, 0, bz, None, None);
let prev = if j > 0 {
Some(smoothed_points[j - 1])
@@ -62,10 +70,119 @@ pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay, groun
next.map(|(x, _, z)| (x, z)),
);
editor.set_block(rail_block, bx, ground_level + 1, bz, None, None);
editor.set_block(rail_block, bx, 1, bz, None, None);
if bx % 4 == 0 {
editor.set_block(OAK_LOG, bx, ground_level, bz, None, None);
editor.set_block(OAK_LOG, bx, 0, bz, None, None);
}
}
}
}
}
fn generate_subway(editor: &mut WorldEditor, element: &ProcessedWay) {
for i in 1..element.nodes.len() {
let prev_node = element.nodes[i - 1].xz();
let cur_node = element.nodes[i].xz();
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);
for j in 0..smoothed_points.len() {
let (bx, _, bz) = smoothed_points[j];
// Create a 4-block wide floor
for dx in -2..=1 {
for dz in -2..=1 {
editor.set_block(SMOOTH_STONE, bx + dx, -9, bz + dz, None, None);
}
}
// Create a 4-block wide ceiling 3 blocks above the floor
for dx in -2..=1 {
for dz in -2..=1 {
// Add occasional glowstone for lighting
if dx == 0 && dz == 0 && j % 4 == 0 {
editor.set_block(GLOWSTONE, bx, -4, bz, None, None);
} else {
editor.set_block(
SMOOTH_STONE,
bx + dx,
-4,
bz + dz,
None,
Some(&[GLOWSTONE]),
);
}
}
}
// Get previous and next points for direction
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)),
);
// Place the rail on top of the floor
editor.set_block(rail_block, bx, -8, bz, None, None);
// Helper function to place wall only if block below is not SMOOTH_STONE
let mut place_wall = |x: i32, y: i32, z: i32| {
if !editor.check_for_block(x, y - 1, z, Some(&[SMOOTH_STONE])) {
editor.set_block(POLISHED_ANDESITE, x, y, z, None, None);
editor.set_block(POLISHED_ANDESITE, x, y + 1, z, None, None);
editor.set_block(POLISHED_ANDESITE, x, y + 2, z, None, None);
editor.set_block(POLISHED_ANDESITE, x, y + 3, z, None, None);
editor.set_block(POLISHED_ANDESITE, x, y + 4, z, None, None);
}
};
// Place dirt blocks two blocks away from the rail
// Determine orientation based on rail block
match rail_block {
RAIL_NORTH_SOUTH => {
// For north-south rails, place dirt two blocks east and west
place_wall(bx + 3, -8, bz);
place_wall(bx - 3, -8, bz);
}
RAIL_EAST_WEST => {
// For east-west rails, place dirt two blocks north and south
place_wall(bx, -8, bz + 3);
place_wall(bx, -8, bz - 3);
}
RAIL_NORTH_EAST => {
// For curves, place dirt two blocks away at appropriate positions
place_wall(bx - 3, -8, bz);
place_wall(bx, -8, bz + 3);
}
RAIL_NORTH_WEST => {
place_wall(bx + 3, -8, bz);
place_wall(bx, -8, bz + 3);
}
RAIL_SOUTH_EAST => {
place_wall(bx - 3, -8, bz);
place_wall(bx, -8, bz - 3);
}
RAIL_SOUTH_WEST => {
place_wall(bx + 3, -8, bz);
place_wall(bx, -8, bz - 3);
}
_ => {
// Default for any other rail blocks
place_wall(bx + 3, -8, bz);
place_wall(bx - 3, -8, bz);
}
}
}

View File

@@ -1,10 +1,8 @@
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: &Ground) {
pub fn generate_tourisms(editor: &mut WorldEditor, element: &ProcessedNode) {
// 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 {
@@ -22,15 +20,14 @@ 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()) {
// 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);
if let Some(info_type) = element.tags.get("information").map(|x: &String| x.as_str()) {
if info_type != "office" && info_type != "visitor_centre" {
// Draw an information board
// TODO draw a sign with text if provided
editor.set_block(COBBLESTONE_WALL, x, 1, z, None, None);
editor.set_block(OAK_PLANKS, x, 2, z, None, None);
}
}
}
}

View File

@@ -1,166 +1,196 @@
use crate::block_definitions::*;
use crate::world_editor::WorldEditor;
use rand::Rng;
/// Helper function to set blocks in a circular pattern around a central point.
fn round1(editor: &mut WorldEditor, material: Block, x: i32, y: i32, z: i32) {
editor.set_block(material, x - 2, y, z, None, None);
editor.set_block(material, x + 2, y, z, None, None);
editor.set_block(material, x, y, z - 2, None, None);
editor.set_block(material, x, y, z + 2, None, None);
editor.set_block(material, x - 1, y, z - 1, None, None);
editor.set_block(material, x + 1, y, z + 1, None, None);
editor.set_block(material, x + 1, y, z - 1, None, None);
editor.set_block(material, x - 1, y, z + 1, None, None);
}
type Coord = (i32, i32, i32);
/// Helper function to set blocks in a wider circular pattern.
fn round2(editor: &mut WorldEditor, material: Block, x: i32, y: i32, z: i32) {
editor.set_block(material, x + 3, y, z, None, None);
editor.set_block(material, x + 2, y, z - 1, None, None);
editor.set_block(material, x + 2, y, z + 1, None, None);
editor.set_block(material, x + 1, y, z - 2, None, None);
editor.set_block(material, x + 1, y, z + 2, None, None);
editor.set_block(material, x - 3, y, z, None, None);
editor.set_block(material, x - 2, y, z - 1, None, None);
editor.set_block(material, x - 2, y, z + 1, None, None);
editor.set_block(material, x - 1, y, z + 2, None, None);
editor.set_block(material, x - 1, y, z - 2, None, None);
editor.set_block(material, x, y, z - 3, None, None);
editor.set_block(material, x, y, z + 3, None, None);
}
// TODO all this data would probably be better suited in a TOML file or something.
/// Helper function to set blocks in a more scattered circular pattern.
fn round3(editor: &mut WorldEditor, material: Block, x: i32, y: i32, z: i32) {
editor.set_block(material, x + 3, y, z - 1, None, None);
editor.set_block(material, x + 3, y, z + 1, None, None);
editor.set_block(material, x + 2, y, z - 2, None, None);
editor.set_block(material, x + 2, y, z + 2, None, None);
editor.set_block(material, x + 1, y, z - 3, None, None);
editor.set_block(material, x + 1, y, z + 3, None, None);
editor.set_block(material, x - 3, y, z - 1, None, None);
editor.set_block(material, x - 3, y, z + 1, None, None);
editor.set_block(material, x - 2, y, z - 2, None, None);
editor.set_block(material, x - 2, y, z + 2, None, None);
editor.set_block(material, x - 1, y, z + 3, None, None);
editor.set_block(material, x - 1, y, z - 3, None, None);
}
/// A circular pattern around a central point.
#[rustfmt::skip]
const ROUND1_PATTERN: [Coord; 8] = [
(-2, 0, 0),
(2, 0, 0),
(0, 0, -2),
(0, 0, 2),
(-1, 0, -1),
(1, 0, 1),
(1, 0, -1),
(-1, 0, 1),
];
/// Function to create different types of trees.
pub fn create_tree(editor: &mut WorldEditor, x: i32, y: i32, z: i32, typetree: u8, snow: bool) {
let mut blacklist: Vec<Block> = Vec::new();
blacklist.extend(building_corner_variations());
blacklist.extend(building_wall_variations());
blacklist.extend(building_floor_variations());
blacklist.push(WATER);
/// A wider circular pattern.
const ROUND2_PATTERN: [Coord; 12] = [
(3, 0, 0),
(2, 0, -1),
(2, 0, 1),
(1, 0, -2),
(1, 0, 2),
(-3, 0, 0),
(-2, 0, -1),
(-2, 0, 1),
(-1, 0, 2),
(-1, 0, -2),
(0, 0, -3),
(0, 0, 3),
];
if editor.check_for_block(x, y - 1, z, None, Some(&blacklist)) {
return;
}
/// A more scattered circular pattern.
const ROUND3_PATTERN: [Coord; 12] = [
(3, 0, -1),
(3, 0, 1),
(2, 0, -2),
(2, 0, 2),
(1, 0, -3),
(1, 0, 3),
(-3, 0, -1),
(-3, 0, 1),
(-2, 0, -2),
(-2, 0, 2),
(-1, 0, 3),
(-1, 0, -3),
];
match typetree {
1 => {
// Oak tree
editor.fill_blocks(OAK_LOG, x, y, z, x, y + 8, z, None, None);
editor.fill_blocks(OAK_LEAVES, x - 1, y + 3, z, x - 1, y + 9, z, None, None);
editor.fill_blocks(OAK_LEAVES, x + 1, y + 3, z, x + 1, y + 9, z, None, None);
editor.fill_blocks(OAK_LEAVES, x, y + 3, z - 1, x, y + 9, z - 1, None, None);
editor.fill_blocks(OAK_LEAVES, x, y + 3, z + 1, x, y + 9, z + 1, None, None);
editor.fill_blocks(OAK_LEAVES, x, y + 9, z, x, y + 10, z, None, None);
round1(editor, OAK_LEAVES, x, y + 8, z);
round1(editor, OAK_LEAVES, x, y + 7, z);
round1(editor, OAK_LEAVES, x, y + 6, z);
round1(editor, OAK_LEAVES, x, y + 5, z);
round1(editor, OAK_LEAVES, x, y + 4, z);
round1(editor, OAK_LEAVES, x, y + 3, z);
round2(editor, OAK_LEAVES, x, y + 7, z);
round2(editor, OAK_LEAVES, x, y + 6, z);
round2(editor, OAK_LEAVES, x, y + 5, z);
round2(editor, OAK_LEAVES, x, y + 4, z);
round3(editor, OAK_LEAVES, x, y + 6, z);
round3(editor, OAK_LEAVES, x, y + 5, z);
/// Used for iterating over each of the round patterns
const ROUND_PATTERNS: [&[Coord]; 3] = [&ROUND1_PATTERN, &ROUND2_PATTERN, &ROUND3_PATTERN];
if snow {
editor.set_block(SNOW_LAYER, x, y + 11, z, None, None);
editor.set_block(SNOW_LAYER, x + 1, y + 10, z, None, None);
editor.set_block(SNOW_LAYER, x - 1, y + 10, z, None, None);
editor.set_block(SNOW_LAYER, x, y + 10, z - 1, None, None);
editor.set_block(SNOW_LAYER, x, y + 10, z + 1, None, None);
round1(editor, SNOW_LAYER, x, y + 9, z);
round1(editor, SNOW_LAYER, x, y + 8, z);
round1(editor, SNOW_LAYER, x, y + 7, z);
round1(editor, SNOW_LAYER, x, y + 6, z);
round2(editor, SNOW_LAYER, x, y + 8, z);
round2(editor, SNOW_LAYER, x, y + 7, z);
round2(editor, SNOW_LAYER, x, y + 6, z);
round2(editor, SNOW_LAYER, x, y + 5, z);
round3(editor, SNOW_LAYER, x, y + 7, z);
round3(editor, SNOW_LAYER, x, y + 6, z);
}
}
2 => {
// Spruce tree
editor.fill_blocks(SPRUCE_LOG, x, y, z, x, y + 9, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x - 1, y + 3, z, x - 1, y + 10, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x + 1, y + 3, z, x + 1, y + 10, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x, y + 3, z - 1, x, y + 10, z - 1, None, None);
editor.fill_blocks(BIRCH_LEAVES, x, y + 3, z + 1, x, y + 10, z + 1, None, None);
editor.set_block(BIRCH_LEAVES, x, y + 10, z, None, None);
round1(editor, BIRCH_LEAVES, x, y + 9, z);
round1(editor, BIRCH_LEAVES, x, y + 7, z);
round1(editor, BIRCH_LEAVES, x, y + 6, z);
round1(editor, BIRCH_LEAVES, x, y + 4, z);
round1(editor, BIRCH_LEAVES, x, y + 3, z);
round2(editor, BIRCH_LEAVES, x, y + 6, z);
round2(editor, BIRCH_LEAVES, x, y + 3, z);
//////////////////////////////////////////////////
if snow {
editor.set_block(SNOW_LAYER, x, y + 11, z, None, None);
editor.set_block(SNOW_LAYER, x + 1, y + 11, z, None, None);
editor.set_block(SNOW_LAYER, x - 1, y + 11, z, None, None);
editor.set_block(SNOW_LAYER, x, y + 11, z - 1, None, None);
editor.set_block(SNOW_LAYER, x, y + 11, z + 1, None, None);
round1(editor, SNOW_LAYER, x, y + 10, z);
round1(editor, SNOW_LAYER, x, y + 8, z);
round1(editor, SNOW_LAYER, x, y + 7, z);
round1(editor, SNOW_LAYER, x, y + 5, z);
round1(editor, SNOW_LAYER, x, y + 4, z);
round2(editor, SNOW_LAYER, x, y + 7, z);
round2(editor, SNOW_LAYER, x, y + 4, z);
}
}
3 => {
// Birch tree
editor.fill_blocks(BIRCH_LOG, x, y, z, x, y + 6, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x - 1, y + 2, z, x - 1, y + 7, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x + 1, y + 2, z, x + 1, y + 7, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x, y + 2, z - 1, x, y + 7, z - 1, None, None);
editor.fill_blocks(BIRCH_LEAVES, x, y + 2, z + 1, x, y + 7, z + 1, None, None);
editor.fill_blocks(BIRCH_LEAVES, x, y + 7, z, x, y + 8, z, None, None);
round1(editor, BIRCH_LEAVES, x, y + 6, z);
round1(editor, BIRCH_LEAVES, x, y + 5, z);
round1(editor, BIRCH_LEAVES, x, y + 4, z);
round1(editor, BIRCH_LEAVES, x, y + 3, z);
round1(editor, BIRCH_LEAVES, x, y + 2, z);
round2(editor, BIRCH_LEAVES, x, y + 2, z);
round2(editor, BIRCH_LEAVES, x, y + 3, z);
round2(editor, BIRCH_LEAVES, x, y + 4, z);
const OAK_LEAVES_FILL: [(Coord, Coord); 5] = [
((-1, 3, 0), (-1, 9, 0)),
((1, 3, 0), (1, 9, 0)),
((0, 3, -1), (0, 9, -1)),
((0, 3, 1), (0, 9, 1)),
((0, 9, 0), (0, 10, 0)),
];
if snow {
editor.set_block(SNOW_LAYER, x, y + 9, z, None, None);
editor.set_block(SNOW_LAYER, x + 1, y + 8, z, None, None);
editor.set_block(SNOW_LAYER, x - 1, y + 8, z, None, None);
editor.set_block(SNOW_LAYER, x, y + 8, z - 1, None, None);
editor.set_block(SNOW_LAYER, x, y + 8, z + 1, None, None);
round1(editor, SNOW_LAYER, x, y + 7, z);
round1(editor, SNOW_LAYER, x, y + 6, z);
round1(editor, SNOW_LAYER, x, y + 5, z);
round1(editor, SNOW_LAYER, x, y + 4, z);
round1(editor, SNOW_LAYER, x, y + 3, z);
round2(editor, SNOW_LAYER, x, y + 3, z);
round2(editor, SNOW_LAYER, x, y + 4, z);
round2(editor, SNOW_LAYER, x, y + 5, z);
}
}
_ => {} // Do nothing if typetree is not recognized
const SPRUCE_LEAVES_FILL: [(Coord, Coord); 5] = [
((-1, 3, 0), (-1, 10, 0)),
((0, 3, -1), (0, 10, -1)),
((1, 3, 0), (1, 10, 0)),
((0, 3, -1), (0, 10, -1)),
((0, 3, 1), (0, 10, 1)),
];
const BIRCH_LEAVES_FILL: [(Coord, Coord); 5] = [
((-1, 2, 0), (-1, 7, 0)),
((1, 2, 0), (1, 7, 0)),
((0, 2, -1), (0, 7, -1)),
((0, 2, 1), (0, 7, 1)),
((0, 7, 0), (0, 8, 0)),
];
//////////////////////////////////////////////////
/// Helper function to set blocks in various patterns.
fn round(editor: &mut WorldEditor, material: Block, (x, y, z): Coord, block_pattern: &[Coord]) {
for (i, j, k) in block_pattern {
editor.set_block(material, x + i, y + j, z + k, None, None);
}
}
pub enum TreeType {
Oak,
Spruce,
Birch,
}
// TODO what should be moved in, and what should be referenced?
pub struct Tree<'a> {
// kind: TreeType, // NOTE: Not actually necessary to store!
log_block: Block,
log_height: i32,
leaves_block: Block,
leaves_fill: &'a [(Coord, Coord)],
round_ranges: [Vec<i32>; 3],
}
impl Tree<'_> {
pub fn create(editor: &mut WorldEditor, (x, y, z): Coord) {
let mut blacklist: Vec<Block> = Vec::new();
blacklist.extend(BUILDING_CORNER_VARIATIONS);
blacklist.extend(building_wall_variations());
blacklist.extend(building_floor_variations());
blacklist.push(WATER);
let mut rng = rand::thread_rng();
let tree = Self::get_tree(match rng.gen_range(1..=3) {
1 => TreeType::Oak,
2 => TreeType::Spruce,
3 => TreeType::Birch,
_ => unreachable!(),
});
// Build the logs
editor.fill_blocks(
tree.log_block,
x,
y,
z,
x,
y + tree.log_height,
z,
None,
Some(&blacklist),
);
// Fill in the leaves
for ((i1, j1, k1), (i2, j2, k2)) in tree.leaves_fill {
editor.fill_blocks(
tree.leaves_block,
x + i1,
y + j1,
z + k1,
x + i2,
y + j2,
z + k2,
None,
None,
);
}
// Do the three rounds
for (round_range, round_pattern) in tree.round_ranges.iter().zip(ROUND_PATTERNS) {
for offset in round_range {
round(editor, tree.leaves_block, (x, y + offset, z), round_pattern);
}
}
}
fn get_tree(kind: TreeType) -> Self {
match kind {
TreeType::Oak => Self {
// kind,
log_block: OAK_LOG,
log_height: 8,
leaves_block: OAK_LEAVES,
leaves_fill: &OAK_LEAVES_FILL,
round_ranges: [
(3..=8).rev().collect(),
(4..=7).rev().collect(),
(5..=6).rev().collect(),
],
},
TreeType::Spruce => Self {
// kind,
log_block: SPRUCE_LOG,
log_height: 9,
leaves_block: BIRCH_LEAVES, // TODO Is this correct?
leaves_fill: &SPRUCE_LEAVES_FILL,
// TODO can I omit the third empty vec? May cause issues with iter zip
round_ranges: [vec![9, 7, 6, 4, 3], vec![6, 3], vec![]],
},
TreeType::Birch => Self {
// kind,
log_block: BIRCH_LOG,
log_height: 6,
leaves_block: BIRCH_LEAVES,
leaves_fill: &BIRCH_LEAVES_FILL,
round_ranges: [(2..=6).rev().collect(), (2..=4).collect(), vec![]],
},
} // match
} // fn get_tree
} // impl Tree

View File

@@ -4,16 +4,11 @@ use std::time::Instant;
use crate::{
block_definitions::WATER,
cartesian::XZPoint,
ground::Ground,
osm_parser::{ProcessedMemberRole, ProcessedNode, ProcessedRelation},
world_editor::WorldEditor,
};
pub fn generate_water_areas(
editor: &mut WorldEditor,
element: &ProcessedRelation,
ground: &Ground,
) {
pub fn generate_water_areas(editor: &mut WorldEditor, element: &ProcessedRelation) {
let start_time = Instant::now();
if !element.tags.contains_key("water") {
@@ -57,7 +52,7 @@ pub fn generate_water_areas(
.map(|x| x.iter().map(|y| y.xz()).collect::<Vec<_>>())
.collect();
inverse_floodfill(max_x, max_z, outers, inners, editor, ground, start_time);
inverse_floodfill(max_x, max_z, outers, inners, editor, start_time);
}
// Merges ways that share nodes into full loops
@@ -153,7 +148,6 @@ fn inverse_floodfill(
outers: Vec<Vec<XZPoint>>,
inners: Vec<Vec<XZPoint>>,
editor: &mut WorldEditor,
ground: &Ground,
start_time: Instant,
) {
let min_x: i32 = 0;
@@ -193,7 +187,6 @@ fn inverse_floodfill(
&outers,
&inners,
editor,
ground,
start_time,
);
}
@@ -204,7 +197,6 @@ fn inverse_floodfill_recursive(
outers: &[Polygon],
inners: &[Polygon],
editor: &mut WorldEditor,
ground: &Ground,
start_time: Instant,
) {
// Check if we've exceeded 25 seconds
@@ -219,8 +211,7 @@ 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);
inverse_floodfill_iterative(min, max, 0, outers, inners, editor);
return;
}
@@ -242,8 +233,7 @@ fn inverse_floodfill_recursive(
if outers.iter().any(|outer: &Polygon| outer.contains(&rect))
&& !inners.iter().any(|inner: &Polygon| inner.intersects(&rect))
{
let ground_level = ground.level(XZPoint::new(min_x, min_z));
rect_fill(min_x, max_x, min_z, max_z, ground_level, editor);
rect_fill(min_x, max_x, min_z, max_z, 0, editor);
continue;
}
@@ -265,7 +255,6 @@ fn inverse_floodfill_recursive(
&outers_intersects,
&inners_intersects,
editor,
ground,
start_time,
);
}

View File

@@ -1,11 +1,10 @@
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: &Ground) {
pub fn generate_waterways(editor: &mut WorldEditor, element: &ProcessedWay) {
if let Some(_waterway_type) = element.tags.get("waterway") {
let mut previous_node: Option<XZPoint> = None;
let mut waterway_width: i32 = 4; // Default waterway width
@@ -35,17 +34,15 @@ pub fn generate_waterways(editor: &mut WorldEditor, element: &ProcessedWay, grou
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) {
// Set water block at the ground level
editor.set_block(WATER, x, ground_level, z, None, None);
editor.set_block(WATER, x, 0, z, None, None);
// Clear vegetation above the water
editor.set_block(
AIR,
x,
ground_level + 1,
1,
z,
Some(&[GRASS, WHEAT, CARROTS, POTATOES]),
None,

60
src/geo_coord.rs Normal file
View File

@@ -0,0 +1,60 @@
/// Bounds-checked longitude and latitude.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct GeoCoord {
lat: f64,
lng: f64,
}
impl GeoCoord {
pub fn new(lat: f64, lng: f64) -> Result<Self, String> {
let lat_in_range = (-90.0..=90.0).contains(&lat) && (-90.0..=90.0).contains(&lat);
let lng_in_range = (-180.0..=180.0).contains(&lng) && (-180.0..=180.0).contains(&lng);
if !lat_in_range {
return Err(format!("Latitude {} not in range -90.0..=90.0", lat));
}
if !lng_in_range {
return Err(format!("Longitude {} not in range -180.0..=180.0", lng));
}
Ok(Self { lat, lng })
}
pub fn lat(&self) -> f64 {
self.lat
}
pub fn lng(&self) -> f64 {
self.lng
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_input() {
assert!(GeoCoord::new(0., 0.).is_ok());
// latitude extremes
assert!(GeoCoord::new(-90.0, 0.).is_ok());
assert!(GeoCoord::new(90.0, 0.).is_ok());
// longitude extremes
assert!(GeoCoord::new(0., -180.0).is_ok());
assert!(GeoCoord::new(0., 180.0).is_ok());
}
#[test]
fn test_out_of_bounds() {
// latitude out-of-bounds
assert!(GeoCoord::new(-91., 0.).is_err());
assert!(GeoCoord::new(91., 0.).is_err());
// longitude out-of-bounds
assert!(GeoCoord::new(0., -181.).is_err());
assert!(GeoCoord::new(0., 181.).is_err());
}
}

View File

@@ -1,21 +1,21 @@
use crate::cartesian::XZPoint;
use crate::{bbox::BBox, 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;
const MAX_Y: i32 = 319;
/// Scale factor for converting real elevation to Minecraft heights
const BASE_HEIGHT_SCALE: f64 = 0.6;
const BASE_HEIGHT_SCALE: f64 = 0.72;
/// Mapbox API access token for terrain data
const MAPBOX_PUBKEY: &str =
"pk.eyJ1IjoibG91aXMtZSIsImEiOiJjbWF0cWlycjEwYWNvMmtxeHFwdDQ5NnJoIn0.6A0AKg0iucvoGhYuCkeOjA";
"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
#[derive(Clone)]
pub struct Ground {
pub elevation_enabled: bool,
ground_level: i32,
@@ -36,8 +36,8 @@ struct ElevationData {
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) {
let elevation_data: Option<ElevationData> = if elevation_enabled {
match Self::fetch_elevation_data(args) {
Ok(data) => {
if args.debug {
Self::save_debug_image(&data.heights, "elevation_debug");
@@ -73,6 +73,7 @@ impl Ground {
self.interpolate_height(x_ratio, z_ratio, data)
}
#[allow(unused)]
#[inline(always)]
pub fn min_level<I: Iterator<Item = XZPoint>>(&self, coords: I) -> Option<i32> {
if !self.elevation_enabled {
@@ -81,6 +82,7 @@ impl Ground {
coords.map(|c: XZPoint| self.level(c)).min()
}
#[allow(unused)]
#[inline(always)]
pub fn max_level<I: Iterator<Item = XZPoint>>(&self, coords: I) -> Option<i32> {
if !self.elevation_enabled {
@@ -106,9 +108,9 @@ impl Ground {
}
/// 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();
fn calculate_zoom_level(bbox: BBox) -> u8 {
let lat_diff: f64 = (bbox.max().lat() - bbox.min().lat()).abs();
let lng_diff: f64 = (bbox.max().lng() - bbox.min().lng()).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)
@@ -124,26 +126,17 @@ impl Ground {
}
fn fetch_elevation_data(
bbox_str: &str,
scale: f64,
args: &crate::args::Args,
) -> 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;
crate::osm_parser::geo_distance(args.bbox.min(), args.bbox.max());
let scale_factor_x: f64 = scale_factor_x * args.scale;
let scale_factor_z: f64 = scale_factor_z * args.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);
let zoom: u8 = Self::calculate_zoom_level(args.bbox);
let tiles: Vec<(u32, u32)> = Self::get_tile_coordinates(args.bbox, zoom);
// Calculate tile boundaries
let x_min: &u32 = tiles.iter().map(|(x, _)| x).min().unwrap();
@@ -225,7 +218,7 @@ impl Ground {
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 height_scale: f64 = BASE_HEIGHT_SCALE * args.scale.sqrt(); // sqrt to make height scaling less extreme
let scaled_range: f64 = height_range * height_scale;
// Convert to scaled Minecraft Y coordinates
@@ -236,7 +229,9 @@ impl Ground {
// 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)
// With terrain enabled, ground_level is used as the MIN_Y for terrain
((args.ground_level as f64 + scaled_height).round() as i32)
.clamp(args.ground_level, MAX_Y)
})
.collect();
mc_heights.push(mc_row);
@@ -249,16 +244,10 @@ impl Ground {
})
}
fn get_tile_coordinates(
min_lat: f64,
min_lng: f64,
max_lat: f64,
max_lng: f64,
zoom: u8,
) -> Vec<(u32, u32)> {
fn get_tile_coordinates(bbox: BBox, 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 (x1, y1) = Self::lat_lng_to_tile(bbox.min().lat(), bbox.min().lng(), zoom);
let (x2, y2) = Self::lat_lng_to_tile(bbox.max().lat(), bbox.max().lng(), zoom);
let mut tiles: Vec<(u32, u32)> = Vec::new();
for x in x1.min(x2)..=x1.max(x2) {

476
src/gui.rs Normal file
View File

@@ -0,0 +1,476 @@
use crate::args::Args;
use crate::bbox;
use crate::data_processing;
use crate::osm_parser;
use crate::progress;
use crate::retrieve_data;
use crate::version_check;
use fastnbt::Value;
use flate2::read::GzDecoder;
use log::{error, LevelFilter};
use rfd::FileDialog;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::{env, fs, io::Write, panic};
use tauri_plugin_log::{Builder as LogBuilder, Target, TargetKind};
pub fn run_gui() {
// Launch the UI
println!("Launching UI...");
// 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)");
}
#[tauri::command]
fn gui_select_world(generate_new: bool) -> Result<String, i32> {
// Determine the default Minecraft 'saves' directory based on the OS
let default_dir: Option<PathBuf> = if cfg!(target_os = "windows") {
env::var("APPDATA")
.ok()
.map(|appdata: String| PathBuf::from(appdata).join(".minecraft").join("saves"))
} else if cfg!(target_os = "macos") {
dirs::home_dir().map(|home: PathBuf| {
home.join("Library/Application Support/minecraft")
.join("saves")
})
} else if cfg!(target_os = "linux") {
dirs::home_dir().map(|home| {
let flatpak_path = home.join(".var/app/com.mojang.Minecraft/.minecraft/saves");
if flatpak_path.exists() {
flatpak_path
} else {
home.join(".minecraft/saves")
}
})
} else {
None
};
if generate_new {
// Handle new world generation
if let Some(default_path) = &default_dir {
if default_path.exists() {
// Call create_new_world and return the result
create_new_world(default_path).map_err(|_| 1) // Error code 1: Minecraft directory not found
} else {
Err(1) // Error code 1: Minecraft directory not found
}
} else {
Err(1) // Error code 1: Minecraft directory not found
}
} else {
// Handle existing world selection
// Open the directory picker dialog
let dialog: FileDialog = FileDialog::new();
let dialog: FileDialog = if let Some(start_dir) = default_dir.filter(|dir| dir.exists()) {
dialog.set_directory(start_dir)
} else {
dialog
};
if let Some(path) = dialog.pick_folder() {
// Check if the "region" folder exists within the selected directory
if path.join("region").exists() {
// Check the 'session.lock' file
let session_lock_path = path.join("session.lock");
if session_lock_path.exists() {
// Try to acquire a lock on the session.lock file
if let Ok(file) = fs::File::open(&session_lock_path) {
if fs2::FileExt::try_lock_shared(&file).is_err() {
return Err(2); // Error code 2: The selected world is currently in use
} else {
// Release the lock immediately
let _ = fs2::FileExt::unlock(&file);
}
}
}
return Ok(path.display().to_string());
} else {
// No Minecraft directory found, generating new world in custom user selected directory
return create_new_world(&path).map_err(|_| 3); // Error code 3: Failed to create new world
}
}
// If no folder was selected, return an error message
Err(4) // Error code 4: No world selected
}
}
fn create_new_world(base_path: &Path) -> Result<String, String> {
// Generate a unique world name with proper counter
// Check for both "Arnis World X" and "Arnis World X: Location" patterns
let mut counter: i32 = 1;
let unique_name: String = loop {
let candidate_name: String = format!("Arnis World {}", counter);
let candidate_path: PathBuf = base_path.join(&candidate_name);
// Check for exact match (no location suffix)
let exact_match_exists = candidate_path.exists();
// Check for worlds with location suffix (Arnis World X: Location)
let location_pattern = format!("Arnis World {}: ", counter);
let location_match_exists = fs::read_dir(base_path)
.map(|entries| {
entries
.filter_map(Result::ok)
.filter_map(|entry| entry.file_name().into_string().ok())
.any(|name| name.starts_with(&location_pattern))
})
.unwrap_or(false);
if !exact_match_exists && !location_match_exists {
break candidate_name;
}
counter += 1;
};
let new_world_path: PathBuf = base_path.join(&unique_name);
// Create the new world directory structure
fs::create_dir_all(new_world_path.join("region"))
.map_err(|e| format!("Failed to create world directory: {}", e))?;
// Copy the region template file
const REGION_TEMPLATE: &[u8] = include_bytes!("../mcassets/region.template");
let region_path = new_world_path.join("region").join("r.0.0.mca");
fs::write(&region_path, REGION_TEMPLATE)
.map_err(|e| format!("Failed to create region file: {}", e))?;
// Add the level.dat file
const LEVEL_TEMPLATE: &[u8] = include_bytes!("../mcassets/level.dat");
// Decompress the gzipped level.template
let mut decoder = GzDecoder::new(LEVEL_TEMPLATE);
let mut decompressed_data = Vec::new();
decoder
.read_to_end(&mut decompressed_data)
.map_err(|e| format!("Failed to decompress level.template: {}", e))?;
// Parse the decompressed NBT data
let mut level_data: Value = fastnbt::from_bytes(&decompressed_data)
.map_err(|e| format!("Failed to parse level.dat template: {}", e))?;
// 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
data.insert("LevelName".to_string(), Value::String(unique_name.clone()));
// Update LastPlayed to the current Unix time in milliseconds
let current_time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.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;
}
}
}
}
}
// Serialize the updated NBT data back to bytes
let serialized_level_data: Vec<u8> = fastnbt::to_bytes(&level_data)
.map_err(|e| format!("Failed to serialize updated level.dat: {}", e))?;
// Compress the serialized data back to gzip
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder
.write_all(&serialized_level_data)
.map_err(|e| format!("Failed to compress updated level.dat: {}", e))?;
let compressed_level_data = encoder
.finish()
.map_err(|e| format!("Failed to finalize compression for level.dat: {}", e))?;
// Write the level.dat file
fs::write(new_world_path.join("level.dat"), compressed_level_data)
.map_err(|e| format!("Failed to create level.dat file: {}", e))?;
// Add the icon.png file
const ICON_TEMPLATE: &[u8] = include_bytes!("../mcassets/icon.png");
fs::write(new_world_path.join("icon.png"), ICON_TEMPLATE)
.map_err(|e| format!("Failed to create icon.png file: {}", e))?;
Ok(new_world_path.display().to_string())
}
/// Adds localized area name to the world name in level.dat
fn add_localized_world_name(world_path_str: &str, bbox: &bbox::BBox) -> String {
let world_path = PathBuf::from(world_path_str);
// Only proceed if the path exists
if !world_path.exists() {
return world_path_str.to_string();
}
// Check the level.dat file first to get the current name
let level_path = world_path.join("level.dat");
if !level_path.exists() {
return world_path_str.to_string();
}
// Try to read the current world name from level.dat
let current_name = match std::fs::read(&level_path) {
Ok(level_data) => {
let mut decoder = GzDecoder::new(level_data.as_slice());
let mut decompressed_data = Vec::new();
if decoder.read_to_end(&mut decompressed_data).is_ok() {
if let Ok(Value::Compound(ref root)) =
fastnbt::from_bytes::<Value>(&decompressed_data)
{
if let Some(Value::Compound(ref data)) = root.get("Data") {
if let Some(Value::String(name)) = data.get("LevelName") {
name.clone()
} else {
return world_path_str.to_string();
}
} else {
return world_path_str.to_string();
}
} else {
return world_path_str.to_string();
}
} else {
return world_path_str.to_string();
}
}
Err(_) => return world_path_str.to_string(),
};
// Only modify if it's an Arnis world and doesn't already have an area name
if !current_name.starts_with("Arnis World ") || current_name.contains(": ") {
return world_path_str.to_string();
}
// Calculate center coordinates of bbox
let center_lat = (bbox.min().lat() + bbox.max().lat()) / 2.0;
let center_lon = (bbox.min().lng() + bbox.max().lng()) / 2.0;
// Try to fetch the area name
let area_name = match retrieve_data::fetch_area_name(center_lat, center_lon) {
Ok(Some(name)) => name,
_ => return world_path_str.to_string(), // Keep original name if no area name found
};
// Create new name with localized area name, ensuring total length doesn't exceed 30 characters
let base_name = current_name.clone();
let max_area_name_len = 30 - base_name.len() - 2; // 2 chars for ": "
let truncated_area_name =
if area_name.chars().count() > max_area_name_len && max_area_name_len > 0 {
// Truncate the area name to fit within the 30 character limit
area_name
.chars()
.take(max_area_name_len)
.collect::<String>()
} else if max_area_name_len == 0 {
// If base name is already too long, don't add area name
return world_path_str.to_string();
} else {
area_name
};
let new_name = format!("{}: {}", base_name, truncated_area_name);
// Update the level.dat file with the new name
if let Ok(level_data) = std::fs::read(&level_path) {
let mut decoder = GzDecoder::new(level_data.as_slice());
let mut decompressed_data = Vec::new();
if decoder.read_to_end(&mut decompressed_data).is_ok() {
if let Ok(mut nbt_data) = fastnbt::from_bytes::<Value>(&decompressed_data) {
// Update the level name in NBT data
if let Value::Compound(ref mut root) = nbt_data {
if let Some(Value::Compound(ref mut data)) = root.get_mut("Data") {
data.insert("LevelName".to_string(), Value::String(new_name));
// Save the updated NBT data
if let Ok(serialized_data) = fastnbt::to_bytes(&nbt_data) {
let mut encoder = flate2::write::GzEncoder::new(
Vec::new(),
flate2::Compression::default(),
);
if encoder.write_all(&serialized_data).is_ok() {
if let Ok(compressed_data) = encoder.finish() {
if let Err(e) = std::fs::write(&level_path, compressed_data) {
eprintln!(
"Failed to update level.dat with area name: {}",
e
);
}
}
}
}
}
}
}
}
}
// Return the original path since we didn't change the directory name
world_path_str.to_string()
}
#[tauri::command]
fn gui_get_version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[tauri::command]
fn gui_check_for_updates() -> Result<bool, String> {
match version_check::check_for_updates() {
Ok(is_newer) => Ok(is_newer),
Err(e) => Err(format!("Error checking for updates: {}", e)),
}
}
#[tauri::command]
#[allow(clippy::too_many_arguments)]
fn gui_start_generation(
bbox_text: String,
selected_world: String,
world_scale: f64,
ground_level: i32,
floodfill_timeout: u64,
terrain_enabled: bool,
fillground_enabled: bool,
is_new_world: bool,
) -> Result<(), String> {
use bbox::BBox;
use progress::emit_gui_error;
tauri::async_runtime::spawn(async move {
if let Err(e) = tokio::task::spawn_blocking(move || {
// Parse the bounding box from the text with proper error handling
let bbox = match BBox::from_str(&bbox_text) {
Ok(bbox) => bbox,
Err(e) => {
let error_msg = format!("Failed to parse bounding box: {}", e);
eprintln!("{}", error_msg);
emit_gui_error(&error_msg);
return Err(error_msg);
}
};
// Add localized name to the world if user generated a new world
let updated_world_path = if is_new_world {
add_localized_world_name(&selected_world, &bbox)
} else {
selected_world
};
// Create an Args instance with the chosen bounding box and world directory path
let args: Args = Args {
bbox,
file: None,
path: updated_world_path,
downloader: "requests".to_string(),
scale: world_scale,
ground_level,
terrain: terrain_enabled,
fillground: fillground_enabled,
debug: false,
timeout: Some(std::time::Duration::from_secs(floodfill_timeout)),
};
// Run data fetch and world generation
match retrieve_data::fetch_data(args.bbox, None, args.debug, "requests") {
Ok(raw_data) => {
let (mut parsed_elements, scale_factor_x, scale_factor_z) =
osm_parser::parse_osm_data(&raw_data, args.bbox, &args);
parsed_elements.sort_by(|el1, el2| {
let (el1_priority, el2_priority) =
(osm_parser::get_priority(el1), osm_parser::get_priority(el2));
match (
el1.tags().contains_key("landuse"),
el2.tags().contains_key("landuse"),
) {
(true, false) => std::cmp::Ordering::Greater,
(false, true) => std::cmp::Ordering::Less,
_ => el1_priority.cmp(&el2_priority),
}
});
let _ = data_processing::generate_world(
parsed_elements,
&args,
scale_factor_x,
scale_factor_z,
);
Ok(())
}
Err(e) => {
let error_msg = format!("Failed to fetch data: {}", e);
emit_gui_error(&error_msg);
Err(error_msg)
}
}
})
.await
{
let error_msg = format!("Error in blocking task: {}", e);
eprintln!("{}", error_msg);
emit_gui_error(&error_msg);
}
});
Ok(())
}

View File

@@ -1,6 +1,7 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod args;
mod bbox;
mod block_definitions;
mod bresenham;
mod cartesian;
@@ -8,10 +9,23 @@ mod colors;
mod data_processing;
mod element_processing;
mod floodfill;
mod geo_coord;
mod ground;
mod osm_parser;
#[cfg(feature = "gui")]
mod progress;
mod retrieve_data;
mod version_check;
mod world_editor;
use args::Args;
use clap::Parser;
use colored::*;
use std::{env, fs, io::Write};
#[cfg(feature = "gui")]
mod gui;
// 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 {
@@ -21,30 +35,11 @@ mod progress {
false
}
}
mod retrieve_data;
mod version_check;
mod world_editor;
use args::Args;
use clap::Parser;
use colored::*;
use fastnbt::Value;
use flate2::read::GzDecoder;
use log::{error, LevelFilter};
use rfd::FileDialog;
use std::{
env,
fs::{self, File},
io::{Read, Write},
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() {
fn run_cli() {
let version: &str = env!("CARGO_PKG_VERSION");
let repository: &str = env!("CARGO_PKG_REPOSITORY");
println!(
@@ -65,6 +60,49 @@ fn print_banner() {
version,
repository.bright_white().bold()
);
// Check for updates
if let Err(e) = version_check::check_for_updates() {
eprintln!(
"{}: {}",
"Error checking for version updates".red().bold(),
e
);
}
// Parse input arguments
let args: Args = Args::parse();
args.run();
// Fetch data
let raw_data: serde_json::Value =
retrieve_data::fetch_data(args.bbox, args.file.as_deref(), args.debug, "requests")
.expect("Failed to fetch data");
// Parse raw data
let (mut parsed_elements, scale_factor_x, scale_factor_z) =
osm_parser::parse_osm_data(&raw_data, args.bbox, &args);
parsed_elements
.sort_by_key(|element: &osm_parser::ProcessedElement| osm_parser::get_priority(element));
// Write the parsed OSM data to a file for inspection
if args.debug {
let mut output_file: fs::File =
fs::File::create("parsed_osm_data.txt").expect("Failed to create output file");
for element in &parsed_elements {
writeln!(
output_file,
"Element ID: {}, Type: {}, Tags: {:?}",
element.id(),
element.kind(),
element.tags(),
)
.expect("Failed to write to output file");
}
}
// Generate world
let _ = data_processing::generate_world(parsed_elements, &args, scale_factor_x, scale_factor_z);
}
fn main() {
@@ -76,399 +114,14 @@ fn main() {
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();
// Check if either `--help` or `--path` is present to run command-line mode
let is_help: bool = raw_args.iter().any(|arg: &String| arg == "--help");
let is_path_provided: bool = raw_args
.iter()
.any(|arg: &String| arg.starts_with("--path"));
if is_help || is_path_provided {
print_banner();
// Check for updates
if let Err(e) = version_check::check_for_updates() {
eprintln!(
"{}: {}",
"Error checking for version updates".red().bold(),
e
);
}
// Parse input arguments
let args: Args = Args::parse();
args.run();
let bbox: Vec<f64> = args
.bbox
.as_ref()
.expect("Bounding box is required")
.split(',')
.map(|s: &str| s.parse::<f64>().expect("Invalid bbox coordinate"))
.collect::<Vec<f64>>();
let bbox_tuple: (f64, f64, f64, f64) = (bbox[0], bbox[1], bbox[2], bbox[3]);
// Fetch data
let raw_data: serde_json::Value =
retrieve_data::fetch_data(bbox_tuple, args.file.as_deref(), args.debug, "requests")
.expect("Failed to fetch data");
// Parse raw data
let (mut parsed_elements, scale_factor_x, scale_factor_z) =
osm_parser::parse_osm_data(&raw_data, bbox_tuple, &args);
parsed_elements.sort_by_key(|element: &osm_parser::ProcessedElement| {
osm_parser::get_priority(element)
});
// Write the parsed OSM data to a file for inspection
if args.debug {
let mut output_file: File =
File::create("parsed_osm_data.txt").expect("Failed to create output file");
for element in &parsed_elements {
writeln!(
output_file,
"Element ID: {}, Type: {}, Tags: {:?}",
element.id(),
element.kind(),
element.tags(),
)
.expect("Failed to write to output file");
}
}
// Generate world
let _ =
data_processing::generate_world(parsed_elements, &args, scale_factor_x, scale_factor_z);
} else {
#[cfg(not(feature = "gui"))]
{
panic!("This version of arnis was not built with GUI enabled");
}
#[cfg(feature = "gui")]
{
// Launch the UI
println!("Launching UI...");
// 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
let default_dir: Option<PathBuf> = if cfg!(target_os = "windows") {
env::var("APPDATA")
.ok()
.map(|appdata: String| PathBuf::from(appdata).join(".minecraft").join("saves"))
} else if cfg!(target_os = "macos") {
dirs::home_dir().map(|home: PathBuf| {
home.join("Library/Application Support/minecraft")
.join("saves")
})
} else if cfg!(target_os = "linux") {
dirs::home_dir().map(|home| {
let flatpak_path = home.join(".var/app/com.mojang.Minecraft/.minecraft/saves");
if flatpak_path.exists() {
flatpak_path
} else {
home.join(".minecraft/saves")
}
})
} else {
None
};
if generate_new {
// Handle new world generation
if let Some(default_path) = &default_dir {
if default_path.exists() {
// Call create_new_world and return the result
create_new_world(default_path).map_err(|_| 1) // Error code 1: Minecraft directory not found
} else {
Err(1) // Error code 1: Minecraft directory not found
}
} else {
Err(1) // Error code 1: Minecraft directory not found
}
} else {
// Handle existing world selection
// Open the directory picker dialog
let dialog: FileDialog = FileDialog::new();
let dialog: FileDialog = if let Some(start_dir) = default_dir.filter(|dir| dir.exists()) {
dialog.set_directory(start_dir)
} else {
dialog
};
if let Some(path) = dialog.pick_folder() {
// Check if the "region" folder exists within the selected directory
if path.join("region").exists() {
// Check the 'session.lock' file
let session_lock_path = path.join("session.lock");
if session_lock_path.exists() {
// Try to acquire a lock on the session.lock file
if let Ok(file) = File::open(&session_lock_path) {
if fs2::FileExt::try_lock_shared(&file).is_err() {
return Err(2); // Error code 2: The selected world is currently in use
} else {
// Release the lock immediately
let _ = fs2::FileExt::unlock(&file);
}
}
}
return Ok(path.display().to_string());
} else {
// No Minecraft directory found, generating new world in custom user selected directory
return create_new_world(&path).map_err(|_| 3); // Error code 3: Failed to create new world
}
}
// If no folder was selected, return an error message
Err(4) // Error code 4: No world selected
}
}
fn create_new_world(base_path: &Path) -> Result<String, String> {
// Generate a unique world name
let mut counter: i32 = 1;
let unique_name: String = loop {
let candidate_name: String = format!("Arnis World {}", counter);
let candidate_path: PathBuf = base_path.join(&candidate_name);
if !candidate_path.exists() {
break candidate_name;
}
counter += 1;
};
let new_world_path: PathBuf = base_path.join(&unique_name);
// Create the new world directory structure
fs::create_dir_all(new_world_path.join("region"))
.map_err(|e| format!("Failed to create world directory: {}", e))?;
// Copy the region template file
const REGION_TEMPLATE: &[u8] = include_bytes!("../mcassets/region.template");
let region_path = new_world_path.join("region").join("r.0.0.mca");
fs::write(&region_path, REGION_TEMPLATE)
.map_err(|e| format!("Failed to create region file: {}", e))?;
// Add the level.dat file
const LEVEL_TEMPLATE: &[u8] = include_bytes!("../mcassets/level.dat");
// Decompress the gzipped level.template
let mut decoder = GzDecoder::new(LEVEL_TEMPLATE);
let mut decompressed_data = Vec::new();
decoder
.read_to_end(&mut decompressed_data)
.map_err(|e| format!("Failed to decompress level.template: {}", e))?;
// Parse the decompressed NBT data
let mut level_data: Value = fastnbt::from_bytes(&decompressed_data)
.map_err(|e| format!("Failed to parse level.dat template: {}", e))?;
// 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
data.insert("LevelName".to_string(), Value::String(unique_name.clone()));
// Update LastPlayed to the current Unix time in milliseconds
let current_time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.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;
}
}
}
// Only run CLI mode if the user supplied args.
#[cfg(feature = "gui")]
{
let gui_mode = std::env::args().len() == 1; // Just "arnis" with no args
if gui_mode {
gui::run_gui();
}
}
// Serialize the updated NBT data back to bytes
let serialized_level_data: Vec<u8> = fastnbt::to_bytes(&level_data)
.map_err(|e| format!("Failed to serialize updated level.dat: {}", e))?;
// Compress the serialized data back to gzip
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder
.write_all(&serialized_level_data)
.map_err(|e| format!("Failed to compress updated level.dat: {}", e))?;
let compressed_level_data = encoder
.finish()
.map_err(|e| format!("Failed to finalize compression for level.dat: {}", e))?;
// Write the level.dat file
fs::write(new_world_path.join("level.dat"), compressed_level_data)
.map_err(|e| format!("Failed to create level.dat file: {}", e))?;
// Add the icon.png file
const ICON_TEMPLATE: &[u8] = include_bytes!("../mcassets/icon.png");
fs::write(new_world_path.join("icon.png"), ICON_TEMPLATE)
.map_err(|e| format!("Failed to create icon.png file: {}", e))?;
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() {
Ok(is_newer) => Ok(is_newer),
Err(e) => Err(format!("Error checking for updates: {}", e)),
}
}
#[cfg(feature = "gui")]
#[tauri::command]
fn gui_start_generation(
bbox_text: String,
selected_world: String,
world_scale: f64,
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 || {
// Utility function to reorder bounding box coordinates
fn reorder_bbox(bbox: &[f64]) -> (f64, f64, f64, f64) {
(bbox[1], bbox[0], bbox[3], bbox[2])
}
// Parse bounding box string and validate it
let bbox: Vec<f64> = bbox_text
.split_whitespace()
.map(|s| s.parse::<f64>().expect("Invalid bbox coordinate"))
.collect();
if bbox.len() != 4 {
return Err("Invalid bounding box format".to_string());
}
// Create an Args instance with the chosen bounding box and world directory path
let args: Args = Args {
bbox: Some(bbox_text),
file: None,
path: selected_world,
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)),
};
// Reorder bounding box coordinates for further processing
let reordered_bbox: (f64, f64, f64, f64) = reorder_bbox(&bbox);
// Run data fetch and world generation
match retrieve_data::fetch_data(reordered_bbox, None, args.debug, "requests") {
Ok(raw_data) => {
let (mut parsed_elements, scale_factor_x, scale_factor_z) =
osm_parser::parse_osm_data(&raw_data, reordered_bbox, &args);
parsed_elements.sort_by(|el1, el2| {
let (el1_priority, el2_priority) =
(osm_parser::get_priority(el1), osm_parser::get_priority(el2));
match (
el1.tags().contains_key("landuse"),
el2.tags().contains_key("landuse"),
) {
(true, false) => std::cmp::Ordering::Greater,
(false, true) => std::cmp::Ordering::Less,
_ => el1_priority.cmp(&el2_priority),
}
});
let _ = data_processing::generate_world(
parsed_elements,
&args,
scale_factor_x,
scale_factor_z,
);
Ok(())
}
Err(e) => Err(format!("Failed to start generation: {}", e)),
}
})
.await
{
eprintln!("Error in blocking task: {}", e);
}
});
Ok(())
run_cli();
}

View File

@@ -1,4 +1,7 @@
use crate::{args::Args, cartesian::XZPoint, progress::emit_gui_progress_update};
use crate::{
args::Args, bbox::BBox, cartesian::XZPoint, geo_coord::GeoCoord,
progress::emit_gui_progress_update,
};
use colored::Colorize;
use serde::Deserialize;
use serde_json::Value;
@@ -124,15 +127,13 @@ impl ProcessedElement {
fn lat_lon_to_minecraft_coords(
lat: f64,
lon: f64,
bbox: (f64, f64, f64, f64), // (min_lon, min_lat, max_lon, max_lat)
bbox: BBox, // (min_lon, min_lat, max_lon, max_lat)
scale_factor_z: f64,
scale_factor_x: f64,
) -> (i32, i32) {
let (min_lon, min_lat, max_lon, max_lat) = bbox;
// Calculate the relative position within the bounding box
let rel_x: f64 = (lon - min_lon) / (max_lon - min_lon);
let rel_z: f64 = 1.0 - (lat - min_lat) / (max_lat - min_lat);
let rel_x: f64 = (lon - bbox.min().lng()) / (bbox.max().lng() - bbox.min().lng());
let rel_z: f64 = 1.0 - (lat - bbox.min().lat()) / (bbox.max().lat() - bbox.min().lat());
// Apply scaling factors for each dimension and convert to Minecraft coordinates
let x: i32 = (rel_x * scale_factor_x) as i32;
@@ -143,7 +144,7 @@ fn lat_lon_to_minecraft_coords(
pub fn parse_osm_data(
json_data: &Value,
bbox: (f64, f64, f64, f64),
bbox: BBox,
args: &Args,
) -> (Vec<ProcessedElement>, f64, f64) {
println!("{} Parsing data...", "[2/5]".bold());
@@ -154,7 +155,7 @@ pub fn parse_osm_data(
serde_json::from_value(json_data.clone()).expect("Failed to parse OSM data");
// Determine which dimension is larger and assign scale factors accordingly
let (scale_factor_z, scale_factor_x) = geo_distance(bbox.1, bbox.3, bbox.0, bbox.2);
let (scale_factor_z, scale_factor_x) = geo_distance(bbox.min(), bbox.max());
let scale_factor_z: f64 = scale_factor_z.floor() * args.scale;
let scale_factor_x: f64 = scale_factor_x.floor() * args.scale;
@@ -291,11 +292,11 @@ pub fn get_priority(element: &ProcessedElement) -> usize {
// (lat meters, lon meters)
#[inline]
pub fn geo_distance(lat1: f64, lat2: f64, lon1: f64, lon2: f64) -> (f64, f64) {
let z: f64 = lat_distance(lat1, lat2);
pub fn geo_distance(a: GeoCoord, b: GeoCoord) -> (f64, f64) {
let z: f64 = lat_distance(a.lat(), b.lat());
// distance between two lons depends on their latitude. In this case we'll just average them
let x: f64 = lon_distance((lat1 + lat2) / 2.0, lon1, lon2);
let x: f64 = lon_distance((a.lat() + b.lat()) / 2.0, a.lng(), b.lng());
(z, x)
}

View File

@@ -1,3 +1,4 @@
use crate::bbox::BBox;
use crate::progress::{emit_gui_error, emit_gui_progress_update, is_running_with_gui};
use colored::Colorize;
use rand::seq::SliceRandom;
@@ -80,7 +81,7 @@ fn download_with_wget(url: &str, query: &str) -> io::Result<String> {
/// Main function to fetch data
pub fn fetch_data(
bbox: (f64, f64, f64, f64),
bbox: BBox,
file: Option<&str>,
debug: bool,
download_method: &str,
@@ -115,6 +116,9 @@ pub fn fetch_data(
nwr["tourism"];
nwr["bridge"];
nwr["railway"];
nwr["subway"="yes"];
nwr["tunnel"="yes"];
nwr["public_transport"="station"];
nwr["barrier"];
nwr["entrance"];
nwr["door"];
@@ -130,7 +134,10 @@ pub fn fetch_data(
.relsinbbox out body;
.waysinbbox out body;
.nodesinbbox out skel qt;"#,
bbox.1, bbox.0, bbox.3, bbox.2
bbox.min().lat(),
bbox.min().lng(),
bbox.max().lat(),
bbox.max().lng(),
);
if let Some(file) = file {
@@ -220,3 +227,32 @@ pub fn fetch_data(
Ok(data)
}
}
/// Fetches a short area name using Nominatim for the given lat/lon
pub fn fetch_area_name(lat: f64, lon: f64) -> Result<Option<String>, Box<dyn std::error::Error>> {
let client = Client::builder().timeout(Duration::from_secs(20)).build()?;
let url = format!(
"https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat={}&lon={}&addressdetails=1",
lat, lon
);
let resp = client.get(&url).header("User-Agent", "arnis-rust").send()?;
if !resp.status().is_success() {
return Ok(None);
}
let json: Value = resp.json()?;
if let Some(address) = json.get("address") {
let fields = ["city", "town", "village", "county", "borough", "suburb"];
for field in fields.iter() {
if let Some(name) = address.get(*field).and_then(|v| v.as_str()) {
return Ok(Some(name.to_string()));
}
}
}
Ok(None)
}

View File

@@ -1,4 +1,6 @@
use crate::block_definitions::*;
use crate::cartesian::XZPoint;
use crate::ground::Ground;
use crate::progress::emit_gui_progress_update;
use colored::Colorize;
use fastanvil::Region;
@@ -232,6 +234,7 @@ pub struct WorldEditor {
world: WorldToModify,
scale_factor_x: f64,
scale_factor_z: f64,
ground: Option<Box<Ground>>,
}
impl WorldEditor {
@@ -242,6 +245,22 @@ impl WorldEditor {
world: WorldToModify::default(),
scale_factor_x,
scale_factor_z,
ground: None,
}
}
/// Sets the ground reference for elevation-based block placement
pub fn set_ground(&mut self, ground: &Ground) {
self.ground = Some(Box::new(ground.clone()));
}
/// Calculate the absolute Y position from a ground-relative offset
#[inline(always)]
pub fn get_absolute_y(&self, x: i32, y_offset: i32, z: i32) -> i32 {
if let Some(ground) = &self.ground {
ground.level(XZPoint::new(x, z)) + y_offset
} else {
y_offset // If no ground reference, use y_offset as absolute Y
}
}
@@ -270,8 +289,11 @@ impl WorldEditor {
(self.scale_factor_x as i32, self.scale_factor_x as i32)
}
#[allow(unused)]
#[inline]
pub fn block_at(&self, x: i32, y: i32, z: i32) -> bool {
self.world.get_block(x, y, z).is_some()
let absolute_y = self.get_absolute_y(x, y, z);
self.world.get_block(x, absolute_y, z).is_some()
}
#[allow(clippy::too_many_arguments, dead_code)]
@@ -286,6 +308,7 @@ impl WorldEditor {
z: i32,
_rotation: i8,
) {
let absolute_y = self.get_absolute_y(x, y, z);
let chunk_x = x >> 4;
let chunk_z = z >> 4;
let region_x = chunk_x >> 5;
@@ -313,7 +336,7 @@ impl WorldEditor {
block_entities.insert("is_waxed".to_string(), Value::Byte(0));
block_entities.insert("keepPacked".to_string(), Value::Byte(0));
block_entities.insert("x".to_string(), Value::Int(x));
block_entities.insert("y".to_string(), Value::Int(y));
block_entities.insert("y".to_string(), Value::Int(absolute_y));
block_entities.insert("z".to_string(), Value::Int(z));
let region: &mut RegionToModify = self.world.get_or_create_region(region_x, region_z);
@@ -334,6 +357,8 @@ impl WorldEditor {
}
/// Sets a block of the specified type at the given coordinates.
/// Y value is interpreted as an offset from ground level.
#[inline]
pub fn set_block(
&mut self,
block: Block,
@@ -348,7 +373,10 @@ impl WorldEditor {
return;
}
let should_insert = if let Some(existing_block) = self.world.get_block(x, y, z) {
// Calculate the absolute Y coordinate based on ground level
let absolute_y = self.get_absolute_y(x, y, z);
let should_insert = if let Some(existing_block) = self.world.get_block(x, absolute_y, z) {
// Check against whitelist and blacklist
if let Some(whitelist) = override_whitelist {
whitelist
@@ -366,12 +394,51 @@ impl WorldEditor {
};
if should_insert {
self.world.set_block(x, y, z, block);
self.world.set_block(x, absolute_y, z, block);
}
}
/// Sets a block of the specified type at the given coordinates with absolute Y value.
#[inline]
pub fn set_block_absolute(
&mut self,
block: Block,
x: i32,
absolute_y: i32,
z: i32,
override_whitelist: Option<&[Block]>,
override_blacklist: Option<&[Block]>,
) {
// Check if coordinates are within bounds
if x < 0 || x > self.scale_factor_x as i32 || z < 0 || z > self.scale_factor_z as i32 {
return;
}
let should_insert = if let Some(existing_block) = self.world.get_block(x, absolute_y, z) {
// Check against whitelist and blacklist
if let Some(whitelist) = override_whitelist {
whitelist
.iter()
.any(|whitelisted_block: &Block| whitelisted_block.id() == existing_block.id())
} else if let Some(blacklist) = override_blacklist {
!blacklist
.iter()
.any(|blacklisted_block: &Block| blacklisted_block.id() == existing_block.id())
} else {
false
}
} else {
true
};
if should_insert {
self.world.set_block(x, absolute_y, z, block);
}
}
/// Fills a cuboid area with the specified block between two coordinates.
#[allow(clippy::too_many_arguments)]
#[inline]
pub fn fill_blocks(
&mut self,
block: Block,
@@ -389,25 +456,91 @@ impl WorldEditor {
let (min_z, max_z) = if z1 < z2 { (z1, z2) } else { (z2, z1) };
for x in min_x..=max_x {
for y in min_y..=max_y {
for y_offset in min_y..=max_y {
for z in min_z..=max_z {
self.set_block(block, x, y, z, override_whitelist, override_blacklist);
self.set_block(
block,
x,
y_offset,
z,
override_whitelist,
override_blacklist,
);
}
}
}
}
/// Fills a cuboid area with the specified block between two coordinates using absolute Y values.
#[allow(clippy::too_many_arguments)]
#[inline]
pub fn fill_blocks_absolute(
&mut self,
block: Block,
x1: i32,
y1_absolute: i32,
z1: i32,
x2: i32,
y2_absolute: i32,
z2: i32,
override_whitelist: Option<&[Block]>,
override_blacklist: Option<&[Block]>,
) {
let (min_x, max_x) = if x1 < x2 { (x1, x2) } else { (x2, x1) };
let (min_y, max_y) = if y1_absolute < y2_absolute {
(y1_absolute, y2_absolute)
} else {
(y2_absolute, y1_absolute)
};
let (min_z, max_z) = if z1 < z2 { (z1, z2) } else { (z2, z1) };
for x in min_x..=max_x {
for absolute_y in min_y..=max_y {
for z in min_z..=max_z {
self.set_block_absolute(
block,
x,
absolute_y,
z,
override_whitelist,
override_blacklist,
);
}
}
}
}
/// Checks for a block at the given coordinates.
pub fn check_for_block(
#[inline]
pub fn check_for_block(&self, x: i32, y: i32, z: i32, whitelist: Option<&[Block]>) -> bool {
let absolute_y = self.get_absolute_y(x, y, z);
// Retrieve the chunk modification map
if let Some(existing_block) = self.world.get_block(x, absolute_y, z) {
if let Some(whitelist) = whitelist {
if whitelist
.iter()
.any(|whitelisted_block: &Block| whitelisted_block.id() == existing_block.id())
{
return true; // Block is in the list
}
}
}
false
}
/// Checks for a block at the given coordinates with absolute Y value.
#[allow(unused)]
pub fn check_for_block_absolute(
&self,
x: i32,
y: i32,
absolute_y: i32,
z: i32,
whitelist: Option<&[Block]>,
blacklist: Option<&[Block]>,
) -> bool {
// Retrieve the chunk modification map
if let Some(existing_block) = self.world.get_block(x, y, z) {
if let Some(existing_block) = self.world.get_block(x, absolute_y, z) {
// Check against whitelist and blacklist
if let Some(whitelist) = whitelist {
if whitelist
@@ -416,6 +549,7 @@ impl WorldEditor {
{
return true; // Block is in whitelist
}
return false;
}
if let Some(blacklist) = blacklist {
if blacklist
@@ -425,11 +559,19 @@ impl WorldEditor {
return true; // Block is in blacklist
}
}
return whitelist.is_none() && blacklist.is_none();
}
false
}
/// Checks if a block exists at the given coordinates with absolute Y value.
/// Unlike check_for_block_absolute, this doesn't filter by block type.
#[allow(unused)]
pub fn block_at_absolute(&self, x: i32, absolute_y: i32, z: i32) -> bool {
self.world.get_block(x, absolute_y, z).is_some()
}
/// 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();
@@ -666,6 +808,7 @@ impl WorldEditor {
}
// Helper function to get entity coordinates
#[inline]
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
@@ -685,6 +828,7 @@ fn get_entity_coords(entity: &HashMap<String, Value>) -> (i32, i32, i32) {
(x, y, z)
}
#[inline]
fn create_level_wrapper(chunk: &Chunk) -> HashMap<String, Value> {
HashMap::from([(
"Level".to_string(),

View File

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