diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index de92541..0f7d9ec 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -37,6 +37,9 @@ jobs: fail-fast: false matrix: include: + - minecraft: '1.20.1' + module: mod-1.20.1 + java: '21' - minecraft: '1.21.1' module: mod java: '21' @@ -76,6 +79,12 @@ jobs: run: | ./gradlew.bat --no-daemon build if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Test 1.20.1 saved worlds + if: matrix.minecraft == '1.20.1' + working-directory: mod-1.20.1 + run: | + ./gradlew.bat --no-daemon runGameTest + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Test 1.21.1 gameplay logic if: matrix.minecraft == '1.21.1' working-directory: mod diff --git a/.gitignore b/.gitignore index 7246eb7..2101129 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,9 @@ mod-26.3/run/ mod-26.3/run-render-check/ mod/run-map-check-*/ mod/run-walking-check/ + +# Fabric 1.20.1 backport: source is tracked, local builds and test worlds are not. +mod-1.20.1/build/ +mod-1.20.1/.gradle/ +mod-1.20.1/run/ +mod-1.20.1/run-*/ diff --git a/CHANGELOG.md b/CHANGELOG.md index cc90019..81c975a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 1.0.4 - 2026-10-27 + +- Add a Fabric 1.20.1 build and clean base pack, with Java 17 checks. +- Replace rocket/flight redirects that conflict with older MixinExtras annotation handling. +- Prepare adjacent terrain by geographic coordinates and guard against crossing into unrelated saved regions. +- Bound background voxel workers and recover queued work after worker crashes. +- Add native render settings, Polish strings and a read-only release checker. Updates still require closing Minecraft and replacing the matching JAR. +- Clarify JAR and modpack installation. RealWorldMC is not a datapack. + +Live provider transitions, fresh graphical setup and cross-platform gameplay still need release validation. See [the test record](docs/release-1.0.4.md). + ## 1.0.3 (2026-10-18) - Integrate itzSelestia's Xaero minimap/world-map contribution, preserving the original commits; improve geographic overlays, caching and dimension isolation. diff --git a/HANDOFF.md b/HANDOFF.md index f8e491a..ac7042b 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1,3 +1,13 @@ +# Current handoff: 1.0.4 local candidate + +Work is on `release/1.0.4` in `D:\RealWorldMC`. No remote push, merge, tag or publication was performed for this candidate. Four targets are tracked: 1.20.1, recommended 1.21.1, experimental 26.2 and 26.3. The website is separate and unchanged. + +Start with [validation and remaining work](docs/release-1.0.4.md), [1.20.1 port handoff](docs/port-1.20.1-handoff.md), [release instructions](docs/releases.md) and [draft release notes](docs/releases/v1.0.4.md). PR #9 and #10 commits were imported locally with follow-up safety fixes; do not merge their original heads and assume those fixes are included. + +The following sections are historical architecture notes. Older version labels describe their original snapshot. + +--- + # RealWorldMC handoff ## 1.0.2 preparation, 15 October 2026 diff --git a/build-pack.ps1 b/build-pack.ps1 index bfe43f2..6164595 100644 --- a/build-pack.ps1 +++ b/build-pack.ps1 @@ -1,4 +1,4 @@ -param([ValidateSet('1.21.1','26.2','26.3')][string]$MinecraftVersion = '1.21.1', [string]$ServiceDirectory = '', [string]$OutputDirectory = $PSScriptRoot, [switch]$VisualPack) +param([ValidateSet('1.20.1','1.21.1','26.2','26.3')][string]$MinecraftVersion = '1.21.1', [string]$ServiceDirectory = '', [string]$OutputDirectory = $PSScriptRoot, [switch]$VisualPack) $ErrorActionPreference = 'Stop' $jarName = if ($MinecraftVersion -ne '1.21.1') { "realworldmc-mc$MinecraftVersion-1.0.0.jar" } else { 'realworldmc-1.0.0.jar' } $jar = Join-Path $PSScriptRoot $jarName diff --git a/build-release.ps1 b/build-release.ps1 index 127eb12..ac20e1f 100644 --- a/build-release.ps1 +++ b/build-release.ps1 @@ -1,4 +1,4 @@ -param([ValidateSet('1.21.1','26.2','26.3')][string]$MinecraftVersion = '1.21.1', [string]$OutputDirectory = (Join-Path $PSScriptRoot 'release-output')) +param([ValidateSet('1.20.1','1.21.1','26.2','26.3')][string]$MinecraftVersion = '1.21.1', [string]$OutputDirectory = (Join-Path $PSScriptRoot 'release-output')) $ErrorActionPreference = 'Stop' $module = if ($MinecraftVersion -ne '1.21.1') { "mod-$MinecraftVersion" } else { 'mod' } $versionLine = Get-Content (Join-Path $PSScriptRoot "$module/gradle.properties") | Where-Object { $_ -match '^version=' } diff --git a/docs/controls.md b/docs/controls.md index 9f44078..2a3622d 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -2,7 +2,7 @@ [Back to README](../README.md) -These instructions are for **1.21.1**. On 26.2, Street View opens the browser companion; native photo gameplay is not included. +These instructions cover the native **1.20.1 and 1.21.1** builds. On 26.2 and 26.3, Street View opens the browser companion; native photo gameplay is not included. ## Travel @@ -17,9 +17,9 @@ These instructions are for **1.21.1**. On 26.2, Street View opens the browser co `/earth setlocation 44.427454 26.087287` changes the start for **new worlds** and requires command permission. Existing worlds keep their own origin. -## Glide and fly +## Flight -`/earth fly` toggles equipment-free flight. Steve automatically glides while moving quickly and stands upright when hovering or moving straight up/down. `/earth glide` enables the same mode. Add `on` or `off` to either command; `/rw` works too. These modes require Creative singleplayer. +`/earth fly` toggles equipment-free flight. Steve automatically glides while moving quickly and stands upright when hovering or moving straight up/down. Add `on` or `off` to set it explicitly; `/rw` works too. These modes require Creative singleplayer. W/S move forward/back, A/D strafe, arrow up/down changes speed, and Space/Shift rises/descends. Release movement keys to slow to a hover. Fireworks provide an optional boost. See [the flight guide](flight.md) for speeds, camera behaviour and globe transitions. @@ -50,7 +50,7 @@ Your rebound camera toggle also works. Entering or leaving Street View preserves `/earth help` shows the main commands. Click a yellow command to fill chat, then enter its arguments. `/earth help more` shows extra options. -Messages use a green **RW**, a dark gray separator and white text. Commands are pale yellow. `/earth goto` uses a green boss bar with three stages; these are not download percentages. In the prepared 1.0.1 build, photo loading and short control hints appear in stacked lines above the bottom-left map credits. The larger white arrows turn yellow when selected. Loading updates do not fill chat. +Messages use a green **RW**, a dark gray separator and white text. Commands are pale yellow. `/earth goto` uses a green boss bar with three stages; these are not download percentages. Photo loading and short control hints appear in stacked lines above the bottom-left map credits. The larger white arrows turn yellow when selected. Loading updates do not fill chat. `/earth hud` toggles this corner information. Add `on` or `off` to set it explicitly. The setting persists; normal chat, loading boss bars, navigation arrows and other mods' messages are unaffected. Opening chat hides the controls so they do not overlap it. @@ -58,12 +58,18 @@ Street View uses fixed daylight and softly shaded blocks. Lighting in a 360-degr ## Experimental space filming -The local experimental 1.21.1 build also has [Earth-to-space filming controls](space-flight.md). They are not in the published v1.0.0 download. +The native builds include [experimental Earth-to-space filming controls](space-flight.md). In Creative singleplayer, fly above 2 km over your region's ground reference to enter automatically. Space/Shift change altitude; W/S cruise and A/D strafe. Descend below 1.6 km to resume local flight. `/earth space` starts ascent earlier; `/earth space return` goes back to the entry point. The threshold uses the region's saved ground height, not a live terrain measurement under the player. -The prepared 1.0.1 build also accepts `/rw moon`, `/rw mars` and `/rw earth` for orbital flyovers and return to Earth orbit. The `/earth` prefix works too. Above 100 km, aim at a destination marker and hold W for 2.5 seconds to travel. Release W or look away to cancel. See [space flight](space-flight.md) for imagery limits and [planetary data](planetary-data.md) for sources. +The native builds also accept `/rw moon`, `/rw mars` and `/rw earth` for orbital flyovers and return to Earth orbit. The `/earth` prefix works too. Above 100 km, aim at a destination marker and hold W for 2.5 seconds to travel. Release W or look away to cancel. See [space flight](space-flight.md) for imagery limits and [planetary data](planetary-data.md) for sources. ## New-world starting place New Real World worlds choose from [100 places](spawn-locations.md). Operator commands `/earth setlocation random` and `/earth setlocation ` control future worlds only. Saved worlds never move. + +## Detail and updates + +`/earth settings` opens map detail controls on the native builds. Changes apply to new tile requests; they do not edit provider keys. Higher settings use more memory and requests. + +`/earth update` checks the latest GitHub release and opens its notes. It does not replace files while Minecraft is running. Back up worlds, close Minecraft, then replace the old JAR with the matching Minecraft version. `/rw` is an alias for both commands. diff --git a/docs/plan-1.0.4.md b/docs/plan-1.0.4.md new file mode 100644 index 0000000..5e2081a --- /dev/null +++ b/docs/plan-1.0.4.md @@ -0,0 +1,82 @@ +# RealWorldMC 1.0.4 implementation plan + +Updated 27 October 2026. Implemented locally on `release/1.0.4`; no remote PR merged, push, tag or release. See [validation and manual gates](release-1.0.4.md). The sections below retain the original audit and acceptance criteria. + +## Baseline + +Latest release: [v1.0.3](https://github.com/Teddy563/realworldmc/releases/tag/v1.0.3), published 18 October. Local tracked HEAD and origin/main both point to `6f18d1f` (release rerun fix, PR #8). The current checkout is `port/1.20.1`; the new port was untracked before this audit. + +Release targets: Fabric 1.20.1 (new, required), 1.21.1 (recommended), 26.2 and 26.3 (experimental). Native feature changes must not be advertised as experimental-target feature parity. + +## Order of work + +### 1. Preserve and integrate the 1.20.1 port + +Follow [the port handoff](port-1.20.1-handoff.md). First commit the source snapshot and build exclusions separately, preserving its known static generator Codec fix. Add deterministic packaging of the current service, clean base pack, CI and clean-launch/save-reopen checks. Retain Heroes as an optional pack, not a mandatory dependency of RealWorldMC. + +### 2. Fix launch crash #12 before feature work + +[Issue #12](https://github.com/Teddy563/realworldmc/issues/12) reports a MixinExtras AnnotationNode ClassCastException transforming FireworkRocketItem with only RealWorldMC and Fabric API, Loader 0.17.2, Java 21.0.7. + +The published metadata permits Loader >=0.16.0, but development uses 0.19.5. This is a compatibility hypothesis, not a confirmed root cause. Reproduce with the published 1.0.3 JAR and the exact reported minimal stack. Compare the tested loader and the declared minimum; inspect the actual MixinExtras version and remapped rocket mixin annotations. Fix the injection or dependency declaration based on the result. Do not prescribe unrelated optimization mods as a workaround. + +Gate: minimal packaged-JAR launch reaches the menu and a world on every supported loader baseline; normal rockets and equipment-free boosts still work. Include Java 17 / 1.20.1 in the launch matrix. If raising the minimum loader is required, tell users plainly in metadata, setup and release notes. + +### 3. Resolve region crossing #7; revise PR #9 + +[Issue #7](https://github.com/Teddy563/realworldmc/issues/7) describes NYC changing to Croatia across a barrier. Current EarthRegions.indexAt rounds positions into cells spaced 50,000 blocks apart, so crossing a midpoint can select a different saved geographic origin. The issue has a linked user video; review that repro during implementation (not watched in this audit). + +[PR #9](https://github.com/Teddy563/realworldmc/pull/9), reviewed at `313e9920`, has green CI. Its 22,000-block radius only creates a gap: the next center becomes valid again at 28,000 blocks along the same axis. It does not guarantee geographic continuity and may expose empty terrain in the gap. Do not close #7 on the radius change alone. + +Implement explicit ownership of the active geographic region. Before its safe limit, prepare a geographically adjacent origin and translate position, velocity and camera heading together. Retain current coverage until the new frame is ready. If preparation fails, retain the current view and provide a bounded stop/retry path; never infer a destination from an unrelated occupied grid cell. Saved worlds and existing edits must retain their geographic association. + +Gate: populated adjacent NYC/Croatia cells, both directions, diagonals, negative boundaries, high-speed flight, orbit return, failed provider request and world reload. Confirm coordinates and scenery agree before/after each transition. Apply to 1.20.1, 1.21.1 and experimental targets, including renderer and collision callers. + +### 4. Harden the worker-pool part of PR #9 separately + +Useful direction: keep CPU voxelization off the HTTP event loop. Static review found: + +- A replacement worker is pushed into freeWorkers by _spawnWorker and may immediately receive a queued task through _processNext without being removed from that free list. A new request can then assign a second task to the same worker and overwrite activeId. +- The pending queue is unbounded; explicit worker counts are not bounded integers. Add a conservative cap and backpressure. +- Guard worker retirement against duplicate error/exit handling, failed respawns and postMessage serialization errors. Every accepted task must resolve or reject; close must reject new work. +- Mesh inputs are structured-cloned; only output buffers are transferred. Measure memory and CPU before calling the entire operation zero-copy. +- Existing tests check output shape, not equivalence to synchronous results under real coordinates or worker failure. + +Gate: byte-for-byte sync/worker parity, queue saturation, crash with queued work, failed spawn, duplicate exit, shutdown, invalid counts and a responsiveness/memory benchmark. Preserve the contributor commit and add focused fixes, or split the PR with the contributor before merge. Do not bundle incomplete boundary behavior with an otherwise useful worker optimization. + +### 5. Rebase and narrow PR #10 after #9 + +[PR #10](https://github.com/Teddy563/realworldmc/pull/10), reviewed at `b5045b40`, includes PR #9's exact commit plus updater, Polish translations and rendering settings. CI is green, but it does not test safe update installation. Rebase after #9 so its changes are not integrated twice. + +Keep: version notice, changelog UI, translations and a bounded quality-settings screen, after these changes: + +- Match the exact Minecraft/loader release asset. Never fall back to the first JAR if the right version is missing. +- Current updater writes a new versioned JAR beside the old one, leaving duplicate mod IDs on restart. For 1.0.4, prefer a Releases/download-folder workflow with clear replacement steps. Defer in-place installation until it has verified staging, backup, restart-time replacement and rollback tests; never overwrite a loaded JAR. +- Validate downloaded filename/path, size, release checksum and mod metadata. Handle interrupted downloads and GitHub rate limits without freezing startup. +- Use Fabric's version parser or another existing semver implementation. Current digit-stripping can misread +mc1.20.1 build metadata and prereleases. +- Marshal progress/UI mutations onto the client thread; handle closed/resized screens. Translate hardcoded English/Polish status text too. +- Bound fineRadius/far/maxTiles/maxSse on both client and service. Apply quality settings before orbital policy so local distance overrides do not overwrite orbit distances. Save atomically through existing config conventions and preserve credentials; report save errors instead of silently ignoring them. + +Gate: exact assets for all four targets, no matching asset, offline/403/429, interrupted download, duplicate-mod prevention, prerelease/build metadata comparisons, UI scaling, language fallback and orbital settings. + +### 6. Address installation question #11 + +[Issue #11](https://github.com/Teddy563/realworldmc/issues/11) is a setup/documentation issue: RealWorldMC is a Fabric mod, not a datapack. Explain matching Minecraft + Fabric + Fabric API, placing the JAR in mods, and importing .mrpack through a compatible launcher. Do not claim an untested launcher is supported. Prepare a reply for owner review; no comment was posted in this audit. + +## Merge and release gates + +1. Source-tracked 1.20.1 port with packaging/tests. +2. Minimal-launch fix #12. +3. Revised region fix and hardened worker pool from #9; keep independent commits. +4. Rebased safe subset of #10, with direct in-place updater deferred unless fully validated. +5. Docs/#11, four-target CI, release notes and clean pack import. + +Keep contributor attribution. New maintainer commits use Teddy563 , no automated co-author trailers. Do not force-push contributor branches or merge solely because CI is green. + +Version all mod targets and service to 1.0.4. Generate each JAR/ZIP/mrpack from the same commit and service source; check metadata, archive contents and checksums. Test no-Node Windows startup and documented macOS/Linux Node discovery. Ensure no provider credentials, personal worlds, cached tiles, patched private add-ons or build outputs enter source/releases. + +Only tag v1.0.4 after all four build/import/launch gates pass. Keep 1.21.1 recommended; describe 1.20.1 as newly supported with its tested feature list. Publish GitHub first and verify website asset selection for four targets; update Modrinth separately with the matching files and versions. + +## Evidence and limits + +Read open issues and comments, full PR file diffs, PR commit lists and CI statuses through GitHub API. Both PRs passed six existing checks (three builds plus three Node OS checks). Read the local port source/build metadata and prior handoff; inspected the existing Java 17 JAR. No new gameplay tests or provider requests were performed, and no PRs/comments/releases were changed. The root HANDOFF.md is historical and still contains obsolete 1.0.1/1.0.2 status; update its current-status section during implementation. diff --git a/docs/port-1.20.1-handoff.md b/docs/port-1.20.1-handoff.md new file mode 100644 index 0000000..8dfeb49 --- /dev/null +++ b/docs/port-1.20.1-handoff.md @@ -0,0 +1,46 @@ +# Fabric 1.20.1 backport handoff + +Reviewed 27 October 2026. Required release target for 1.0.4; not published yet. + +## Integration status + +The port is tracked on `release/1.0.4` with its own clean base pack. The previous personal manifest is preserved as `modpack/heroes-1.20.1.index.json`; it is not the default download. Builds use version 1.0.4 and release filenames `RealWorldMC-1.0.4-mc1.20.1.*`. + +Shared checks and two Minecraft GameTests pass on Java 17, including generator Codec and saved-region round trips. This tests serialization, not a full graphical save/quit/reopen session. Region travel, safe release notices and render settings are backported. The current service is bundled during packaging. See [validation](release-1.0.4.md) for remaining live checks. + +## Original source and evidence + +- Source: `mod-1.20.1/`, copied/backported from the 1.0.3 native implementation. +- Pack manifest: `modpack/1.20.1.index.json`, currently named RealWorldMC Heroes. +- Current local branch: `port/1.20.1`; tracked HEAD matches main at `6f18d1f`. +- Prior handoff: local Claude project memory `D--ModrinthApp-profiles-Fabulously-Optimized/memory/realworldmc-vulkanmod.md`, updated 24 October. +- That handoff records successful user testing of the imported Heroes profile. This is historical evidence, not a new clean-install certification. +- Local build artifact is `realworldmc-1.0.3+mc1.20.1.jar`, Java class version 61 (Java 17). It does not contain a bundled service ZIP. The handoff describes a separately repackaged JAR using the 1.0.3 service bundle. + +## Backport changes to retain + +- Java 17 source/bytecode and mixin compatibility; Minecraft 1.20.1, Fabric API 0.92.12+1.20.1 and build Loader 0.19.5. +- Older networking, registry, saved-data, world-generation, GUI, rendering and mixin APIs adapted from the native target. +- A single static EarthChunkGenerator CODEC returned by codec(). The prior fresh-instance implementation reportedly lost the saved generator in level.dat. Add a save/reopen regression before release. +- 1.20.1 resource paths use loot_tables and tags/blocks instead of the newer singular names; verify drops and mineable tags rather than blindly copying 1.21.1 resources. +- Optional Xaero integration targets Minimap 26.6.0 and World Map 1.47.0 for 1.20.1. +- Native Street View, flight, setup and map source is present. Presence is not proof that every feature works on 1.20.1. + +## Personal pack notes, not public defaults + +The Heroes profile was created for Viltrumite and Orbital Railgun Renewed. The earlier VulkanMod experiment was reverted. Indium was needed with that profile's Sodium 0.5 / Distant Horizons combination. + +The handoff mentions both removing SkinShuffle due to ETF conflicts and later testing a locally patched SkinShuffle. Confirm the final profile state; do not publish that patched third-party JAR without checking its distribution terms. A copied 1.21.1 Visuality config crashed Visuality 0.7.1 and was reset. Mocap was disabled. Keep these personal profile changes separate from the base mod release. + +Do not copy provider keys, account files, worlds or personal options into any release. Test the first-run masked setup with empty credentials. The prior successful world test used the user's configured keys, so it does not validate the fresh-user flow. + +## Required for 1.0.4 + +1. Track source, wrapper and manifest; exclude build/.gradle/run directories. +2. Integrate the same 1.0.4 service bundle at build time; do not borrow an old release ZIP. +3. Add 1.20.1 to build-release.ps1, build-pack.ps1, install.ps1, test-pack.ps1 and CI. Normalize project version to 1.0.4 and choose the artifact name explicitly; the current +mc1.20.1 version is rejected by the release script's version check. +4. Add packaged-service, clean import, startup and world save/reopen tests. This module currently has no checks/gametest/clientcheck source sets. +5. Apply the 1.0.4 crash and region fixes to this target too. Build on a JDK supported by Loom/Gradle, compile with release 17, and launch-test on Java 17. +6. Publish a standalone Fabric JAR plus a clean base pack. Keep the Heroes pack a separate optional variant after dependency and licensing review. + +Maintain this file alongside port changes. No 1.20.1 release has been created by this audit. diff --git a/docs/release-1.0.4.md b/docs/release-1.0.4.md new file mode 100644 index 0000000..f511032 --- /dev/null +++ b/docs/release-1.0.4.md @@ -0,0 +1,49 @@ +# 1.0.4 local validation and handoff + +Date: 27 October 2026. Branch: `release/1.0.4`. Baseline: `6f18d1f` (v1.0.3 main). Local candidate only: no push, remote merge, tag or publication. Personal Minecraft profiles and credentials were not changed. + +## What changed + +| Area | Implemented | Still verify before publishing | +|---|---|---| +| Fabric 1.20.1 | Tracked backport, Java 17 bytecode, clean Fabric API base pack, current bundled services, fourth CI target | Fresh graphical setup, live map and Street View, save/quit/reopen on Java 17 | +| Startup crash #12 | Replace flight/rocket Redirect annotations with WrapOperation; retain normal rocket behavior | Exact reporter API 0.116.13 and published packaged-JAR launch; test with their add-ons | +| Region crossing #7 | Start adjacent geographic terrain preparation at 18 km; bound normal horizontal movement at 21 km; async arrival chunks; transform position, heading and velocity; retain native renderer tiles | Fly both ways through a saved NYC/Croatia grid boundary, diagonal/high-speed flight, turn back during loading, disconnect provider, retry, save/reopen and orbit return | +| Worker pool / PR #9 | Bounded queue, two workers by default, explicit limits, synchronous fallback, crash recovery and shutdown | Real long-flight memory/FPS comparison; no performance gain is claimed from synthetic checks | +| Settings / PR #10 | Native `/earth settings`, bounded request overrides, atomic local saves, no provider-config rewrite | Small GUI scales, slider/preset behavior, persistence and live detail changes | +| Update notice / PR #10 | Native `/earth update`, exact target asset matching, bounded network reads and response size, release notes and browser link | Offline/rate-limited UI, long notes, Polish text and small windows | +| Installation issue #11 | JAR vs mrpack vs datapack instructions | Fresh-user follow-through; no issue reply posted | +| Experimental 26.2 / 26.3 | Compile/check/package the shared service and boundary fixes | Real GPU launch, rendering and provider travel on both targets; native settings/photo UI parity is not claimed | + +## Automated evidence + +All commands ran locally on Windows. Build logs and candidate artifacts are ignored under `release-output/`. + +- All four targets: Gradle `build` passed after the implementation changes. +- All four standalone JARs: extraction, checksum, upgrade/reuse, credential preservation and real bundled-service lifecycle checks passed with an empty PATH. +- All four `.mrpack` files: clean temporary import, both services, private-key isolation and automatic shutdown passed with no provider requests or installed Node dependency. +- Service: **45/45 tests passed**, including worker crashes, queue limits, byte parity and render override validation (`release-output/service104.log`). +- 1.21.1: **11 Minecraft GameTests passed**, also tested on Loader 0.17.2. Tested Fabric API is 0.116.17, not the exact reporter's 0.116.13. +- 1.21.1 photo/camera rendering checks passed on Loader 0.17.2 / MixinExtras 0.5.0: camera separation, panorama pixels, textured excavation/TNT, map-wall holes, clipping/render-state restoration and orbital imagery (vanilla pipeline). Receipt: `mod/run-photo-check/photo-check-result.txt`; log: `release-output/photo104-loader0172.log`. +- 1.21.1 isolated graphical flight test passed: forward/back/strafe, throttle, hover/up/down, first/rear/front views, real rockets and expiry, block collisions, anchored orbit/return and survival cleanup. Receipt: `mod/run-flight-check/creative-flight-result.txt`. +- 1.20.1: shared checks passed on **Java 17**, plus **2 Minecraft GameTests** for generator Codec round-trip and saved-region identity/movement ownership. A serialization round-trip does not replace a graphical world reopen test. +- Shared boundary checks cover **245** radial/negative/diagonal/high-speed movements, turning back and nonfinite input. Release metadata checks cover exact assets across all four targets and version ordering. +- `git diff --check` passed. No coverage-percentage instrumentation was run; these are scenario-based checks, not a claimed line-coverage percentage. + +Final per-target logs: `release-output/final-VERSION.log`, `standalone-VERSION.log`, `packcheck-VERSION.log`. Downloads: `release-output/v1.0.4-final/VERSION/`. + +## Manual test order + +1. Back up a world and use a separate Fabric profile. Install exactly one matching RealWorldMC JAR plus Fabric API, or import the clean mrpack. Do not overwrite a working personal profile to test this candidate. +2. On 1.20.1/Java 17, test first-run masked setup, map loading, Street View, placing/mining blocks, F5 and save/quit/reopen. Repeat the short flow on recommended 1.21.1. +3. Run `/earth fly on`. Check W/S and A/D direction, Space/Shift, hover and rocket boost. Check your camera/add-on mods separately. +4. For the region regression, use a copy of a world containing the previously unrelated adjacent saved locations. Fly beyond 18 km from the current region center. Confirm `/earth where`, scenery, heading and motion agree through preparation. Repeat at high speed, diagonally and on the return trip. Interrupt provider access: loading must end or retry without jumping to an unrelated location. World edits must remain at their original geographic places. +5. Open `/earth settings` and `/earth update` at normal and large GUI scales. Confirm settings persist; keys stay intact; update opens the browser but never replaces the installed mod. Test without internet too. +6. Launch experimental 26.2/26.3 in separate test worlds. Check map loading and region transition. These targets still use the browser Street View companion. +7. After a future push, require Windows/macOS/Linux CI to pass. This Windows session does not certify macOS or Linux gameplay. Add 1.20.1 to the separate website selector if needed; its code was not changed here. + +## PR and release decision + +PR #9 and #10 contributor commits are preserved locally. Follow-up changes fix their queue lifecycle, region ownership and unsafe running-JAR replacement. Merge the reviewed combined branch rather than assuming the original PR heads contain those fixes. Do not close #7 based only on the numerical boundary tests. Keep #12 open until the reporter/minimal packaged launch is confirmed. + +Draft notes: [v1.0.4](releases/v1.0.4.md). New maintainer commits use Teddy563 , without co-author trailers. Imported contributor authors remain credited. No release tag exists for this candidate yet. diff --git a/docs/releases.md b/docs/releases.md index 4458396..da46bf1 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -1,6 +1,6 @@ # Build and publish -The `release.yml` GitHub workflow builds all three targets, checks the code and +The `release.yml` GitHub workflow builds all four targets, checks the code and packages standalone Windows x64 JARs, importable .mrpacks and optional ZIPs. Minecraft 26.2 and 26.3 remain experimental even when included in a normal RealWorldMC release. @@ -8,7 +8,7 @@ normal RealWorldMC release. | GitHub event | Result | |---|---| -| Push to `main` or a pull request into `main` | Build and test all three targets, then upload downloadable Actions artifacts. Nothing is published. | +| Push to `main` or a pull request into `main` | Build and test all four targets, then upload downloadable Actions artifacts. Nothing is published. | | Manual Run workflow | The same build and package checks, without publishing. | | Push a matching `v*` tag | Build and test, then publish JARs, modpacks, ZIPs and SHA-256 checksums together. | @@ -20,7 +20,7 @@ Review the [manual checklist](../RELEASE-CHECKLIST.md). Commit source and the sm The workflow is local until committed and pushed. Pushing `main` verifies the build first. A later version tag is the step that publishes the release, so do not tag until the in-game checks are complete. -1. Update `version` in all three Gradle projects, the changelog and service package version. +1. Update `version` in all four Gradle projects, the changelog and service package version. 2. Put the approved notes in `docs/releases/.md`, for example `docs/releases/v1.0.2.md`, then commit the tested source, including `.github/workflows/release.yml`. 3. Push a matching tag, for example `v1.0.2`. Tags with a suffix such as `v1.0.1-rc.1` publish a prerelease. 4. Wait for all builds. The workflow uploads all files to a draft with the approved notes, then publishes it. If no notes file exists, it generates notes from Git history. @@ -28,21 +28,17 @@ The workflow is local until committed and pushed. Pushing `main` verifies the bu Do not reuse an existing release tag; fix and release a new version. -Standalone downloads are named `RealWorldMC-VERSION-mc1.21.1.jar` and `RealWorldMC-VERSION-mc26.2.jar`. These include a checksum-verified service archive and private runtime; older thin JAR filenames are intentionally not selected by the site. +Downloads use `RealWorldMC-VERSION-mcMINECRAFT.jar`, `.mrpack` and `.zip`, with Minecraft targets `1.20.1`, `1.21.1`, `26.2` and `26.3`. Standalone JARs contain a checksum-verified service archive and a Windows x64 runtime. Thin development JARs are not release downloads. -Importable downloads are named `RealWorldMC-VERSION-mc1.21.1.mrpack` and -`RealWorldMC-VERSION-mc26.2.mrpack`. The site matches these names through GitHub's -public Releases API. No website token is needed. It excludes prereleases from -the recommended 1.21.1 option, permits them for 26.2, and caches results for five -minutes. Missing files or API limits show a releases-page fallback, never a guessed URL. +The website reads public GitHub releases. Its version selector is maintained in the separate site repository; adding a build here does not automatically add a new selector there. Verify 1.20.1 is discoverable before announcing it. GitHub Releases lists all four targets directly. For a local package, build the appropriate Gradle project, then run -`./build-release.ps1 -MinecraftVersion 1.21.1` (or `26.2` / `26.3`). The package uses an +`./build-release.ps1 -MinecraftVersion 1.21.1` (or `1.20.1` / `26.2` / `26.3`). The package uses an allowlist and includes LICENSE, NOTICE and LICENSES. It excludes local credentials, logs, caches and worlds. Build-time `npm ci --omit=dev --ignore-scripts` installs locked dependencies into a fresh staging folder. `prepare-service.ps1` downloads a pinned, SHA-256-verified Windows x64 Node runtime, including its licence. Dependencies and runtime enter the pack and standalone JAR; user keys do not. `bundle-jar.ps1` creates the embedded archive without changing the developer JAR. The runtime extracts versioned code away from personal configuration files. Inspect `release-output/` before sharing. Run `./test-pack.ps1 -Pack ` before publishing. CI does this automatically: clean extraction, empty PATH, both localhost services, key isolation and parent-exit cleanup. No provider keys are needed for CI. The legacy installer is only an optional shortcut to open the existing pack. -Also run `./mod/gradlew.bat -p mod standaloneJarChecks -PreleaseJar=`. CI runs the matching module task for all three targets. It checks safe extraction, upgrades, key preservation and real service startup/restart with an empty PATH. +Also run `./mod/gradlew.bat -p mod standaloneJarChecks -PreleaseJar=`. CI runs the matching module task for all four targets. It checks safe extraction, upgrades, key preservation and real service startup/restart with an empty PATH. Build success checks code and packaging, not every graphics driver or live provider. Run a manual Minecraft smoke test before tagging: setup, provider test, flight, @@ -60,6 +56,10 @@ Workflow behavior follows [GitHub's event triggers](https://docs.github.com/en/a ## 1.0.2 checks -The workflow also runs the shared Node detection checks on Windows, macOS and Linux. Publishing requires these checks and all three build/package jobs to pass. The 26.3 artifacts use `RealWorldMC-VERSION-mc26.3` as their filename prefix. The website may still show 26.2 as its experimental shortcut; the GitHub release lists both targets. +The workflow also runs the shared Node detection checks on Windows, macOS and Linux. Publishing requires these checks and all four build/package jobs to pass. The 26.3 artifacts use `RealWorldMC-VERSION-mc26.3` as their filename prefix. The website may still show 26.2 as its experimental shortcut; the GitHub release lists both targets. `mod-26.3` shares modern source/resources with `mod-26.2`, except the terrain generator and two GPU classes whose APIs changed in 26.3. Build both whenever changing that shared code. See [26.3 details](experimental-26.3.md). + +## Current candidate + +See [1.0.4 validation and remaining checks](release-1.0.4.md). Build 1.20.1 with JDK 21, targeting Java 17. Its checks can run on Java 17 with `-PchecksJava=`; CI builds on 21. Local checks do not substitute for macOS/Linux CI or real provider gameplay. diff --git a/docs/releases/v1.0.4.md b/docs/releases/v1.0.4.md new file mode 100644 index 0000000..aa247bf --- /dev/null +++ b/docs/releases/v1.0.4.md @@ -0,0 +1,16 @@ +# RealWorldMC 1.0.4 + +- New Fabric 1.20.1 download and base pack for Java 17. 1.21.1 remains recommended; 26.2 and 26.3 remain experimental. +- Fix a rocket/flight mixin conflict that could stop Minecraft from launching. +- Prepare neighboring terrain by geographic position and prevent movement into unrelated saved locations. +- Improve background tile processing, queue limits and worker recovery. +- Add render settings and release notes inside the native builds with `/earth settings` and `/earth update`. +- Add Polish interface strings and clearer installation instructions. + +Choose the JAR or modpack matching your Minecraft version. Back up worlds and close Minecraft before replacing the old mod. Updates do not replace files automatically. + +[Setup and downloads](https://realworldmc.com/) · [Installation guide](https://github.com/Teddy563/realworldmc/blob/main/docs/setup.md) + +Thanks to @deloskiytbackup for the contributions in #9 and #10, integrated with additional boundary, worker-recovery and update-safety fixes. + +Known limits: geographic transitions still need wider live-provider testing. The 1.20.1 backport is new; back up worlds before trying it. Full macOS/Linux gameplay and add-on compatibility are not yet verified. [Test record](https://github.com/Teddy563/realworldmc/blob/main/docs/release-1.0.4.md). diff --git a/docs/setup.md b/docs/setup.md index c4dabb6..2db8c93 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -52,3 +52,17 @@ Linux, macOS and Windows ARM do not have a bundled runtime. Install Node.js 22+. For the optional browser companion on 1.21.1, add a restricted Maps JavaScript API `browserKey` in `realworldmc-service/streetview.config.json`, keeping it separate from the native `tilesKey`. Restart Minecraft after manual file edits. The first-run screen configures the native key, not browser access. For Propwash FPV and the 26.3 target, see [experimental 26.3](experimental-26.3.md). + + +## Installing a JAR instead of a pack + +RealWorldMC is a Fabric mod, not a datapack. Do not put it in a world's `datapacks` folder. + +1. Create a Fabric profile for the exact Minecraft version on the download. +2. Install Fabric API for that same version. +3. Put the RealWorldMC JAR in that profile's `mods` folder. Remove older RealWorldMC JARs first. +4. Start that profile and complete the setup screen. + +For a `.mrpack`, use the import option in Modrinth App or Prism Launcher. Do not put the pack in `mods` or `datapacks`. + +The next release includes a Fabric 1.20.1 build targeting Java 17, alongside the recommended 1.21.1 build (Java 21). Use the matching download, never a JAR for another Minecraft version. The base 1.20.1 pack contains RealWorldMC and Fabric API; the optional personal Heroes pack is not required. diff --git a/install.ps1 b/install.ps1 index e8b9cab..37b77bb 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1,4 +1,4 @@ -param([ValidateSet('1.21.1','26.2','26.3')][string]$MinecraftVersion = '1.21.1', [switch]$NoOpen) +param([ValidateSet('1.20.1','1.21.1','26.2','26.3')][string]$MinecraftVersion = '1.21.1', [switch]$NoOpen) $ErrorActionPreference = 'Stop' $pack = Join-Path $PSScriptRoot "RealWorldMC-1.0.0-mc$MinecraftVersion.mrpack" if (-not (Test-Path -LiteralPath $pack)) { throw 'Download the ready-made .mrpack from Releases and import it into Modrinth or Prism.' } diff --git a/mod-1.20.1/build.gradle b/mod-1.20.1/build.gradle new file mode 100644 index 0000000..ab0b27b --- /dev/null +++ b/mod-1.20.1/build.gradle @@ -0,0 +1,119 @@ +plugins { + id 'fabric-loom' version "${loom_version}" +} + +base { + archivesName = "realworldmc-mc1.20.1" +} + +repositories { + maven { + url "https://chocolateminecraft.com/maven" + name "Xaero's Maven" + } +} + +loom { + splitEnvironmentSourceSets() + + mods { + "realworldmc" { + sourceSet sourceSets.main + sourceSet sourceSets.client + } + } +} + +dependencies { + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings loom.officialMojangMappings() + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_api_version}" + modCompileOnly "xaero.minimap:xaerominimap-fabric-1.20.1:26.6.0" + modCompileOnly "xaero.map:xaeroworldmap-fabric-1.20.1:1.47.0" +} + +processResources { + def version = project.version + inputs.property "version", version + + filesMatching("fabric.mod.json") { + expand "version": version + } +} + +tasks.withType(JavaCompile).configureEach { + it.options.release = 17 + it.options.encoding = "UTF-8" +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +tasks.named('jar') { + from('../LICENSE') + from('../NOTICE') + from('../LICENSES') { into 'LICENSES' } +} + +sourceSets { + main { java.srcDir '../shared/src/main/java' } +} + +// Run the existing service/setup checks against the backport classes too. +sourceSets { + checks { + java.srcDir '../shared/src/checks/java' + java.srcDir '../mod/src/checks/java' + java.include 'dev/realworldmc/ReleaseMetadataChecks.java', 'dev/realworldmc/RegionBoundaryChecks.java', 'dev/realworldmc/BundledServiceChecks.java', 'dev/realworldmc/SpawnLocationChecks.java', 'dev/realworldmc/NodeRuntimeChecks.java', 'dev/realworldmc/SetupChecks.java', 'dev/realworldmc/ServiceRuntimeChecks.java', 'dev/realworldmc/StreetNavigationChecks.java', 'dev/realworldmc/MeshCutChecks.java' + compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath + runtimeClasspath += sourceSets.main.output + sourceSets.main.runtimeClasspath + } +} +['BundledService', 'SpawnLocation', 'NodeRuntime', 'Setup', 'ServiceRuntime', 'StreetNavigation', 'MeshCut'].each { name -> + def taskName = name[0].toLowerCase() + name.substring(1) + 'Checks' + tasks.register(taskName, JavaExec) { + dependsOn tasks.named('checksClasses') + classpath = sourceSets.checks.runtimeClasspath + mainClass = "dev.realworldmc.${name}Checks" + } + tasks.named('check') { dependsOn tasks.named(taskName) } +} +tasks.register('standaloneJarChecks', JavaExec) { + dependsOn tasks.named('checksClasses') + doFirst { if (!project.hasProperty('releaseJar')) throw new GradleException('Pass -PreleaseJar=path/to/release.jar') } + classpath = files(project.findProperty('releaseJar') ?: 'missing.jar') + sourceSets.checks.runtimeClasspath + mainClass = 'dev.realworldmc.BundledServiceChecks' + args 'release' + environment 'PATH', '' +} + +tasks.register('regionBoundaryChecks', JavaExec) { + dependsOn tasks.named('checksClasses') + classpath = sourceSets.checks.runtimeClasspath + mainClass = 'dev.realworldmc.RegionBoundaryChecks' +} +tasks.named('check') { dependsOn tasks.named('regionBoundaryChecks') } + +tasks.register('releaseMetadataChecks', JavaExec) { + dependsOn tasks.named('checksClasses') + classpath = sourceSets.checks.runtimeClasspath + mainClass = 'dev.realworldmc.ReleaseMetadataChecks' +} +tasks.named('check') { dependsOn tasks.named('releaseMetadataChecks') } + +// Exercise Java 17 at runtime without requiring Gradle itself to run on Java 17. +tasks.withType(JavaExec).configureEach { + if (project.hasProperty('checksJava')) executable = project.property('checksJava') +} + +fabricApi { + configureTests { + createSourceSet = true + modId = 'realworldmc-gametest' + enableGameTests = true + enableClientGameTests = false + } +} diff --git a/mod-1.20.1/gradle.properties b/mod-1.20.1/gradle.properties new file mode 100644 index 0000000..30122c3 --- /dev/null +++ b/mod-1.20.1/gradle.properties @@ -0,0 +1,14 @@ +org.gradle.jvmargs=-Xmx3G +org.gradle.parallel=true + +# Fabric Properties +minecraft_version=1.20.1 +loader_version=0.19.5 +loom_version=1.17.21 + +# Mod Properties +version=1.0.4 +group=dev.realworldmc + +# Dependencies +fabric_api_version=0.92.12+1.20.1 diff --git a/mod-1.20.1/gradle/wrapper/gradle-wrapper.jar b/mod-1.20.1/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..eddabd2 Binary files /dev/null and b/mod-1.20.1/gradle/wrapper/gradle-wrapper.jar differ diff --git a/mod-1.20.1/gradle/wrapper/gradle-wrapper.properties b/mod-1.20.1/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ad7845b --- /dev/null +++ b/mod-1.20.1/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/mod-1.20.1/gradlew b/mod-1.20.1/gradlew new file mode 100644 index 0000000..249efbb --- /dev/null +++ b/mod-1.20.1/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/mod-1.20.1/gradlew.bat b/mod-1.20.1/gradlew.bat new file mode 100644 index 0000000..a51ec4f --- /dev/null +++ b/mod-1.20.1/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/mod-1.20.1/settings.gradle b/mod-1.20.1/settings.gradle new file mode 100644 index 0000000..5afd0ff --- /dev/null +++ b/mod-1.20.1/settings.gradle @@ -0,0 +1,13 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + mavenCentral() + gradlePluginPortal() + } +} + +// Should match your modid +rootProject.name = 'realworldmc' diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/ActionBar.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/ActionBar.java new file mode 100644 index 0000000..bf18931 --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/ActionBar.java @@ -0,0 +1,115 @@ +package dev.realworldmc.client; + +import dev.realworldmc.RWTheme; + +import dev.realworldmc.EarthConfig; +import dev.realworldmc.RWMessages; +import net.fabricmc.fabric.api.client.message.v1.ClientSendMessageEvents; +import net.minecraft.client.Minecraft; +import net.minecraft.network.chat.Component; +import net.minecraft.client.gui.GuiGraphics; +import java.util.ArrayList; +import java.util.List; + +public final class ActionBar { + private static Component status=Component.empty(); + private static long until; + private ActionBar() {} + public static boolean hidden(Component message) { + return !EarthConfig.get().actionBar && message.getString().startsWith("RW | "); + } + public static void show(Component message) { status=message; until=net.minecraft.Util.getMillis()+4000; } + public static boolean capture(Component message) { + if(!message.getString().startsWith("RW | "))return false; + if(!hidden(message))show(message); + return true; + } + public static void clear() { status=Component.empty();until=0; } + public static String key(net.minecraft.client.KeyMapping key) {return key.getTranslatedKeyMessage().getString();} + /** Bottom is the last text baseline immediately above the map credits. */ + public static void render(GuiGraphics graphics, int bottom, List controls) { + var mc=Minecraft.getInstance(); + if(!EarthConfig.get().actionBar || mc.options.hideGui || mc.screen!=null)return; + float scale=.8f; + int width=Math.min(230,(int)((graphics.guiWidth()-12)/scale)); + var lines=new ArrayList(); + if(until>net.minecraft.Util.getMillis()) { + String text=status.getString().replaceFirst("^RW \\| ",""); + if(text.startsWith("Street View ready"))text="Ready"; + var wrapped=mc.font.split(Component.literal(text),width-12); + lines.addAll(wrapped.subList(0,Math.min(2,wrapped.size()))); + } + int statusEnd=lines.size(); + for(String control:controls)lines.addAll(mc.font.split(Component.literal(control),width-12)); + int controlsEnd=lines.size(); + for(String usage:ApiUsageHud.lines())lines.addAll(mc.font.split(Component.literal(usage),width-12)); + int height=16+lines.size()*11; + graphics.pose().pushPose(); + graphics.pose().translate(5,Math.max(5,bottom-height*scale),0); + graphics.pose().scale(scale,scale,1); + graphics.fill(0,0,width,height,0xcc151715); + graphics.fill(0,0,width,14,RWTheme.SURFACE); + graphics.fill(0,0,2,height,RWTheme.BRAND); + graphics.drawString(mc.font,PanoramaRenderer.INSTANCE.active()?"Street View":"RealWorldMC",7,3,RWTheme.GREEN,false); + int y=17; + for(int i=0;i flightControls() { + var mc=Minecraft.getInstance();var controls=new ArrayList(); + if(CreativeFlight.enabled()) { + controls.add(CreativeFlight.status()); + controls.add(key(mc.options.keyUp)+" / "+key(mc.options.keyDown)+": forward / back · "+key(mc.options.keyLeft)+" / "+key(mc.options.keyRight)+": strafe"); + controls.add(key(PanoramaRenderer.INSTANCE.flightSpeedKey(true))+" / "+key(PanoramaRenderer.INSTANCE.flightSpeedKey(false))+": speed · "+key(mc.options.keyJump)+" / "+key(mc.options.keyShift)+": up / down"); + controls.add("/earth fly: off · Rockets: boost"); + } + if(SpaceFlight.enabled()) { + controls.add(String.format(java.util.Locale.ROOT,"%s orbit · %.1f km",SpaceFlight.body().title,SpaceFlight.altitude()/1000)); + if(!CreativeFlight.enabled()) { + controls.add(key(mc.options.keyUp)+" / "+key(mc.options.keyDown)+": cruise · "+key(mc.options.keyLeft)+" / "+key(mc.options.keyRight)+": strafe"); + controls.add(key(mc.options.keyJump)+" / "+key(mc.options.keyShift)+": up / down"); + } + controls.add("/earth space return: back"); + controls.add("/rw moon · /rw mars · /rw earth"); + } + if(EarthConfig.get().streetViewShortcut && mc.player!=null && mc.player.onGround())controls.add(StreetShortcut.hint()); + return controls; + } + public static void register() { + ClientSendMessageEvents.ALLOW_COMMAND.register(command -> { + String[] words = command.strip().split("\\s+"); + if(words.length>=2 && words.length<=3 && (words[0].equals("earth") || words[0].equals("rw"))) { + var cfg=EarthConfig.get();var mc=Minecraft.getInstance(); + if(words[1].equals("controls") && (words.length==2 || java.util.Set.of("on","off").contains(words[2]))) { + cfg.controlsHud=words.length==2?!cfg.controlsHud:words[2].equals("on");cfg.save();return false; + } + if(words[1].equals("walk") && (words.length==2 || java.util.Set.of("on","off").contains(words[2]))) { + if(PanoramaRenderer.INSTANCE.active())PanoramaRenderer.INSTANCE.requestWalking(words.length==2?!PanoramaRenderer.INSTANCE.walking():words[2].equals("on"));return false; + } + if(words[1].equals("camera") && words.length==3 && java.util.Set.of("first","back","front").contains(words[2])) { + mc.options.setCameraType(words[2].equals("first")?net.minecraft.client.CameraType.FIRST_PERSON:words[2].equals("back")?net.minecraft.client.CameraType.THIRD_PERSON_BACK:net.minecraft.client.CameraType.THIRD_PERSON_FRONT);return false; + } + } + if(words.length>=2 && words.length<=3 && (words[0].equals("earth") || words[0].equals("rw")) && words[1].equals("usage")) { + if(words.length==3 && !java.util.Set.of("on","off").contains(words[2]))return true; + var cfg=EarthConfig.get();cfg.usageHud=words.length==2?!cfg.usageHud:words[2].equals("on");cfg.save(); + var mc=Minecraft.getInstance();if(mc.player!=null)mc.player.displayClientMessage(RWMessages.message("Usage panel "+(cfg.usageHud?"on":"off")+"."),false);return false; + } + if(words.length>=2 && words.length<=3 && (words[0].equals("earth") || words[0].equals("rw")) && words[1].equals("streetkey")) { + if(words.length==3 && !java.util.Set.of("on","off").contains(words[2]))return true; + var cfg=EarthConfig.get();cfg.streetViewShortcut=words.length==2?!cfg.streetViewShortcut:words[2].equals("on");cfg.save(); + var mc=Minecraft.getInstance();if(mc.player!=null)mc.player.displayClientMessage(RWMessages.message("Street View shortcut "+(cfg.streetViewShortcut?"on":"off")+". /earth streetkey on|off"),false);return false; + } + if (words.length < 2 || words.length > 3 || !(words[0].equals("earth") || words[0].equals("rw")) || !words[1].equals("hud")) return true; + if (words.length == 3 && !java.util.Set.of("on", "off").contains(words[2])) return true; + var cfg = EarthConfig.get(); + cfg.actionBar = words.length == 2 ? !cfg.actionBar : words[2].equals("on"); + cfg.save(); + clear(); + var mc = Minecraft.getInstance(); + if (mc.player != null) mc.player.displayClientMessage(RWMessages.message("Corner information " + (cfg.actionBar ? "on." : "off. Use /earth hud on to restore it.")), false); + return false; + }); + net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents.DISCONNECT.register((handler,client)->clear()); + } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/ApiUsageHud.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/ApiUsageHud.java new file mode 100644 index 0000000..f084ab7 --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/ApiUsageHud.java @@ -0,0 +1,59 @@ +package dev.realworldmc.client; + +import com.google.gson.*; +import dev.realworldmc.EarthConfig; +import dev.realworldmc.ServiceClient; +import net.minecraft.client.Minecraft; +import java.net.URI; +import java.net.http.*; +import java.time.Duration; +import java.util.*; +import java.util.concurrent.CompletableFuture; + +/** A local request estimate, not access to the player's Google billing account. */ +public final class ApiUsageHud { + private static final HttpClient HTTP=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build(); + private static JsonObject street,terrain; + private static long next; + private static int generation; + private static boolean pending; + private ApiUsageHud() { } + public static void clear(){generation++;street=null;terrain=null;next=0;pending=false;} + private static JsonObject read(String base) { + try { + var response=HTTP.send(HttpRequest.newBuilder(URI.create(base+"/usage")).timeout(Duration.ofSeconds(2)).GET().build(),HttpResponse.BodyHandlers.ofString()); + if(response.statusCode()!=200 || response.body().length()>8192)return null; + JsonObject data=JsonParser.parseString(response.body()).getAsJsonObject(); + if(!data.has("available") || !data.get("available").getAsBoolean())return null; + for(String field:new String[]{"requests","tiles","roots","freeStreetTiles","free3dRoots"})if(!data.has(field) || data.get(field).getAsLong()<0)return null; + return data; + } catch(Exception e){return null;} + } + public static void tick(Minecraft mc) { + if(mc.level==null || !EarthConfig.get().actionBar || !EarthConfig.get().usageHud || pending || System.currentTimeMillis()new JsonObject[]{read(ServiceClient.photoBase()),read(ServiceClient.base())}) + .thenAccept(result->mc.execute(()->{if(token!=generation)return;street=result[0];terrain=result[1];pending=false;})); + } + private static boolean flag(JsonObject value,String key){return value!=null && value.has(key) && value.get(key).getAsBoolean();} + private static long number(JsonObject value,String key){return value.has(key)?Math.max(0,value.get(key).getAsLong()):0;} + private static String fmt(long value){return String.format(Locale.ROOT,"%,d",value);} + public static List lines() { + List lines=new ArrayList<>(); + if(!EarthConfig.get().usageHud)return lines; + boolean photo=PanoramaRenderer.INSTANCE.active(); + JsonObject data=photo?street:terrain; + if(!flag(data,"available")){lines.add("Usage: unavailable");return lines;} + if(photo && !flag(data,"configured")){lines.add("Usage: key not set");return lines;} + if(!photo && !flag(data,"directGoogle")){lines.add("Usage: provider account");return lines;} + long used=number(data,photo?"tiles":"roots"),limit=number(data,photo?"freeStreetTiles":"free3dRoots"); + String unit=photo?"tiles":"3D roots"; + lines.add((photo?"Tiles: ":"3D roots: ")+fmt(used)+" / "+fmt(limit)); + lines.add("Free ~"+fmt(Math.max(0,limit-used))+" · Local/month"); + if(photo){int tiles=PanoramaRenderer.INSTANCE.tilesPerPhoto();if(tiles>0)lines.add("Next ~"+tiles+" tiles · Requests "+fmt(number(data,"requests")));} + + if(photo)lines.add("Cache: "+fmt(number(data,"cachedTiles"))+" tiles · Reused "+fmt(number(data,"cacheHits"))); + return lines; + } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/CelestialBody.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/CelestialBody.java new file mode 100644 index 0000000..18e9537 --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/CelestialBody.java @@ -0,0 +1,15 @@ +package dev.realworldmc.client; + +/** Mean radii in metres. Planetary maps are bundled and require no map-provider credentials. */ +public enum CelestialBody { + EARTH("Earth",6_378_137,0,""), + MOON("Moon",1_737_400,20_000,"NASA Scientific Visualization Studio / LROC, RealWorldMC"), + MARS("Mars",3_389_500,40_000,"NASA / JPL-Caltech / USGS Viking, RealWorldMC"); + + public final String title, credits; + public final double radius, minimumAltitude; + CelestialBody(String title,double radius,double minimumAltitude,String credits) { + this.title=title;this.radius=radius;this.minimumAltitude=minimumAltitude;this.credits=credits; + } + public String id() { return name().toLowerCase(java.util.Locale.ROOT); } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/CreativeFlight.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/CreativeFlight.java new file mode 100644 index 0000000..eaabb60 --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/CreativeFlight.java @@ -0,0 +1,137 @@ +package dev.realworldmc.client; + +import dev.realworldmc.FlightBoost; +import dev.realworldmc.RWMessages; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.fabricmc.fabric.api.client.message.v1.ClientSendMessageEvents; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; +import net.minecraft.client.Minecraft; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; + +/** Equipment-free local flight; the existing orbital controller owns movement above its threshold. */ +public final class CreativeFlight { + // Vanilla rocket-assisted level flight is about 33 m/s; this cruise target is about twice that. + static final double MAX_SPEED = 3.3, MIN_SPEED = .2; + private static boolean active, glide; + private static double speed = MAX_SPEED; + private static Vec3 velocity = Vec3.ZERO; + private static final FlightPose pose = new FlightPose(); + private CreativeFlight() {} + + public static boolean enabled() { return active; } + public static boolean gliding() { return glide; } + public static boolean posed(Entity entity) { return enabled() && entity == Minecraft.getInstance().player; } + public static FlightPose pose() { return pose; } + public static double speedFactor() { return enabled() ? speed / MAX_SPEED * movementMultiplier() * (FlightBoost.boosted() ? 1.5 : 1) : 1; } + private static double movementMultiplier() { + var player = Minecraft.getInstance().player; + if (player == null) return 1; + // Axiom adjusts vanilla flying speed; effects and movement mods use this attribute. + double flying = player.getAbilities().getFlyingSpeed() / .05f; + double base = player.getAttributeBaseValue(net.minecraft.world.entity.ai.attributes.Attributes.MOVEMENT_SPEED); + double effects = base > 0 ? player.getAttributeValue(net.minecraft.world.entity.ai.attributes.Attributes.MOVEMENT_SPEED) / base : 1; + double multiplier = flying * effects; + return Double.isFinite(multiplier) ? net.minecraft.util.Mth.clamp(multiplier, 0, 8) : 1; + } + public static int rocketForward(int forward, int right, int vertical) { + return enabled() && FlightBoost.boosted() && forward == 0 && right == 0 && vertical == 0 ? 1 : forward; + } + public static String status() { + return (gliding() ? "Glide" : "Hover") + String.format(java.util.Locale.ROOT, " · %.0f%% speed%s", speed / MAX_SPEED * 100, FlightBoost.boosted() ? " · rocket" : ""); + } + private static boolean allowed(Minecraft mc) { + return mc.player != null && mc.level != null && mc.hasSingleplayerServer() + && mc.player.isCreative() && mc.player.isAlive() && !mc.player.isPassenger() + && mc.level.dimension() == Level.OVERWORLD && MapRenderer.INSTANCE.enabled(); + } + public static void register() { + ClientSendMessageEvents.ALLOW_COMMAND.register(command -> { + String[] words = command.strip().split("\\s+"); + if (words.length < 2 || words.length > 3 || !(words[0].equals("earth") || words[0].equals("rw"))) return true; + if (!words[1].equals("fly") || words.length == 3 && !java.util.Set.of("on", "off").contains(words[2])) return true; + set(words.length == 3 ? words[2].equals("on") : !enabled()); + return false; + }); + ClientTickEvents.START_CLIENT_TICK.register(CreativeFlight::tick); + ClientPlayConnectionEvents.DISCONNECT.register((handler, mc) -> stop(mc)); + } + private static void set(boolean on) { + var mc = Minecraft.getInstance(); + if (!on) { + stop(mc); + ActionBar.show(RWMessages.message("Flight off")); + return; + } + if (!allowed(mc)) { + if (mc.player != null) mc.player.displayClientMessage(RWMessages.message("Glide and fly need a Creative, singleplayer Real World world. Leave Street View or your vehicle first."), false); + return; + } + if (enabled()) return; + active = true; glide = false; + pose.reset(mc.player.getYRot()); + FlightBoost.begin(mc.getSingleplayerServer(), mc.player.getUUID()); + mc.player.stopFallFlying(); + mc.player.getAbilities().flying = true; + mc.player.onUpdateAbilities(); + var id = mc.player.getUUID(); var server = mc.getSingleplayerServer(); + server.execute(() -> { var player = server.getPlayerList().getPlayer(id); if (player != null && FlightBoost.active(player)) player.stopFallFlying(); }); + ActionBar.show(RWMessages.message(status() + " · /earth fly: off")); + } + private static void stop(Minecraft mc) { + if (enabled() && mc.player != null) mc.player.setDeltaMovement(Vec3.ZERO); + active = false; glide = false; velocity = Vec3.ZERO; speed = MAX_SPEED; + FlightBoost.clear(); + // Leave ordinary Creative flight available so toggling off cannot drop the player. + } + private static void tick(Minecraft mc) { + if (!enabled()) return; + if (!allowed(mc)) { stop(mc); return; } + if (mc.isPaused()) return; + FlightBoost.tick(); + if (!mc.player.getAbilities().flying) { + mc.player.getAbilities().flying = true; + mc.player.onUpdateAbilities(); + } + mc.player.fallDistance = 0; + if (mc.screen != null) { velocity = Vec3.ZERO; glide = false; pose.film(false, Vec3.ZERO, mc.player.getYRot()); return; } + var arrows = PanoramaRenderer.INSTANCE; + adjustSpeed((arrows.flightSpeedKey(true).isDown() ? 1 : 0) - (arrows.flightSpeedKey(false).isDown() ? 1 : 0)); + int forward = (mc.options.keyUp.isDown() ? 1 : 0) - (mc.options.keyDown.isDown() ? 1 : 0); + int right = (mc.options.keyRight.isDown() ? 1 : 0) - (mc.options.keyLeft.isDown() ? 1 : 0); + int vertical = (mc.options.keyJump.isDown() ? 1 : 0) - (mc.options.keyShift.isDown() ? 1 : 0); + forward = rocketForward(forward, right, vertical); + Vec3 direction = direction(forward, right, vertical, mc.player.getYRot(), mc.player.getXRot()); + Vec3 target = direction.scale(MAX_SPEED * speedFactor()); + velocity = velocity.lerp(target, .18); + if (velocity.lengthSqr() < .00001) velocity = Vec3.ZERO; + updateStance(); + pose.film(gliding(), velocity, mc.player.getYRot()); + } + private static void updateStance() { + // Separate thresholds prevent pose chatter near hovering speed. + glide = velocity.horizontalDistance() > (glide ? .25 : .65); + } + static void adjustSpeed(int direction) { speed = net.minecraft.util.Mth.clamp(speed + Integer.signum(direction) * .045, MIN_SPEED, MAX_SPEED); } + static Vec3 direction(int forward, int right, int vertical, float yawDegrees, float pitchDegrees) { + double yaw = Math.toRadians(yawDegrees), pitch = Math.toRadians(pitchDegrees); + Vec3 direction = new Vec3(-Math.sin(yaw) * Math.cos(pitch) * forward - Math.cos(yaw) * right, + vertical - Math.sin(pitch) * forward, Math.cos(yaw) * Math.cos(pitch) * forward - Math.sin(yaw) * right); + return direction.lengthSqr() > 1 ? direction.normalize() : direction; + } + public static boolean travel(Player player) { + var mc = Minecraft.getInstance(); + if (!posed(player) || !allowed(mc) || SpaceFlight.enabled()) return false; + player.setDeltaMovement(velocity); + player.move(MoverType.SELF, velocity); + if (player.horizontalCollision) velocity = new Vec3(0, velocity.y, 0); + if (player.verticalCollision) velocity = new Vec3(velocity.x, 0, velocity.z); + player.setDeltaMovement(velocity); + updateStance(); + player.fallDistance = 0; + return true; + } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/DistantHorizonsCompat.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/DistantHorizonsCompat.java new file mode 100644 index 0000000..65565f6 --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/DistantHorizonsCompat.java @@ -0,0 +1,49 @@ +package dev.realworldmc.client; + +import dev.realworldmc.RealWorldMC; +import dev.realworldmc.PanoramaRoom; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.client.Minecraft; +import net.minecraft.world.level.Level; +import java.lang.reflect.Method; + +/** Temporary DH API override: do not change the user's saved DH or shader settings. */ +public final class DistantHorizonsCompat { + private static boolean unavailable, owned, warned; + private static Object value, previous; + private static Method getApiValue, setValue, clearValue; + public static void update(Minecraft mc) { + boolean hide = mc.level != null && (PanoramaRoom.isRoom(mc.level) + || (mc.level.dimension().equals(Level.OVERWORLD) && MapRenderer.INSTANCE.enabled())); + if(unavailable || (!hide && !owned)) return; + try { + if(value == null) { + if(!FabricLoader.getInstance().isModLoaded("distanthorizons")){unavailable=true;return;} + Object configs=Class.forName("com.seibel.distanthorizons.api.DhApi$Delayed").getField("configs").get(null); + if(configs==null)return; // DH initializes its API after Minecraft starts. + Object graphics=Class.forName("com.seibel.distanthorizons.api.interfaces.config.IDhApiConfig").getMethod("graphics").invoke(configs); + value=Class.forName("com.seibel.distanthorizons.api.interfaces.config.client.IDhApiGraphicsConfig").getMethod("renderingEnabled").invoke(graphics); + Class type=Class.forName("com.seibel.distanthorizons.api.interfaces.config.IDhApiConfigValue"); + getApiValue=type.getMethod("getApiValue");setValue=type.getMethod("setValue",Object.class);clearValue=type.getMethod("clearValue"); + } + if(hide && !owned) { + previous=getApiValue.invoke(value); + owned=Boolean.TRUE.equals(setValue.invoke(value,Boolean.FALSE)); + if(!owned && !warned){warned=true;RealWorldMC.LOGGER.warn("DH refused the temporary LOD rendering override.");} + } else if(!hide && owned) release(); + } catch(ReflectiveOperationException e) { + if(!warned){warned=true;RealWorldMC.LOGGER.warn("DH compatibility API unavailable; disable DH rendering manually in Earth worlds.");} + unavailable=true; + } + } + public static void release() { + if(!owned)return; + try { + // Do not overwrite an override changed by another mod while we were active. + if(Boolean.FALSE.equals(getApiValue.invoke(value))) { + if(previous==null)clearValue.invoke(value);else setValue.invoke(value,previous); + } + }catch(ReflectiveOperationException e){RealWorldMC.LOGGER.warn("Could not restore the temporary DH override.");} + owned=false;previous=null; + } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/EarthSettings.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/EarthSettings.java new file mode 100644 index 0000000..2783d57 --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/EarthSettings.java @@ -0,0 +1,90 @@ +package dev.realworldmc.client; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import dev.realworldmc.ServiceClient; +import net.fabricmc.loader.api.FabricLoader; + +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Stores and manages dynamic Earth rendering quality and distance settings. + */ +public final class EarthSettings { + public static final int DEFAULT_FINE_RADIUS = 160; + public static final int DEFAULT_FAR = 8000; + public static final int DEFAULT_MAX_TILES = 900; + public static final int DEFAULT_MAX_SSE = 12; + + public static final int[] FINE_RADIUS_PRESETS = { 96, 160, 240, 320, 480, 640 }; + public static final int[] FAR_PRESETS = { 4000, 8000, 12000, 16000, 24000 }; + public static final int[] MAX_TILES_PRESETS = { 600, 900, 1200, 1600, 2400 }; + public static final int[] MAX_SSE_PRESETS = { 18, 12, 8, 4 }; + + private static volatile int fineRadius = DEFAULT_FINE_RADIUS; + private static volatile int far = DEFAULT_FAR; + private static volatile int maxTiles = DEFAULT_MAX_TILES; + private static volatile int maxSse = DEFAULT_MAX_SSE; + + private static boolean loaded = false; + + private EarthSettings() {} + + public static int getFineRadius() { ensureLoaded(); return fineRadius; } + public static int getFar() { ensureLoaded(); return far; } + public static int getMaxTiles() { ensureLoaded(); return maxTiles; } + public static int getMaxSse() { ensureLoaded(); return maxSse; } + + public static void setFineRadius(int v) { fineRadius = Math.max(96, Math.min(640, v)); } + public static void setFar(int v) { far = Math.max(4000, Math.min(24000, v)); } + public static void setMaxTiles(int v) { maxTiles = Math.max(600, Math.min(2400, v)); } + public static void setMaxSse(int v) { maxSse = Math.max(4, Math.min(18, v)); } + + public static synchronized void ensureLoaded() { + if (loaded) return; + loaded = true; + try { + Path file = getConfigFile(); + if (Files.exists(file)) { + JsonObject json = JsonParser.parseString(Files.readString(file)).getAsJsonObject(); + if (json.has("render") && json.get("render").isJsonObject()) { + JsonObject r = json.getAsJsonObject("render"); + if (r.has("fineRadius")) setFineRadius(r.get("fineRadius").getAsInt()); + if (r.has("far")) setFar(r.get("far").getAsInt()); + if (r.has("maxTiles")) setMaxTiles(r.get("maxTiles").getAsInt()); + if (r.has("maxSse")) setMaxSse(r.get("maxSse").getAsInt()); + } + } + } catch (Exception ignored) {} + } + + public static synchronized boolean save() { + Path file=getConfigFile(), temporary=null; + try { + JsonObject r=new JsonObject(); + r.addProperty("fineRadius", getFineRadius()); r.addProperty("far", getFar()); + r.addProperty("maxTiles", getMaxTiles()); r.addProperty("maxSse", getMaxSse()); + JsonObject json=new JsonObject(); json.add("render",r); + Files.createDirectories(file.getParent()); + temporary=Files.createTempFile(file.getParent(), "realworldmc-render-", ".tmp"); + Files.writeString(temporary,new GsonBuilder().setPrettyPrinting().create().toJson(json)); + try { Files.move(temporary,file,java.nio.file.StandardCopyOption.ATOMIC_MOVE,java.nio.file.StandardCopyOption.REPLACE_EXISTING); } + catch(java.nio.file.AtomicMoveNotSupportedException unsupported) { Files.move(temporary,file,java.nio.file.StandardCopyOption.REPLACE_EXISTING); } + return true; + } catch(Exception failure) { return false; } + finally { if(temporary!=null)try{Files.deleteIfExists(temporary);}catch(Exception ignored){} } + } + + public static void resetDefaults() { + fineRadius = DEFAULT_FINE_RADIUS; + far = DEFAULT_FAR; + maxTiles = DEFAULT_MAX_TILES; + maxSse = DEFAULT_MAX_SSE; + } + + private static Path getConfigFile() { + return FabricLoader.getInstance().getConfigDir().resolve("realworldmc-render.json"); + } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/EarthSettingsScreen.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/EarthSettingsScreen.java new file mode 100644 index 0000000..d6adb49 --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/EarthSettingsScreen.java @@ -0,0 +1,236 @@ +package dev.realworldmc.client; + +import dev.realworldmc.RWTheme; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; + +public final class EarthSettingsScreen extends Screen { + private final Screen parent; + private int panelWidth, panelHeight, left, top; + + private int fineRadiusIdx; + private int farIdx; + private int maxTilesIdx; + private int maxSseIdx; + + private Button fineRadiusBtn; + private Button farBtn; + private Button maxTilesBtn; + private Button maxSseBtn; + private String statusMsg = ""; + + public EarthSettingsScreen(Screen parent) { + super(Component.translatable("gui.realworldmc.settings.title")); + this.parent = parent; + EarthSettings.ensureLoaded(); + initIndices(); + } + + private static volatile boolean openRequested = false; + + public static void register() { + net.fabricmc.fabric.api.client.message.v1.ClientSendMessageEvents.ALLOW_COMMAND.register(command -> { + String c = command.strip().toLowerCase(java.util.Locale.ROOT); + if (c.startsWith("/")) c = c.substring(1).stripLeading(); + if (c.matches("(?:rw|earth)\\s+settings")) { + openRequested = true; + return false; + } + return true; + }); + + net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents.END_CLIENT_TICK.register(client -> { + if (openRequested) { + openRequested = false; + client.setScreen(new EarthSettingsScreen(null)); + } + }); + } + + private void initIndices() { + fineRadiusIdx = findClosestIndex(EarthSettings.FINE_RADIUS_PRESETS, EarthSettings.getFineRadius()); + farIdx = findClosestIndex(EarthSettings.FAR_PRESETS, EarthSettings.getFar()); + maxTilesIdx = findClosestIndex(EarthSettings.MAX_TILES_PRESETS, EarthSettings.getMaxTiles()); + maxSseIdx = findClosestIndex(EarthSettings.MAX_SSE_PRESETS, EarthSettings.getMaxSse()); + } + + private static int findClosestIndex(int[] array, int val) { + int best = 0; + int diff = Math.abs(array[0] - val); + for (int i = 1; i < array.length; i++) { + int d = Math.abs(array[i] - val); + if (d < diff) { + diff = d; + best = i; + } + } + return best; + } + + @Override + public boolean isPauseScreen() { + return true; + } + + @Override + protected void init() { + panelWidth = Math.min(440, width - 24); + panelHeight = Math.min(290, height - 24); + left = (width - panelWidth) / 2; + top = (height - panelHeight) / 2; + + int rowY = top + 42; + int btnW = Math.min(170, panelWidth / 2 - 16); + int btnX = left + panelWidth - btnW - 16; + + // 1. Fine Radius + fineRadiusBtn = addRenderableWidget(Button.builder( + getFineRadiusText(), + b -> { + fineRadiusIdx = (fineRadiusIdx + 1) % EarthSettings.FINE_RADIUS_PRESETS.length; + b.setMessage(getFineRadiusText()); + statusMsg = ""; + } + ).bounds(btnX, rowY, btnW, 20).build()); + + // 2. Far distance + rowY += Math.min(32, (panelHeight - 105) / 3); + farBtn = addRenderableWidget(Button.builder( + getFarText(), + b -> { + farIdx = (farIdx + 1) % EarthSettings.FAR_PRESETS.length; + b.setMessage(getFarText()); + statusMsg = ""; + } + ).bounds(btnX, rowY, btnW, 20).build()); + + // 3. Max tiles + rowY += Math.min(32, (panelHeight - 105) / 3); + maxTilesBtn = addRenderableWidget(Button.builder( + getMaxTilesText(), + b -> { + maxTilesIdx = (maxTilesIdx + 1) % EarthSettings.MAX_TILES_PRESETS.length; + b.setMessage(getMaxTilesText()); + statusMsg = ""; + } + ).bounds(btnX, rowY, btnW, 20).build()); + + // 4. Max SSE / Quality + rowY += Math.min(32, (panelHeight - 105) / 3); + maxSseBtn = addRenderableWidget(Button.builder( + getMaxSseText(), + b -> { + maxSseIdx = (maxSseIdx + 1) % EarthSettings.MAX_SSE_PRESETS.length; + b.setMessage(getMaxSseText()); + statusMsg = ""; + } + ).bounds(btnX, rowY, btnW, 20).build()); + + // Actions + int bottomY = top + panelHeight - 32; + addRenderableWidget(Button.builder( + Component.translatable("gui.realworldmc.settings.save"), + b -> applyAndSave() + ).bounds(left + 8, bottomY, (panelWidth-32)/3, 20).build()); + + addRenderableWidget(Button.builder( + Component.translatable("gui.realworldmc.settings.defaults"), + b -> resetDefaults() + ).bounds(left + 16+(panelWidth-32)/3, bottomY, (panelWidth-32)/3, 20).build()); + + addRenderableWidget(Button.builder( + Component.translatable("gui.realworldmc.update.close"), + b -> onClose() + ).bounds(left + 24+2*((panelWidth-32)/3), bottomY, (panelWidth-32)/3, 20).build()); + } + + private Component getFineRadiusText() { + int val = EarthSettings.FINE_RADIUS_PRESETS[fineRadiusIdx]; + int chunks = val / 16; + String note = ""; + return Component.literal(val + " m (" + chunks + " ch.)" + note); + } + + private Component getFarText() { + int val = EarthSettings.FAR_PRESETS[farIdx]; + int km = val / 1000; + int chunks = val / 16; + String note = ""; + return Component.literal(km + " km (" + chunks + " ch.)" + note); + } + + private Component getMaxTilesText() { + int val = EarthSettings.MAX_TILES_PRESETS[maxTilesIdx]; + String note = ""; + return Component.literal(val + " tiles" + note); + } + + private Component getMaxSseText() { + int val = EarthSettings.MAX_SSE_PRESETS[maxSseIdx]; + String label = switch (val) { + case 18 -> "18"; + case 12 -> "12"; + case 8 -> "8"; + case 4 -> "4"; + default -> String.valueOf(val); + }; + return Component.literal(label); + } + + private void applyAndSave() { + EarthSettings.setFineRadius(EarthSettings.FINE_RADIUS_PRESETS[fineRadiusIdx]); + EarthSettings.setFar(EarthSettings.FAR_PRESETS[farIdx]); + EarthSettings.setMaxTiles(EarthSettings.MAX_TILES_PRESETS[maxTilesIdx]); + EarthSettings.setMaxSse(EarthSettings.MAX_SSE_PRESETS[maxSseIdx]); + statusMsg = Component.translatable(EarthSettings.save()?"gui.realworldmc.settings.saved":"gui.realworldmc.settings.save_failed").getString(); + } + + private void resetDefaults() { + EarthSettings.resetDefaults(); + initIndices(); + if (fineRadiusBtn != null) fineRadiusBtn.setMessage(getFineRadiusText()); + if (farBtn != null) farBtn.setMessage(getFarText()); + if (maxTilesBtn != null) maxTilesBtn.setMessage(getMaxTilesText()); + if (maxSseBtn != null) maxSseBtn.setMessage(getMaxSseText()); + statusMsg = Component.translatable(EarthSettings.save()?"gui.realworldmc.settings.saved":"gui.realworldmc.settings.save_failed").getString(); + } + + @Override + public void render(GuiGraphics g, int mouseX, int mouseY, float delta) { + g.fill(0, 0, width, height, 0xC0000000); + g.fill(left, top, left + panelWidth, top + panelHeight, 0xFF1E2224); + g.fill(left, top, left + 3, top + panelHeight, RWTheme.BRAND); + + // Heading + g.drawString(font, Component.translatable("gui.realworldmc.settings.heading"), left + 14, top + 12, RWTheme.GREEN, false); + g.drawString(font, Component.translatable("gui.realworldmc.settings.subheading"), left + 14, top + 24, RWTheme.MUTED, false); + + // Labels + int labelX = left + 16; + int rowY = top + 47; + g.drawString(font, Component.translatable("gui.realworldmc.settings.fine_radius"), labelX, rowY, 0xEEEEEE, false); + rowY += Math.min(32, (panelHeight - 105) / 3); + g.drawString(font, Component.translatable("gui.realworldmc.settings.far"), labelX, rowY, 0xEEEEEE, false); + rowY += Math.min(32, (panelHeight - 105) / 3); + g.drawString(font, Component.translatable("gui.realworldmc.settings.max_tiles"), labelX, rowY, 0xEEEEEE, false); + rowY += Math.min(32, (panelHeight - 105) / 3); + g.drawString(font, Component.translatable("gui.realworldmc.settings.max_sse"), labelX, rowY, 0xEEEEEE, false); + + // Status message + if (!statusMsg.isEmpty()) { + g.drawString(font, statusMsg, left + 16, top + panelHeight - 48, 0xFFFFFF, false); + } + + super.render(g, mouseX, mouseY, delta); + } + + @Override + public void onClose() { + if (minecraft != null) { + minecraft.setScreen(parent); + } + } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/FlightPose.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/FlightPose.java new file mode 100644 index 0000000..5a04ca7 --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/FlightPose.java @@ -0,0 +1,39 @@ +package dev.realworldmc.client; + +import net.minecraft.util.Mth; + +/** Render-only motion. Looking around never changes the direction of a vertical climb. */ +public final class FlightPose { + private float pitch, oldPitch, yaw, oldYaw, thrust, oldThrust, bank, oldBank; + public void reset(float heading) { + pitch=oldPitch=thrust=oldThrust=bank=oldBank=0; + yaw=oldYaw=heading; + } + public void tick(int forward, int right, int vertical, float heading) { + oldPitch=pitch; oldYaw=yaw; oldThrust=thrust; oldBank=bank; + double horizontal=Math.hypot(forward,right); + boolean moving=horizontal>0 || vertical!=0; + float targetPitch=moving ? (float)Math.toDegrees(Math.atan2(horizontal,vertical)) : 0; + float targetYaw=horizontal>0 ? heading-(float)Math.toDegrees(Math.atan2(right,forward)) : yaw; + pitch=Mth.lerp(.22f,pitch,targetPitch); + yaw+=Mth.wrapDegrees(targetYaw-yaw)*.22f; + thrust=Mth.lerp(.18f,thrust,moving?1:0); + bank=Mth.lerp(.18f,bank,right*-12f); + } + /** Film flight has a flat glide posture or an upright hover, without changing the hitbox. */ + public void film(boolean glide, net.minecraft.world.phys.Vec3 movement, float heading) { + oldPitch=pitch; oldYaw=yaw; oldThrust=thrust; oldBank=bank; + boolean moving=movement.lengthSqr()>.0001; + float targetYaw=moving && movement.horizontalDistanceSqr()>.0001 + ? (float)Math.toDegrees(Math.atan2(-movement.x,movement.z)) : heading; + float targetPitch=glide && moving ? (float)Math.toDegrees(Math.atan2(movement.horizontalDistance(),movement.y)) : 0; + pitch=Mth.lerp(.22f,pitch,targetPitch); + yaw+=Mth.wrapDegrees(targetYaw-yaw)*.22f; + thrust=Mth.lerp(.18f,thrust,glide && moving?1:0); + bank=Mth.lerp(.18f,bank,glide?Mth.clamp(Mth.wrapDegrees(targetYaw-yaw)*.12f,-12,12):0); + } + public float pitch(float partial) { return Mth.lerp(partial,oldPitch,pitch); } + public float yaw(float partial) { return Mth.rotLerp(partial,oldYaw,yaw); } + public float thrust(float partial) { return Mth.lerp(partial,oldThrust,thrust); } + public float bank(float partial) { return Mth.lerp(partial,oldBank,bank); } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/GlobeOrbit.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/GlobeOrbit.java new file mode 100644 index 0000000..db2546b --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/GlobeOrbit.java @@ -0,0 +1,71 @@ +package dev.realworldmc.client; + +import dev.realworldmc.EarthRegions; +import net.minecraft.world.phys.Vec3; +import org.joml.Quaterniond; +import org.joml.Vector3d; + +/** Moves the geographic viewpoint while keeping Minecraft's player in one loaded region. */ +public final class GlobeOrbit { + private final Quaterniond rotation = new Quaterniond(), previous = new Quaterniond(); + private double speed, sideSpeed; + private boolean travelled; + + public void reset() { rotation.identity(); previous.identity(); speed = sideSpeed = 0; travelled = false; } + public boolean travelled() { return travelled; } + public void hold() { previous.set(rotation); speed = sideSpeed = 0; } + public Quaterniond rotation(float partial) { return previous.slerp(rotation, net.minecraft.util.Mth.clamp(partial, 0, 1), new Quaterniond()); } + public void tick(double altitude, float yaw, int forward) { + tick(altitude,yaw,forward,0); + } + public void tick(double altitude, float yaw, int forward, int right) { + tick(altitude,yaw,forward,right,6_378_137); + } + public void tick(double altitude, float yaw, int forward, int right, double radius) { + tick(altitude, yaw, forward, right, radius, 1); + } + public void tick(double altitude, float yaw, int forward, int right, double radius, double speedMultiplier) { + previous.set(rotation); + double rate = SpaceFlight.verticalSpeed(altitude) * net.minecraft.util.Mth.clamp(speedMultiplier, 0, 12) / Math.max(1,Math.hypot(forward,right)); + speed += (forward * rate - speed) * .3; + sideSpeed += (right * rate - sideSpeed) * .3; + if (forward == 0 && Math.abs(speed) < .01) speed = 0; + if (right == 0 && Math.abs(sideSpeed) < .01) sideSpeed = 0; + double length = Math.hypot(speed,sideSpeed); + double angle = net.minecraft.util.Mth.clamp(length / (radius + altitude), 0, .02); + if (angle == 0) return; + double heading = Math.toRadians(yaw); + double dx=(-Math.sin(heading)*speed-Math.cos(heading)*sideSpeed)/length; + double dz=(Math.cos(heading)*speed-Math.sin(heading)*sideSpeed)/length; + rotation.premul(new Quaterniond().rotationAxis(-angle, dz, 0, -dx)).normalize(); + travelled = true; + } + public static Vec3 centre(EarthRegions.Region region) { + if (region == null) return new Vec3(0, 64 - 6_378_137, 0); + double lat = Math.toRadians(region.latitude()), sin = Math.sin(lat), cos = Math.cos(lat); + double e2 = 6.6943799901413165e-3, n = 6_378_137 / Math.sqrt(1 - e2 * sin * sin); + return new Vec3(region.offsetX(), 64 - n * (1 - e2 * sin * sin) - region.groundHeight(), + region.offsetZ() - n * e2 * sin * cos); + } + public static Vec3 cameraInMap(Vec3 camera, Vec3 centre, Quaterniond rotation) { + Vec3 offset = camera.subtract(centre); + var point = rotation.transformInverse(new Vector3d(offset.x, offset.y, offset.z)); + return centre.add(point.x, point.y, point.z); + } + /** Keep the subject above the WGS84 ellipsoid, including when crossing the poles. */ + public static Vec3 cameraInMap(Vec3 camera, Vec3 subject, EarthRegions.Region region, Quaterniond rotation) { + return cameraInMap(camera,subject,region,rotation,subject.y-64); + } + public static Vec3 cameraInMap(Vec3 camera, Vec3 subject, EarthRegions.Region region, Quaterniond rotation, double altitude) { + if (region == null) return cameraInMap(camera, centre(null), rotation); + var raw = cameraInMap(subject, centre(region), rotation); + var geo = dev.realworldmc.Geo.mcToGeodetic(region.latitude(), region.longitude(), region.groundHeight(), + raw.x-region.offsetX(), raw.y, raw.z-region.offsetZ()); + var corrected = dev.realworldmc.Geo.geodeticToMc(region.latitude(), region.longitude(), region.groundHeight(), + geo[0], geo[1], region.groundHeight()+altitude); + var offset = camera.subtract(subject); + var rotatedOffset = rotation.transformInverse(new Vector3d(offset.x,offset.y,offset.z)); + return new Vec3(region.offsetX()+corrected[0]+rotatedOffset.x, corrected[1]+rotatedOffset.y, + region.offsetZ()+corrected[2]+rotatedOffset.z); + } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/HelpScreen.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/HelpScreen.java new file mode 100644 index 0000000..d1549fd --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/HelpScreen.java @@ -0,0 +1,98 @@ +package dev.realworldmc.client; + +import dev.realworldmc.RWTheme; + +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.fabricmc.fabric.api.client.message.v1.ClientSendMessageEvents; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.ChatScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; + +/** A scene-visible command guide. Selecting a command only fills chat. */ +public final class HelpScreen extends Screen { + private record Entry(String group,String command,String description) {} + private static final Entry[] ENTRIES={ + new Entry("Explore","/earth goto ","Travel to a real place."), + new Entry("Explore","/earth where","Show your coordinates and map link."), + new Entry("Explore","/earth setup","Add or test API keys privately."), + new Entry("Explore","/earth fly","Toggle automatic glide and upright hover."), + new Entry("Street View","/earth streetview","Open the nearest photo within 500 metres."), + new Entry("Street View","/earth streetview ","Open a photo at chosen coordinates."), + new Entry("Street View","/earth back","Return to Earth at the current photo location."), + new Entry("Street View","/earth back original","Return to the original entry point."), + new Entry("Movement","/earth walk on|off","Walk inside 3×3, or stay at the photo center. V also toggles."), + new Entry("Movement","/earth camera first|back|front","Choose your perspective. F5 also changes camera."), + new Entry("Movement","/earth streetkey on|off","Toggle Sneak + Swap Offhand with empty hands (usually Shift + F)."), + new Entry("Display","/earth hud on|off","Show or hide the optional HUD and navigation arrows."), + new Entry("Display","/earth usage on|off","Show or hide usage estimates separately."), + new Entry("Display","/earth controls on|off","Show or hide key hints separately."), + new Entry("Space","/earth space","Toggle experimental Earth-to-space flight."), + new Entry("Space","/rw moon","Visit the Moon orbital view."), + new Entry("Space","/rw mars","Visit the Mars orbital view."), + new Entry("Space","/rw earth","Return to your previous Earth orbit."), + new Entry("Advanced","/earth streetview height <1-4>","Set photo eye height in metres. Ground depth is approximate."), + new Entry("Advanced","/earth streetview browser","Open the companion browser viewer."), + new Entry("Advanced","/earth streetview setup","Show Street View setup guidance."), + new Entry("Advanced","/earth streetview legacy","Open the previous flat sandbox."), + new Entry("Advanced","/earth setlocation ","Set the start for NEW worlds. Operator permission required."), + new Entry("Advanced","/earth setlocation random","Randomize the start for NEW worlds. Operator only.") + }; + private static int requested=-1; + private int page,left,top,panelWidth,panelHeight,perPage; + public HelpScreen(boolean advanced){super(Component.literal("Earth guide"));page=advanced?-1:0;} + public static void register(){ + ClientSendMessageEvents.ALLOW_COMMAND.register(command->{ + String normalized=command.strip().replaceAll("\\s+"," "); + if(normalized.matches("(?:rw|earth)(?: help(?: more)?)?")){ + requested=normalized.endsWith(" more")?1:0;return false; + } + return true; + }); + ClientTickEvents.END_CLIENT_TICK.register(client->{ + if(requested>=0){boolean advanced=requested==1;requested=-1;if(client.player!=null)client.setScreen(new HelpScreen(advanced));} + }); + } + @Override public boolean isPauseScreen(){return false;} + @Override public void renderBackground(GuiGraphics g){} + @Override protected void init(){ + panelWidth=Math.min(500,width-16);panelHeight=Math.min(366,height-16); + left=(width-panelWidth)/2;top=(height-panelHeight)/2; + perPage=Math.max(1,(panelHeight-100)/43); + page=page<0?18/perPage:Math.min(page,(ENTRIES.length-1)/perPage); + int end=Math.min(ENTRIES.length,(page+1)*perPage); + for(int i=page*perPage;iminecraft.setScreen(new ChatScreen(entry.command())),entry)); + } + int y=top+panelHeight-29; + var previous=addRenderableWidget(new GuideButton(left+10,y,76,20,"Previous",()->{page--;rebuildWidgets();},null));previous.active=page>0; + var next=addRenderableWidget(new GuideButton(left+92,y,76,20,"Next",()->{page++;rebuildWidgets();},null));next.active=endaction.run(),DEFAULT_NARRATION);this.entry=entry; + } + @Override protected void renderWidget(GuiGraphics g,int mouseX,int mouseY,float delta){ + g.fill(getX(),getY(),getX()+width,getY()+height,isHoveredOrFocused()?RWTheme.HOVER:RWTheme.SURFACE); + int color=active?RWTheme.GREEN:RWTheme.DISABLED; + if(entry==null){g.drawString(font,getMessage(),getX()+(width-font.width(getMessage()))/2,getY()+6,color,false);return;} + g.drawString(font,font.plainSubstrByWidth(entry.command(),width-12),getX()+6,getY()+4,color,false); + var lines=font.split(Component.literal(entry.description()),width-12); + for(int i=0;i originals=new HashMap<>(); + private static final PhotoEditsRenderer surfaces=new PhotoEditsRenderer(); + private static Map pending; + private MapDamage() { } + public static void clear(){originals.clear();surfaces.clear();pending=null;} + public static boolean tracked(BlockPos pos){return originals.containsKey(pos);} + public static void receive(MapEditsPayload payload) { + if(payload.reset()){pending=new HashMap<>();return;} + if(pending!=null) { + if(!payload.edits().isEmpty()) { + for(var edit:payload.edits()) { + BlockState state=Block.stateById(edit.originalState()); + if(EarthBlocks.isMapBlock(state) || state.isAir())pending.put(BlockPos.of(edit.position()),state); + } + return; + } + originals.clear();originals.putAll(pending);pending=null;surfaces.clear(); + var snapshot=originals.entrySet().stream().map(e->new StreetEditsPayload.Edit(e.getKey().asLong(),Block.getId(e.getValue()))).toList(); + surfaces.receive(new StreetEditsPayload(false,snapshot)); + MapRenderer.INSTANCE.invalidateDamage();return; + } + List converted=new ArrayList<>(); + for(var edit:payload.edits()) { + BlockState state=Block.stateById(edit.originalState()); + if(!EarthBlocks.isMapBlock(state) && !state.isAir())continue; + originals.put(BlockPos.of(edit.position()),state); + converted.add(new StreetEditsPayload.Edit(edit.position(),edit.originalState())); + } + surfaces.receive(new StreetEditsPayload(false,converted)); + MapRenderer.INSTANCE.invalidateDamage(); + } + public static List cuts(AABB bounds,ClientLevel level,double ax,double ay,double az) { + if(level==null || !level.dimension().equals(Level.OVERWORLD))return List.of(); + List result=new ArrayList<>(); + originals.forEach((pos,state)->{ + double shift=state.isAir()?0:.5; + if(pos.getX()+1bounds.maxX || pos.getY()+1+shiftbounds.maxY || pos.getZ()+1bounds.maxZ)return; + if(!level.hasChunkAt(pos))return; + BlockState now=level.getBlockState(pos); + if(EarthBlocks.isMapBlock(now) || (state.isAir() && !now.canOcclude()))return; + // Match the voxelizer's half-block vertical surface convention. + result.add(new MeshCut.Box(pos.getX()-ax,pos.getY()+shift-ay,pos.getZ()-az,pos.getX()+1-ax,pos.getY()+1+shift-ay,pos.getZ()+1-az)); + }); + result.sort(Comparator.comparingDouble(MeshCut.Box::x).thenComparingDouble(MeshCut.Box::y).thenComparingDouble(MeshCut.Box::z)); + return result; + } + public static void render(WorldRenderContext ctx) { + if(!ctx.world().dimension().equals(Level.OVERWORLD) || !MapRenderer.INSTANCE.enabled() || SpaceView.active())return; + surfaces.renderMapCuts(ctx.camera().getPosition(),ctx.matrixStack().last().pose(),ctx.world()::getBlockState,ctx.world()::hasChunkAt,ctx.world()); + } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/MapRenderer.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/MapRenderer.java new file mode 100644 index 0000000..b1ebc83 --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/MapRenderer.java @@ -0,0 +1,472 @@ +package dev.realworldmc.client; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.VertexBuffer; +import dev.realworldmc.EarthBlocks; +import dev.realworldmc.RealWorldMC; +import dev.realworldmc.EarthRegions; +import dev.realworldmc.RegionsPayload; +import dev.realworldmc.ServiceClient; +import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.client.renderer.culling.Frustum; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; +import org.joml.Matrix4f; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Streams render tiles from the service around the camera and draws them into the world. + * Selection and downloads happen on background threads, GPU work on the render thread. + */ +public final class MapRenderer { + public static final MapRenderer INSTANCE = new MapRenderer(); + + private static final int MAX_UPLOADS_PER_FRAME = 3; + private static final int MAX_REFRESH_PER_FRAME = 4; + /** Extra tiles kept on the GPU beyond the current view. */ + private static final int CACHE_EXTRA = 600; + + private final ExecutorService io = Executors.newFixedThreadPool(6, r -> { + Thread t = new Thread(r, "RealWorldMC tile loader"); + t.setDaemon(true); + return t; + }); + // Flight selection must not wait behind a queue of obsolete detail downloads. + private final ExecutorService selector = Executors.newSingleThreadExecutor(r -> { + Thread t=new Thread(r,"RealWorldMC view selector");t.setDaemon(true);return t; + }); + + /** All places of the world (from the server); null when not in an RealWorldMC world. */ + private volatile List regions; + + /** Region metadata shared with optional map overlays. */ + public List getRegions() { + return regions; + } + + /** Region the camera is in; tiles are only streamed for this one. */ + private volatile EarthRegions.Region current; + + + /** Bumped whenever the region changes so stale downloads are dropped. */ + private volatile int epoch; + + private final Map loaded = new HashMap<>(); + private final Set loading = java.util.concurrent.ConcurrentHashMap.newKeySet(); + private record TileRequest(int epoch, int id) {} + private record Upload(int epoch,TileData data) {} + private final ConcurrentLinkedQueue uploadQueue = new ConcurrentLinkedQueue<>(); + /** Tiles drawn this frame. */ + private List displayed = new ArrayList<>(); + private record Retained(EarthRegions.Region region,List tiles,String credits) {} + private volatile Retained retained; + private boolean preserveLanding; + public void preserveForLanding() { preserveLanding=true; } + public void cancelLanding() { preserveLanding=false; } + public void finishLanding(EarthRegions.Region region) { + if(!java.util.Objects.equals(region,current))switchRegion(region); + preserveLanding=false; + } + /** A tile the service wants drawn; chain = ancestors with content, nearest first. */ + private record Want(int id, boolean fine, int[] chain) { + int parent() { + return chain.length > 0 ? chain[0] : 0; + } + } + + /** Latest selection from the service. */ + private volatile List wanted = List.of(); + /** Ids of wanted tiles and their parents; queued downloads for anything else are skipped. */ + private volatile Set wantedIds = Set.of(); + /** Frame number a tile was last drawn in (for keeping a cache of recently seen tiles). */ + private final Map lastDrawn = new HashMap<>(); + private long frame; + private final AtomicBoolean selecting = new AtomicBoolean(); + private int tickCounter; + + public volatile String status = ""; + public volatile String attributionText = "Google, RealWorldMC"; + + public void setRegions(RegionsPayload payload) { + regions = payload.regions(); + dev.realworldmc.RegionTravel.clientRegions=regions; + RealWorldMC.LOGGER.info("RealWorldMC: {} place(s) in this world", regions.size()); + } + + /** True while in an RealWorldMC world. */ + public boolean enabled() { + return regions != null; + } + + private void switchRegion(EarthRegions.Region region) { + if(current!=null && region!=null && current.index()!=region.index()) { + var delta=dev.realworldmc.Geo.geodeticToMc(current.latitude(),current.longitude(),current.groundHeight(),region.latitude(),region.longitude(),region.groundHeight()); + if(Math.sqrt(delta[0]*delta[0]+delta[2]*delta[2]+Math.pow(delta[1]-64,2))<30_000)preserveLanding=true; + } + + if(!preserveLanding)releaseRetained(); + if(preserveLanding && current!=null && region!=null && !displayed.isEmpty()) { + releaseRetained(); + var tiles=new ArrayList(); + synchronized(loaded) { for(int id:displayed) {var tile=loaded.remove(id);if(tile!=null)tiles.add(tile);} } + retained=new Retained(current,tiles,attributionText); + } + + resetTiles(); + current = region; + if(region!=null)preserveLanding=false; + } + + /** Render thread. */ + public void clear() { + regions = null; + dev.realworldmc.RegionTravel.clientRegions=List.of(); + releaseRetained();preserveLanding=false; + resetTiles(); + } + public void invalidateDamage() { markDirty(t -> true); } + private void releaseRetained() { + if(retained==null)return; + var old=retained;retained=null; + RenderSystem.recordRenderCall(()->old.tiles().forEach(MapTile::close)); + } + + private void resetTiles() { + synchronized (uploadQueue) { + epoch++; + uploadQueue.clear(); + loading.clear(); + } + current = null; + wanted = List.of(); + displayed = new ArrayList<>(); + wantedIds = Set.of(); + List old; + synchronized(loaded) {old=List.copyOf(loaded.values());loaded.clear();lastDrawn.clear();} + RenderSystem.recordRenderCall(()->old.forEach(MapTile::close)); + attributionText = retained==null ? "Google, RealWorldMC" : retained.credits(); + status = ""; + } + + private boolean active(ClientLevel level) { + return current != null && level != null && level.dimension() == Level.OVERWORLD; + } + + // ---------------------------------------------------------------- client tick: selection + downloads + + public void tick(Minecraft mc) { + SpaceFlight.completeArrival(mc); + if(SpaceFlight.body()!=CelestialBody.EARTH)return; + List all = regions; + if (all == null || mc.level == null || mc.gameRenderer == null || mc.level.dimension() != Level.OVERWORLD) return; + if (!status.isEmpty()) mc.gui.setOverlayMessage(dev.realworldmc.RWMessages.message(status), false); + Vec3 camAbs = mc.gameRenderer.getMainCamera().getPosition(); + EarthRegions.Region region = EarthRegions.at(all,camAbs.x,camAbs.z); + if(region!=null && !Double.isFinite(region.groundHeight()))region=null; + if (!java.util.Objects.equals(region, current)) switchRegion(region); + if (region == null) return; + if (++tickCounter % (mc.player!=null && (mc.player.isFallFlying() || mc.player.getAbilities().flying)?5:10) != 0 || !selecting.compareAndSet(false, true)) return; + // Use the same interpolation time as the camera; mixing current-tick altitude with an older camera jitters selection. + float partial=mc.getFrameTime(); + Vec3 cam = SpaceFlight.mapCamera(camAbs, region, partial).subtract(region.offsetX(), 0, region.offsetZ()); + EarthRegions.Region o = region; + int myEpoch = epoch; + boolean space=SpaceFlight.anchored(); + // Predict one second of local travel, bounded to avoid distant requests after teleports. + Vec3 motion=mc.player==null || space ? Vec3.ZERO : mc.player.getDeltaMovement(); + Vec3 ahead=new Vec3(motion.x,0,motion.z).scale(20); + if(ahead.length()>256)ahead=ahead.normalize().scale(256); + final Vec3 lookAhead=ahead; + selector.execute(() -> { + try { + String q = String.format(Locale.ROOT, "/render/select?%s&x=%.2f&y=%.2f&z=%.2f&space=%d&aheadX=%.2f&aheadZ=%.2f&fineRadius=%d&far=%d&maxTiles=%d&maxSse=%d", + ServiceClient.originQuery(o.latitude(), o.longitude(), o.groundHeight()), cam.x, cam.y, cam.z, space ? 1 : 0, lookAhead.x, lookAhead.z, EarthSettings.getFineRadius(), EarthSettings.getFar(), EarthSettings.getMaxTiles(), EarthSettings.getMaxSse()); + JsonObject res = ServiceClient.getJson(q, Duration.ofSeconds(30)); + if (myEpoch != epoch) return; + List list = new ArrayList<>(); + for (JsonElement e : res.getAsJsonArray("tiles")) { + JsonObject t = e.getAsJsonObject(); + JsonArray c = t.getAsJsonArray("chain"); + int[] chain = new int[c == null ? 0 : c.size()]; + for (int i = 0; i < chain.length; i++) chain[i] = c.get(i).getAsInt(); + list.add(new Want(t.get("id").getAsInt(), t.get("fine").getAsBoolean(), chain)); + } + List attr = new ArrayList<>(); + JsonArray a = res.getAsJsonArray("attribution"); + if (a != null) for (JsonElement e : a) attr.add(e.getAsString()); + if (!attr.contains("Google")) attr.add(0, "Google"); + if (!attr.contains("RealWorldMC")) attr.add("RealWorldMC"); + attributionText = String.join(", ", attr); + var prior=retained; + if(prior!=null && !attributionText.equals(prior.credits()))attributionText=prior.credits()+", "+attributionText; + Set ids = new HashSet<>(); + for (Want t : list) { + ids.add(t.id()); + for(int i=0;i { + if (upload.epoch() == epoch && ids.contains(upload.data().id)) return false; + loading.remove(new TileRequest(upload.epoch(), upload.data().id)); + return true; + }); + } + wanted = list; + status = ""; + // Parents first: they are coarse, load fast and fill the view while the detail streams in. + for (Want t : list) if(t.chain().length>1)requestTile(t.chain()[1],false,o,myEpoch); + for (Want t : list) if (t.parent() != 0) requestTile(t.parent(), false, o, myEpoch); + for (Want t : list) requestTile(t.id(), t.fine(), o, myEpoch); + } catch (Exception e) { + if(myEpoch!=epoch)return; + status = "Map connection interrupted. Check /earth setup."; + ServiceClient.ensureRunning(); + } finally { + selecting.set(false); + } + }); + } + + private void requestTile(int id, boolean fine, EarthRegions.Region o, int myEpoch) { + synchronized (loaded) { + if (loaded.containsKey(id)) return; + } + TileRequest request = new TileRequest(myEpoch, id); + if (loading.size() >= 128 || !loading.add(request)) return; + io.execute(() -> { + boolean queued = false; + try { + if (myEpoch != epoch || !wantedIds.contains(id)) return; // flew past it already + byte[] bytes = ServiceClient.getBytes(String.format(Locale.ROOT, "/render/tile?%s&id=%d", + ServiceClient.originQuery(o.latitude(), o.longitude(), o.groundHeight()), id), Duration.ofSeconds(60)); + if (myEpoch == epoch && wantedIds.contains(id)) { + TileData data = TileData.parse(id, fine, bytes, o.offsetX(), o.offsetZ()); + synchronized (uploadQueue) { + if (myEpoch == epoch && wantedIds.contains(id)) { + uploadQueue.add(new Upload(myEpoch, data)); queued = true; + } + } + } + } catch (Exception e) { + RealWorldMC.LOGGER.warn("Tile {} failed: {}", id, e.toString()); + } finally { + // A queued tile stays "loading" until uploadAndSwitch takes it. Uploads only happen while the + // world renders (not behind e.g. Xaero's world map), and selection keeps running meanwhile; + // without this the same tiles were fetched again every selection until the heap ran out. + if (!queued) loading.remove(request); + } + }); + } + + // ---------------------------------------------------------------- render thread + + private void uploadAndSwitch(ClientLevel level) { + for (int i = 0; i < MAX_UPLOADS_PER_FRAME; i++) { + Upload upload=uploadQueue.poll(); + if(upload==null)break; + loading.remove(new TileRequest(upload.epoch(), upload.data().id)); + if(upload.epoch()!=epoch)continue; + TileData d=upload.data(); + synchronized (loaded) { + if (!loaded.containsKey(d.id)) loaded.put(d.id, new MapTile(d, level)); + } + } + + // Wanted tiles are grouped by their parent. A complete group is drawn as is; an incomplete + // one is covered by its nearest already loaded ancestor ("cover"), so the view never has + // holes. Everything below a drawn cover is hidden to avoid two LODs on top of each other. + List want = wanted; + Map> groups = new HashMap<>(); + Map ancestorsOf = new HashMap<>(); + for (Want w : want) { + groups.computeIfAbsent(w.parent(), k -> new ArrayList<>()).add(w); + int[] c = w.chain(); + for (int i = 0; i < c.length; i++) ancestorsOf.putIfAbsent(c[i], java.util.Arrays.copyOfRange(c, i + 1, c.length)); + } + LinkedHashSet draw = new LinkedHashSet<>(); + boolean coveredAll=!want.isEmpty(); + synchronized (loaded) { + Set covers = new HashSet<>(); + List members = new ArrayList<>(); + for (Map.Entry> g : groups.entrySet()) { + boolean complete = true; + for (Want w : g.getValue()) if (!loaded.containsKey(w.id())) complete = false; + int cover = 0; + if (!complete) { + for (int a : g.getValue().get(0).chain()) { + if (loaded.containsKey(a)) { + cover = a; + break; + } + } + } + if (cover != 0) covers.add(cover); + else { + if(!complete)coveredAll=false; + for (Want w : g.getValue()) if (loaded.containsKey(w.id())) members.add(w); + } + } + for (Integer c : covers) { + boolean underAnother = false; + for (int a : ancestorsOf.getOrDefault(c, new int[0])) if (covers.contains(a)) underAnother = true; + if (!underAnother) draw.add(c); + } + for (Want w : members) { + boolean covered = false; + for (int a : w.chain()) if (draw.contains(a)) covered = true; + if (!covered) draw.add(w.id()); + } + frame++; + // Keep the last complete view until replacement children or coarse covers are ready. + // Never paint overlapping parent/child LODs, which causes depth flicker. + if(coveredAll || displayed.isEmpty())displayed=new ArrayList<>(draw); + if(coveredAll) {releaseRetained(); if(!SpaceFlight.enabled())SpaceFlight.terrainReady();} + for (Integer id : displayed) lastDrawn.put(id, frame); + + // Keep recently drawn tiles around (turning back must not reload), evict the oldest beyond the budget. + if (frame % 60 == 0 && loaded.size() > want.size() * 2 + CACHE_EXTRA) { + Set keep = new HashSet<>(displayed); + for (Want w : want) { + keep.add(w.id()); + for(int i=0;i candidates = new ArrayList<>(); + for (Integer id : loaded.keySet()) if (!keep.contains(id)) candidates.add(id); + candidates.sort((a, b) -> Long.compare(lastDrawn.getOrDefault(a, 0L), lastDrawn.getOrDefault(b, 0L))); + int excess = loaded.size() - (want.size() * 2 + CACHE_EXTRA); + for (int i = 0; i < Math.min(excess, candidates.size()); i++) { + Integer id = candidates.get(i); + loaded.remove(id).close(); + lastDrawn.remove(id); + } + } + } + } + + public void render(WorldRenderContext ctx) { + if (!SpaceView.active()) draw(ctx, false); + } + + public void renderSpace(WorldRenderContext ctx) { + if (!SpaceView.active() || !active(ctx.world())) return; + double altitude=SpaceFlight.altitude(ctx.tickDelta()); + SpaceView.sky(ctx.matrixStack().last().pose(),ctx.projectionMatrix(),SpaceFlight.body()==CelestialBody.EARTH?altitude:100_000); + // Orbital projection cannot compare depth written with the local-world projection. + RenderSystem.depthMask(true); + RenderSystem.clear(org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT, Minecraft.ON_OSX); + if(SpaceFlight.body()==CelestialBody.EARTH)draw(ctx,true); + else PlanetRenderer.render(ctx); + SpaceDestinations.project(ctx); + // Only the distant map used the orbital projection. Restore near-world depth before entities. + RenderSystem.depthMask(true); + RenderSystem.clear(org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT, Minecraft.ON_OSX); + } + + private void draw(WorldRenderContext ctx, boolean space) { + ClientLevel level = ctx.world(); + if (!active(level)) return; + uploadAndSwitch(level); + + int refreshed = 0; + for (Integer id : displayed) { + MapTile t = loaded.get(id); + if (t != null && t.dirty && refreshed++ < MAX_REFRESH_PER_FRAME) t.refresh(level); + } + + Vec3 cam = ctx.camera().getPosition(); + Frustum frustum = ctx.frustum(); + Matrix4f proj = ctx.projectionMatrix(); + Matrix4f view = ctx.matrixStack().last().pose(); + if (space) { + float partial = ctx.tickDelta(); + proj = SpaceView.projection(proj, SpaceFlight.altitude(partial)); + cam = SpaceFlight.mapCamera(cam, current, partial); + view = new Matrix4f(view).rotate(new org.joml.Quaternionf(SpaceFlight.orbitRotation(partial))); + frustum = new Frustum(view, proj); + frustum.prepare(cam.x, cam.y, cam.z); + } + List tiles; + if(retained!=null && !space) { + tiles=retained.tiles(); + cam=RegionFrame.point(cam,current,retained.region()); + view=new Matrix4f(view).rotate(new org.joml.Quaternionf().setFromNormalized(RegionFrame.rotation(retained.region(),current))); + frustum=new Frustum(view,proj);frustum.prepare(cam.x,cam.y,cam.z); + } else { + tiles=new ArrayList<>();for(int id:displayed){var tile=loaded.get(id);if(tile!=null)tiles.add(tile);} + } + float partial = ctx.tickDelta(); + float light = level.getSkyDarken(partial); + + RenderSystem.setShader(GameRenderer::getPositionTexShader); + ShaderInstance shader = RenderSystem.getShader(); + if (shader == null) return; + RenderSystem.setShaderColor(light, light, light, 1f); + RenderSystem.enableDepthTest(); + RenderSystem.depthMask(true); + RenderSystem.disableBlend(); + RenderSystem.disableCull(); + + for (MapTile t : tiles) { + if (t == null || (frustum != null && !frustum.isVisible(t.bounds))) continue; + Matrix4f mv = new Matrix4f(view).translate( + (float) (t.data.anchorX - cam.x), (float) (t.data.anchorY - cam.y), (float) (t.data.anchorZ - cam.z)); + for (int i = 0; i < t.partCount(); i++) { + if (t.isEmpty(i)) continue; + RenderSystem.setShaderTexture(0, t.textureId(i)); + VertexBuffer vb = t.buffer(i); + vb.bind(); + vb.drawWithShader(mv, proj, shader); + } + } + VertexBuffer.unbind(); + RenderSystem.setShaderColor(1f, 1f, 1f, 1f); + RenderSystem.enableCull(); + } + + /** A block changed on the client: if a map block appeared or vanished, re-mask affected tiles. */ + public void onBlockChanged(BlockPos pos, BlockState before, BlockState after) { + if (current == null || (!MapDamage.tracked(pos) && EarthBlocks.isMapBlock(before) == EarthBlocks.isMapBlock(after))) return; + markDirty(t -> t.contains(pos)); + } + + public void onChunkLoaded(ChunkPos chunk) { + if (current == null) return; + double x0 = chunk.getMinBlockX(), z0 = chunk.getMinBlockZ(); + markDirty(t -> t.bounds.maxX >= x0 && t.bounds.minX <= x0 + 16 && t.bounds.maxZ >= z0 && t.bounds.minZ <= z0 + 16); + } + + private void markDirty(java.util.function.Predicate test) { + RenderSystem.recordRenderCall(() -> { + for (MapTile t : loaded.values()) if (test.test(t)) t.dirty = true; + }); + } + + public boolean readyAt(double x,double z){return current!=null && current.index()==EarthRegions.indexAt(x,z) && !displayed.isEmpty();} + public int displayedCount() { + return displayed.size(); + } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/MapTile.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/MapTile.java new file mode 100644 index 0000000..e23a970 --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/MapTile.java @@ -0,0 +1,153 @@ +package dev.realworldmc.client; + +import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexBuffer; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.core.BlockPos; +import net.minecraft.world.phys.AABB; + +import org.lwjgl.opengl.EXTTextureFilterAnisotropic; +import org.lwjgl.opengl.GL; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL30; + + +/** GPU side of a tile: one vertex buffer + texture per glTF primitive. Render thread only. */ +public final class MapTile { + public final TileData data; + public final AABB bounds; + private final VertexBuffer[] buffers; + private final DynamicTexture[] textures; + private java.util.List cuts; + private dev.realworldmc.MeshCut.Index cutIndex; + private final boolean[] empty; + public boolean dirty; + + public MapTile(TileData data, ClientLevel level) { + this(data,MapDamage.cuts(new AABB(data.minX,data.minY,data.minZ,data.maxX,data.maxY,data.maxZ),level,data.anchorX,data.anchorY,data.anchorZ)); + } + static MapTile withCuts(TileData data,java.util.List damage) {return new MapTile(data,damage);} + private MapTile(TileData data, java.util.List damage) { + this.data = data; + this.bounds = new AABB(data.minX, data.minY, data.minZ, data.maxX, data.maxY, data.maxZ); + int n = data.parts.length; + buffers = new VertexBuffer[n]; + textures = new DynamicTexture[n]; + cuts=java.util.List.copyOf(damage); + cutIndex=new dev.realworldmc.MeshCut.Index(cuts); + empty = new boolean[n]; + for (int i = 0; i < n; i++) { + TileData.Part part = data.parts[i]; + NativeImage image; + if (part.pixels != null) { + image = new NativeImage(part.texWidth, part.texHeight, false); + for (int y = 0; y < part.texHeight; y++) { + for (int x = 0; x < part.texWidth; x++) image.setPixelRGBA(x, y, part.pixels[y * part.texWidth + x]); + } + } else { + image = new NativeImage(1, 1, false); + image.setPixelRGBA(0, 0, part.fallbackAbgr); + } + textures[i] = new DynamicTexture(image); + enableMipmaps(textures[i].getId(), image.getWidth(), image.getHeight()); + part.pixels = null; + buffers[i] = new VertexBuffer(VertexBuffer.Usage.STATIC); + + upload(i); + } + } + + private static float maxAnisotropy = -1; + + /** Trilinear mipmaps + anisotropic filtering: keeps photo textures sharp and flicker-free at grazing angles. */ + private static void enableMipmaps(int id, int w, int h) { + GlStateManager._bindTexture(id); + int levels = 31 - Integer.numberOfLeadingZeros(Math.max(w, h)); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, levels); + GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); + if (maxAnisotropy < 0) { + maxAnisotropy = GL.getCapabilities().GL_EXT_texture_filter_anisotropic + ? GL11.glGetFloat(EXTTextureFilterAnisotropic.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0; + } + if (maxAnisotropy > 0) { + GL11.glTexParameterf(GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, Math.min(16f, maxAnisotropy)); + } + } + + /** Rebuild only when confirmed damage volumes change, including coarse fallback tiles. */ + public void refresh(ClientLevel level) { + dirty=false; + var now=MapDamage.cuts(bounds,level,data.anchorX,data.anchorY,data.anchorZ); + if(now.equals(cuts))return; + cuts=now;cutIndex=new dev.realworldmc.MeshCut.Index(cuts); + for(int i=0;i(3); + for(int k=0;k<3;k++){int o=offset+k*5;triangle.add(new dev.realworldmc.MeshCut.Vertex(source[o],source[o+1],source[o+2],source[o+3],source[o+4]));} + java.util.List> polygons=java.util.List.of(triangle); + for(var box:candidates){ + var remaining=new java.util.ArrayList>(); + for(var polygon:polygons)remaining.addAll(dev.realworldmc.MeshCut.subtract(polygon,box)); + polygons=remaining;if(polygons.isEmpty())break; + } + for(var polygon:polygons)for(int t=1;t= bounds.minX - 1 && pos.getX() <= bounds.maxX && pos.getY() >= bounds.minY - 2 && pos.getY() <= bounds.maxY + && pos.getZ() >= bounds.minZ - 1 && pos.getZ() <= bounds.maxZ; + } + + public void close() { + for (VertexBuffer b : buffers) b.close(); + for (DynamicTexture t : textures) t.close(); + } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/Meshes.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/Meshes.java new file mode 100644 index 0000000..009afe2 --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/Meshes.java @@ -0,0 +1,15 @@ +package dev.realworldmc.client; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexFormat; + +/** 1.20.1 has one shared tesselator builder: upload each mesh before beginning the next. */ +final class Meshes { + private Meshes() {} + static BufferBuilder begin(VertexFormat.Mode mode, VertexFormat format) { + BufferBuilder builder = Tesselator.getInstance().getBuilder(); + builder.begin(mode, format); + return builder; + } +} diff --git a/mod-1.20.1/src/client/java/dev/realworldmc/client/PanoramaRenderer.java b/mod-1.20.1/src/client/java/dev/realworldmc/client/PanoramaRenderer.java new file mode 100644 index 0000000..72d957d --- /dev/null +++ b/mod-1.20.1/src/client/java/dev/realworldmc/client/PanoramaRenderer.java @@ -0,0 +1,362 @@ +package dev.realworldmc.client; + +import com.google.gson.*; +import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.*; +import dev.realworldmc.RealWorldMC; +import dev.realworldmc.ServiceClient; +import dev.realworldmc.PanoramaRoom; +import dev.realworldmc.PanoramaPayload; +import dev.realworldmc.PanoramaActionPayload; +import dev.realworldmc.StreetNavigation; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; +import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; +import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext; +import net.minecraft.client.KeyMapping; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.lwjgl.glfw.GLFW; +import org.lwjgl.opengl.GL11; +import java.io.ByteArrayInputStream; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.*; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.concurrent.CompletableFuture; +import javax.imageio.ImageIO; + +/** A fixed photo origin with approximate ground reprojection. Minecraft owns foreground gameplay. */ +public final class PanoramaRenderer { + public static final PanoramaRenderer INSTANCE=new PanoramaRenderer(); + private static final HttpClient HTTP=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); + private static final ResourceLocation TEXTURE=RealWorldMC.id("dynamic/streetview_sky"); + private VertexBuffer sphere, fadingSphere; + private ResourceLocation currentTexture=TEXTURE, fadingTexture; + private long fadeStarted; + private net.minecraft.world.phys.Vec3 lastOffset=net.minecraft.world.phys.Vec3.ZERO,fadeOffset=net.minecraft.world.phys.Vec3.ZERO; + private JsonObject metadata; + private dev.realworldmc.EarthRegions.Region mapRegion; + private String copyright="",report="",status=""; + private boolean session,loading,walking,walkingRequested,sourcesVisible; + private int generation, ticket, pendingTicket, entryReadyTicket; + private NativeImage prepared; + private JsonObject preparedMetadata; + private boolean arrivalGuard; + private boolean forwardWasDown, approaching, cancelSent, walkBlocked; + private int walkingDestination = -1; + private long walkRetryAt; + private double anchorX,anchorY,anchorZ; + private double groundY,eyeHeight=2.5; + private long noticeUntil; + private final KeyMapping[] movement=new KeyMapping[4]; + private KeyMapping reportKey,walkKey,sourcesKey; + private final int[] offsets={0,180,-90,90}; + + public void registerKeys(){ + String[] names={"forward","backward","left","right"};int[] keys={GLFW.GLFW_KEY_UP,GLFW.GLFW_KEY_DOWN,GLFW.GLFW_KEY_LEFT,GLFW.GLFW_KEY_RIGHT}; + for(int i=0;i<4;i++)movement[i]=KeyBindingHelper.registerKeyBinding(new KeyMapping("key.realworldmc.photo."+names[i],InputConstants.Type.KEYSYM,keys[i],"key.categories.realworldmc")); + reportKey=KeyBindingHelper.registerKeyBinding(new KeyMapping("key.realworldmc.photo.report",InputConstants.Type.KEYSYM,GLFW.GLFW_KEY_F8,"key.categories.realworldmc")); + walkKey=KeyBindingHelper.registerKeyBinding(new KeyMapping("key.realworldmc.photo.walk",InputConstants.Type.KEYSYM,GLFW.GLFW_KEY_V,"key.categories.realworldmc")); + sourcesKey=KeyBindingHelper.registerKeyBinding(new KeyMapping("key.realworldmc.photo.sources",InputConstants.Type.KEYSYM,GLFW.GLFW_KEY_F7,"key.categories.realworldmc")); + } + public boolean active(){var level=Minecraft.getInstance().level;return session && level!=null && level.dimension().equals(PanoramaRoom.ROOM);} + public boolean walking(){return walking;} + public dev.realworldmc.EarthRegions.Region mapRegion(){return active()?mapRegion:null;} + public int tilesPerPhoto(){return metadata!=null && metadata.has("rwmcTileCount")?metadata.get("rwmcTileCount").getAsInt():0;} + /** Reuse the existing arrow bindings; duplicate registrations would steal photo navigation keys. */ + public KeyMapping flightSpeedKey(boolean faster) { return movement[faster ? 0 : 1]; } + public double groundY(){return groundY;} + public void clear(){ + entryReadyTicket=0;if(StreetExitTransition.entering())StreetExitTransition.clear(); + if(Minecraft.getInstance().player!=null)Minecraft.getInstance().player.noPhysics=Minecraft.getInstance().player.isSpectator(); + arrivalGuard=false;mapRegion=null;generation++;session=false;loading=false;metadata=null;status="";report="";copyright="";forwardWasDown=false; + walking=false;walkingRequested=false;sourcesVisible=false;noticeUntil=0;approaching=false;cancelSent=false;walkingDestination=-1;walkRetryAt=0;walkBlocked=false; + pendingTicket=0;ticket=0;discardPrepared(); + if(sphere!=null){sphere.close();sphere=null;} + finishFade();currentTexture=TEXTURE;lastOffset=net.minecraft.world.phys.Vec3.ZERO; + Minecraft.getInstance().getTextureManager().release(TEXTURE); + Minecraft.getInstance().getTextureManager().release(RealWorldMC.id("dynamic/streetview_next")); + PhotoEditsRenderer.INSTANCE.clear(); + } + private void discardPrepared(){if(prepared!=null){prepared.close();prepared=null;}preparedMetadata=null;} + private void action(int id,String type,String pano){ + if(ClientPlayNetworking.canSend(PanoramaActionPayload.TYPE))ClientPlayNetworking.send(new PanoramaActionPayload(id,type,pano)); + } + public void receive(PanoramaPayload payload){ + Minecraft mc=Minecraft.getInstance(); + switch(payload.phase()){ + case "depart" -> {generation++;discardPrepared();loading=false;approaching=false;walkingRequested=false;StreetExitTransition.begin();} + case "arrive" -> StreetExitTransition.arrive(); + case "depart-cancel" -> StreetExitTransition.clear(); + case "clear" -> clear(); + case "anchor" -> { + if (session && payload.ticket()==ticket) { + viewSettings(payload); + VertexBuffer next=buildSphere(metadata);if(sphere!=null)sphere.close();sphere=next; + } + } + case "movement" -> { + if (session && payload.ticket()==ticket) { + viewSettings(payload);walkingRequested=false; + mc.player.setNoGravity(true);mc.player.setDeltaMovement(0,0,0); + mc.player.setPos(anchorX,walking?groundY:anchorY,anchorZ); + notice(walking?"Walk · Leave 3×3 to travel":"Center · Arrows to travel"); + } + } + case "loading" -> {generation++;discardPrepared();pendingTicket=payload.ticket();loading=true;status=payload.metadata();} + case "error" -> {if(payload.ticket()==pendingTicket || payload.ticket()==ticket){entryReadyTicket=0;if(StreetExitTransition.entering())StreetExitTransition.clear();generation++;discardPrepared();loading=false;walkingRequested=false;approaching=false;cancelSent=false;walkingDestination=-1;walkRetryAt=net.minecraft.Util.getMillis()+2000;walkBlocked=true;notice(payload.metadata());}} + case "prepare" -> { + if(payload.ticket()!=pendingTicket)return; + try{load(JsonParser.parseString(payload.metadata()).getAsJsonObject(),payload.ticket());} + catch(Exception e){loading=false;action(payload.ticket(),"failed","");} + } + case "commit" -> { + if(payload.ticket()!=pendingTicket || prepared==null || preparedMetadata==null)return; + try{ + viewSettings(payload); + VertexBuffer next=buildSphere(metadata); + finishFade(); + ResourceLocation nextTexture=currentTexture.equals(TEXTURE)?RealWorldMC.id("dynamic/streetview_next"):TEXTURE; + mc.getTextureManager().release(nextTexture); + DynamicTexture texture=new DynamicTexture(prepared);prepared=null;texture.setFilter(true,false);mc.getTextureManager().register(nextTexture,texture); + if(sphere!=null){fadingSphere=sphere;fadingTexture=currentTexture;fadeOffset=lastOffset;fadeStarted=net.minecraft.Util.getMillis();} + else {if(sphere!=null)sphere.close();mc.getTextureManager().release(currentTexture);} + sphere=next;currentTexture=nextTexture;preparedMetadata=null; + copyright=text(metadata,"copyright","Google");report=text(metadata,"reportProblemLink",""); + arrivalGuard=session && walking;ticket=payload.ticket();session=true;loading=false;approaching=false;cancelSent=false;walkingDestination=-1;walkRetryAt=net.minecraft.Util.getMillis()+500;walkBlocked=false;forwardWasDown=mc.options.keyUp.isDown(); + anchorX=payload.x();anchorY=payload.y();anchorZ=payload.z(); + if(StreetExitTransition.entering())StreetExitTransition.arrive(); + walkingRequested=false;notice("Street View ready · /earth back returns"); + RealWorldMC.LOGGER.debug("Street View photograph committed at {}, {}, {}",anchorX,anchorY,anchorZ); + }catch(Exception e){if(StreetExitTransition.entering())StreetExitTransition.clear();discardPrepared();loading=false;notice("Photo upload failed; /earth back returns.");RealWorldMC.LOGGER.error("Street View texture upload failed",e);} + } + } + } + private void viewSettings(PanoramaPayload payload){ + metadata=JsonParser.parseString(payload.metadata()).getAsJsonObject(); + anchorX=payload.x();anchorY=payload.y();anchorZ=payload.z(); + eyeHeight=number(metadata,"rwmcEyeHeight",2.5f); + groundY=metadata.has("rwmcGroundY")?metadata.get("rwmcGroundY").getAsDouble():anchorY+1.62-eyeHeight; + if(metadata.has("rwmcRegionIndex"))mapRegion=new dev.realworldmc.EarthRegions.Region(metadata.get("rwmcRegionIndex").getAsInt(),metadata.get("rwmcRegionLat").getAsDouble(),metadata.get("rwmcRegionLon").getAsDouble(),metadata.get("rwmcRegionHeight").getAsDouble());else mapRegion=null; + walking=metadata.has("rwmcWalking") && metadata.get("rwmcWalking").getAsBoolean(); + } + private void notice(String text){status=text;noticeUntil=net.minecraft.Util.getMillis()+6000;} + public void requestWalking(boolean enabled){ + if(loading || walkingRequested || StreetExitTransition.active())return; + walkingRequested=true;action(ticket,"walk",enabled?"on":"off"); + } + private static byte[] fetch(String path) throws Exception { + var r=HTTP.send(HttpRequest.newBuilder(URI.create(ServiceClient.photoBase() + "/native/"+path)).timeout(Duration.ofSeconds(90)).GET().build(),HttpResponse.BodyHandlers.ofByteArray()); + if(r.statusCode()!=200 || r.body().length>20_000_000)throw new IllegalStateException("Street View unavailable");return r.body(); + } + private void load(JsonObject data,int request){ + loading=true;status="Loading photo…";int generationNow=++generation; + Minecraft mc=Minecraft.getInstance(); + CompletableFuture.runAsync(()->{ + NativeImage image=null; + try{ + String pano=URLEncoder.encode(data.get("panoId").getAsString(),StandardCharsets.UTF_8); + var decoded=ImageIO.read(new ByteArrayInputStream(fetch("panorama?pano="+pano))); + if(decoded==null || decoded.getWidth()>4096 || decoded.getHeight()>2048)throw new IllegalStateException("Invalid panorama size"); + image=new NativeImage(decoded.getWidth(),decoded.getHeight(),false); + for(int y=0;y>16)&255)|((c&255)<<16)); + } + NativeImage ready=image;image=null; + mc.execute(()->{ + if(generationNow!=generation || request!=pendingTicket){ready.close();return;} + discardPrepared();prepared=ready;preparedMetadata=data;status="Ready · Waiting for travel"; + if(!session){StreetExitTransition.beginEntry();entryReadyTicket=request;} + else action(request,"ready",""); + }); + }catch(Exception e){RealWorldMC.LOGGER.warn("Street View photo download/decode failed",e);if(image!=null)image.close();mc.execute(()->{ + if(generationNow==generation && request==pendingTicket){loading=false;status="Photo loading failed. Previous stop retained.";action(request,"failed","");} + });} + }); + } + private static String text(JsonObject data,String key,String fallback){return data.has(key)?data.get(key).getAsString():fallback;} + private static float number(JsonObject data,String key,float fallback){return data.has(key)?data.get(key).getAsFloat():fallback;} + private static VertexBuffer buildSphere(JsonObject data){ + // Metadata heading points at the centre of the equirectangular image. + Matrix3f orientation=new Matrix3f().rotateY((float)Math.toRadians(-number(data,"heading",0))) + .rotateX((float)Math.toRadians(90-number(data,"tilt",90))).rotateZ((float)Math.toRadians(number(data,"roll",0))); + BufferBuilder b=Meshes.begin(VertexFormat.Mode.QUADS,DefaultVertexFormat.POSITION_TEX); + int columns=128,rows=64; + float height=number(data,"rwmcEyeHeight",2.5f); + for(int y=0;y0?.45*Math.tanh(length/1.5)/length:.3; + return new net.minecraft.world.phys.Vec3(delta.x*scale,0,delta.z*scale); + } + static net.minecraft.world.phys.Vec3 renderFeet(net.minecraft.world.entity.Entity player,float partial){return player.getPosition(partial);} + static net.minecraft.world.phys.Vec3 projectionOffset(net.minecraft.world.phys.Vec3 capture,net.minecraft.world.phys.Vec3 feet,net.minecraft.world.phys.Vec3 camera,boolean walking){ + var local=walkOffset(capture.subtract(feet),walking); + // Keep the road at its world height, including detached third-person cameras. + return new net.minecraft.world.phys.Vec3(local.x+feet.x-camera.x,capture.y-camera.y,local.z+feet.z-camera.z); + } + public void renderSky(WorldRenderContext ctx){ + if(!active() || sphere==null)return; + boolean cull=GL11.glIsEnabled(GL11.GL_CULL_FACE),blend=GL11.glIsEnabled(GL11.GL_BLEND),depth=GL11.glIsEnabled(GL11.GL_DEPTH_TEST),mask=GL11.glGetBoolean(GL11.GL_DEPTH_WRITEMASK); + float[] color=RenderSystem.getShaderColor().clone(); + int srcRgb=GL11.glGetInteger(org.lwjgl.opengl.GL14.GL_BLEND_SRC_RGB),dstRgb=GL11.glGetInteger(org.lwjgl.opengl.GL14.GL_BLEND_DST_RGB),srcAlpha=GL11.glGetInteger(org.lwjgl.opengl.GL14.GL_BLEND_SRC_ALPHA),dstAlpha=GL11.glGetInteger(org.lwjgl.opengl.GL14.GL_BLEND_DST_ALPHA); + try { + RenderSystem.disableCull();RenderSystem.disableBlend();RenderSystem.disableDepthTest();RenderSystem.depthMask(false);RenderSystem.setShaderColor(1,1,1,1); + RenderSystem.setShader(GameRenderer::getPositionTexShader);RenderSystem.setShaderTexture(0,currentTexture); + var offset=projectionOffset(cameraAnchor(),renderFeet(Minecraft.getInstance().player,ctx.tickDelta()),ctx.camera().getPosition(),walking); + lastOffset=offset; + float fade=Math.min(1,(net.minecraft.Util.getMillis()-fadeStarted)/250f);fade=fade*fade*(3-2*fade); + if(fadingSphere!=null && fade<1){ + RenderSystem.setShaderTexture(0,fadingTexture); + fadingSphere.bind();fadingSphere.drawWithShader(new Matrix4f(ctx.matrixStack().last().pose()).setTranslation(0,0,0).translate((float)fadeOffset.x,(float)fadeOffset.y,(float)fadeOffset.z),ctx.projectionMatrix(),RenderSystem.getShader()); + RenderSystem.enableBlend();RenderSystem.defaultBlendFunc();RenderSystem.setShaderColor(1,1,1,fade); + } else if(fadingSphere!=null)finishFade(); + RenderSystem.setShaderTexture(0,currentTexture); + sphere.bind();sphere.drawWithShader(new Matrix4f(ctx.matrixStack().last().pose()).setTranslation(0,0,0).translate((float)offset.x,(float)offset.y,(float)offset.z),ctx.projectionMatrix(),RenderSystem.getShader()); + }finally{ + VertexBuffer.unbind();RenderSystem.depthMask(mask);if(depth)RenderSystem.enableDepthTest();else RenderSystem.disableDepthTest(); + com.mojang.blaze3d.platform.GlStateManager._blendFuncSeparate(srcRgb,dstRgb,srcAlpha,dstAlpha); + if(cull)RenderSystem.enableCull();else RenderSystem.disableCull();if(blend)RenderSystem.enableBlend();else RenderSystem.disableBlend();RenderSystem.setShaderColor(color[0],color[1],color[2],color[3]); + } + } + private double[] headings(){ + if(metadata==null || !metadata.has("links"))return new double[0]; + JsonArray links=metadata.getAsJsonArray("links");double[] result=new double[links.size()]; + for(int i=0;i=0 && !loading)travel(selected); + return down; + } + private void walkingTravel(Minecraft mc) { + if (mc.screen != null) return; + double dx=mc.player.getX()-anchorX, dz=mc.player.getZ()-anchorZ; + double distance=Math.max(Math.abs(dx),Math.abs(dz)); + if(arrivalGuard) { if(distance<.8 || distance>=StreetNavigation.WALK_TRANSITION)arrivalGuard=false;else return; } + if (Math.max(Math.abs(dx),Math.abs(dz))=0 && next!=walkingDestination; + if (!cancelSent && pendingTicket!=ticket && (withdrew || changed)) { cancelSent=true; action(pendingTicket,"cancel",""); } + return; + } + if (loading || walkBlocked || net.minecraft.Util.getMillis()