diff --git a/.forgejo/workflows/arrakis-crysknife.yml b/.forgejo/workflows/arrakis-crysknife.yml new file mode 100644 index 00000000..a00c8363 --- /dev/null +++ b/.forgejo/workflows/arrakis-crysknife.yml @@ -0,0 +1,50 @@ +name: Arrakis Crysknife Build +on: + workflow_dispatch: + push: + branches: ['feat/jarvis-crysknife-*'] + +jobs: + crysknife: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Package the Arrakis J.A.R.V.I.S., Terrain and resource pack release + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p JarvisConnector test jar + gradle --no-daemon -p DuneTerrain test jar + python3 tools/plugin_pillager_abi.py JarvisConnector/build/libs/jarvistranslator.jar + python3 tools/verify-arrakis-terrain.py DuneTerrain/build/libs/DuneRealms-Terrain.jar DuneTerrain/src/test/resources/retained-arrakis-terrain.json + python3 tools/test_plugin_fleet_install.py -v + python3 tools/test_plugin_pillager_profile.py PillagerProfileTests -v + python3 tools/test_plugin_pack_properties.py -v + mkdir crysknife-artifacts + cp JarvisConnector/build/libs/jarvistranslator.jar DuneTerrain/build/libs/DuneRealms-Terrain.jar crysknife-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > crysknife-artifacts/SOURCE_COMMIT + python3 tools/build-unified-resourcepack.py --source "$GITHUB_SHA" --output "crysknife-artifacts/DuneRealms-Resources-${GITHUB_SHA}.zip" + python3 tools/write-plugin-manifest.py crysknife-artifacts "$GITHUB_SHA" + cp tools/install-plugin-fleet.py tools/plugin_menu_pack.py tools/plugin_backend_abi.py tools/plugin_pillager_abi.py tools/plugin_fleet_rollback.py tools/plugin_pack_properties.py tools/publish-plugin-menu.py crysknife-artifacts/ + cp JarvisConnector/src/test/resources/retained-jarvis-public-abi.json JarvisConnector/src/test/resources/medieval-factions-11.1-raid-api.json JarvisConnector/src/test/resources/worldguard-raid-api.json DuneTerrain/src/test/resources/retained-arrakis-terrain.json crysknife-artifacts/ + (cd crysknife-artifacts && sha256sum -- *.jar *.zip *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Arrakis-Crysknife + path: crysknife-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/arrakis-raw-spice.yml b/.forgejo/workflows/arrakis-raw-spice.yml new file mode 100644 index 00000000..991da2ed --- /dev/null +++ b/.forgejo/workflows/arrakis-raw-spice.yml @@ -0,0 +1,44 @@ +name: Arrakis Raw Spice Build +on: + workflow_dispatch: + push: + branches: ['fix/arrakis-raw-spice-*'] + +jobs: + raw-spice: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Verify the Arrakis JARVIS-only transition + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p JarvisConnector test jar + python3 tools/test_plugin_fleet_install.py -v + python3 tools/plugin_arrakis_raw_spice.py JarvisConnector/build/libs/jarvistranslator.jar + mkdir raw-spice-artifacts + cp JarvisConnector/build/libs/jarvistranslator.jar raw-spice-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > raw-spice-artifacts/SOURCE_COMMIT + python3 tools/write-plugin-manifest.py raw-spice-artifacts "$GITHUB_SHA" + cp tools/{install-plugin-fleet,plugin_arrakis_raw_spice,plugin_menu_pack,plugin_backend_abi,plugin_fleet_rollback,plugin_pack_properties,plugin_pillager_abi,reset-arrakis-terrain}.py raw-spice-artifacts/ + (cd raw-spice-artifacts && sha256sum -- *.jar *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Arrakis-Raw-Spice + path: raw-spice-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/arrakis-terrain.yml b/.forgejo/workflows/arrakis-terrain.yml new file mode 100644 index 00000000..18cace7b --- /dev/null +++ b/.forgejo/workflows/arrakis-terrain.yml @@ -0,0 +1,43 @@ +name: Arrakis Terrain Build +on: + workflow_dispatch: + +jobs: + terrain: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test and package the bounded Terrain release + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneTerrain test jar + python3 tools/test_arrakis_terrain_reset.py -v + python3 tools/verify-arrakis-terrain.py DuneTerrain/build/libs/DuneRealms-Terrain.jar DuneTerrain/src/test/resources/retained-arrakis-terrain.json + mkdir terrain-artifacts + cp DuneTerrain/build/libs/DuneRealms-Terrain.jar terrain-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > terrain-artifacts/SOURCE_COMMIT + python3 tools/write-plugin-manifest.py terrain-artifacts "$GITHUB_SHA" + cp tools/reset-arrakis-terrain.py tools/verify-arrakis-terrain.py tools/plugin_backend_abi.py terrain-artifacts/ + cp DuneTerrain/src/test/resources/retained-arrakis-terrain.json DuneTerrain/docs/ARRAKIS-RESET-20261129.md terrain-artifacts/ + (cd terrain-artifacts && sha256sum -- *.jar *.json *.py *.md SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Arrakis-Terrain + path: terrain-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/atm-ria-copy.yml b/.forgejo/workflows/atm-ria-copy.yml new file mode 100644 index 00000000..06970dd3 --- /dev/null +++ b/.forgejo/workflows/atm-ria-copy.yml @@ -0,0 +1,47 @@ +name: ATM RIA Copy and Sigma Goats +on: + workflow_dispatch: + push: + branches: ['fix/atm-ria-copy-*'] +jobs: + atm-ria-copy: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test ATM controls and preserve Sigma ecology + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneMenus test jar + gradle --no-daemon -p DuneTerrain test jar + mkdir atm-ria-copy + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_ria_copy import ATM, COPY + from plugin_wild_update import read_archive, write_archive + compiled=read_archive(Path('DuneMenus/build/libs/DuneMenus.jar').read_bytes()) + Path('atm-ria-copy/donor.zip').write_bytes(write_archive({p:compiled[p] for p in (ATM,COPY)})) + PY + cp tools/{plugin_ria_copy.py,plugin_wild_update.py,plugin_sigma_goats.py,SigmaGoatMerge.java} atm-ria-copy/ + printf '%s\n' "$GITHUB_SHA" > atm-ria-copy/SOURCE_COMMIT + (cd atm-ria-copy && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-ATM-RIA-Copy-Sigma-Goats + path: atm-ria-copy + if-no-files-found: error diff --git a/.forgejo/workflows/citizens-ready-barrier.yml b/.forgejo/workflows/citizens-ready-barrier.yml new file mode 100644 index 00000000..5c9c145f --- /dev/null +++ b/.forgejo/workflows/citizens-ready-barrier.yml @@ -0,0 +1,42 @@ +name: Citizens Load Barrier Build +on: + workflow_dispatch: + push: + branches: ['feat/citizens-ready-barrier-*'] + +jobs: + citizens-ready: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build and verify the scoped runtime fix + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneNPC test jar + gradle --no-daemon -p DuneLobby test jar + mkdir citizens-ready-artifacts + python3 tools/plugin_citizens_ready.py extract DuneNPC/build/libs/DuneRealms-NPC.jar DuneLobby/build/libs/DuneRealms-Lobby.jar citizens-ready-artifacts/citizens-ready.overlay.zip + cp tools/{plugin_citizens_ready,plugin_wild_update}.py citizens-ready-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > citizens-ready-artifacts/SOURCE_COMMIT + (cd citizens-ready-artifacts && sha256sum -- *.zip *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Citizens-Load-Barrier + path: citizens-ready-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/compact-menu-links.yml b/.forgejo/workflows/compact-menu-links.yml new file mode 100644 index 00000000..5610ac0f --- /dev/null +++ b/.forgejo/workflows/compact-menu-links.yml @@ -0,0 +1,52 @@ +name: Compact Dune Menu Overlay +on: + workflow_dispatch: + push: + branches: ['fix/compact-menu-links-*'] + +jobs: + compact-menu-links: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test menu routes and package only scoped UI classes + shell: bash + run: | + set -euo pipefail + for module in DuneRealmsGUI DuneMenus DuneLobby; do + gradle --no-daemon -p "$module" test jar + done + mkdir compact-menu-links + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_menu_polish import CLASSES + from plugin_wild_update import read_archive, write_archive + for module, jar in {"gui":"DuneRealmsGUI/build/libs/DunerealmsGUI.jar", "menus":"DuneMenus/build/libs/DuneMenus.jar", "lobby":"DuneLobby/build/libs/DuneRealms-Lobby.jar"}.items(): + source = read_archive(Path(jar).read_bytes()) + entries = list(CLASSES[module]) + if module in ("gui", "menus"): entries.append("com/dunerealms/" + module + "/MenuPolish.class") + Path("compact-menu-links/" + module + ".zip").write_bytes(write_archive({e:source[e] for e in entries})) + PY + cp tools/{plugin_menu_polish.py,plugin_wild_update.py,CompactMenuMerge.java} compact-menu-links/ + printf '%s\n' "$GITHUB_SHA" > compact-menu-links/SOURCE_COMMIT + (cd compact-menu-links && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Compact-Menu-Links + path: compact-menu-links + if-no-files-found: error diff --git a/.forgejo/workflows/compact-menus.yml b/.forgejo/workflows/compact-menus.yml new file mode 100644 index 00000000..24817da8 --- /dev/null +++ b/.forgejo/workflows/compact-menus.yml @@ -0,0 +1,44 @@ +name: Compact DuneMenus Build +on: + workflow_dispatch: + push: + branches: ['feat/dunemenus-compact-*'] + +jobs: + compact-menus: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Verify the DuneMenus-only transition + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneMenus test jar + python3 tools/test_plugin_fleet_install.py -v + python3 tools/plugin_compact_menus.py DuneMenus/build/libs/DuneMenus.jar + mkdir compact-menus-artifacts + cp DuneMenus/build/libs/DuneMenus.jar compact-menus-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > compact-menus-artifacts/SOURCE_COMMIT + python3 tools/write-plugin-manifest.py compact-menus-artifacts "$GITHUB_SHA" + cp tools/{install-plugin-fleet,plugin_compact_menus,plugin_menu_pack,plugin_backend_abi,plugin_fleet_rollback,plugin_pack_properties,plugin_pillager_abi}.py compact-menus-artifacts/ + (cd compact-menus-artifacts && sha256sum -- *.jar *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Compact-Menus + path: compact-menus-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/default-voice-permissions.yml b/.forgejo/workflows/default-voice-permissions.yml new file mode 100644 index 00000000..4c2ad551 --- /dev/null +++ b/.forgejo/workflows/default-voice-permissions.yml @@ -0,0 +1,33 @@ +name: Default Voice Permissions Operations Build +on: + workflow_dispatch: + push: + branches: ['ops/default-player-voice-permissions-*'] + +jobs: + default-voice-permissions: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Validate and package the scoped LuckPerms operation + shell: bash + run: | + set -euo pipefail + python3 tools/test_default_voice_permissions.py -v + mkdir default-voice-artifacts + cp tools/{set-default-voice-permissions,allow-giedi-nether-pearl}.py default-voice-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > default-voice-artifacts/SOURCE_COMMIT + (cd default-voice-artifacts && sha256sum -- *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Default-Voice-Permissions + path: default-voice-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/dune-staff.yml b/.forgejo/workflows/dune-staff.yml new file mode 100644 index 00000000..e08e919b --- /dev/null +++ b/.forgejo/workflows/dune-staff.yml @@ -0,0 +1,40 @@ +name: DuneStaff Build +on: + workflow_dispatch: + push: + branches: ['feat/staff-tools-*', 'feat/tweaks-ladders-staff-*'] + +jobs: + dune-staff: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build staff plugin and run its tests + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneStaff build + mkdir dune-staff-artifacts + cp DuneStaff/build/libs/DuneStaff.jar dune-staff-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > dune-staff-artifacts/SOURCE_COMMIT + (cd dune-staff-artifacts && sha256sum -- DuneStaff.jar SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-DuneStaff + path: dune-staff-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/dunechat.yml b/.forgejo/workflows/dunechat.yml new file mode 100644 index 00000000..c474ed6a --- /dev/null +++ b/.forgejo/workflows/dunechat.yml @@ -0,0 +1,42 @@ +name: DuneChat Build +on: + workflow_dispatch: + push: + branches: ['feat/dunechat-*'] + +jobs: + dunechat: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build and test DuneChat + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneChat test jar + python3 tools/test_plugin_dunechat.py -v + mkdir dunechat-artifacts + cp DuneChat/build/libs/DuneChat.jar dunechat-artifacts/ + cp tools/{plugin_dunechat,install-plugin-fleet,write-plugin-manifest,plugin_menu_pack,plugin_backend_abi,plugin_fleet_rollback,plugin_pack_properties,plugin_pillager_abi}.py dunechat-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > dunechat-artifacts/SOURCE_COMMIT + (cd dunechat-artifacts && sha256sum -- *.jar *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-DuneChat + path: dunechat-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/dunechest.yml b/.forgejo/workflows/dunechest.yml new file mode 100644 index 00000000..d1d4ac22 --- /dev/null +++ b/.forgejo/workflows/dunechest.yml @@ -0,0 +1,52 @@ +name: Planet DuneChest Build +on: + workflow_dispatch: + push: + branches: ['feat/dunechest-planets-*'] + +jobs: + dunechest: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build DuneChest and verify the planet pack + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneChest test jar paperValidationJar + python3 tools/test_plugin_fleet_install.py -v + python3 tools/test_plugin_pack_properties.py -v + mkdir chest-artifacts + cp DuneChest/build/libs/DuneChest.jar chest-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > chest-artifacts/SOURCE_COMMIT + pack="chest-artifacts/DuneRealms-Resources-${GITHUB_SHA}.zip" + python3 tools/build-unified-resourcepack.py --source "$GITHUB_SHA" --output "$pack" + echo "c15a074da8edcf1404f16fd284aa0d12d16104743ce99e5702dec48370b87b4d $pack" | sha256sum --check + python3 tools/write-plugin-manifest.py chest-artifacts "$GITHUB_SHA" + cp tools/install-plugin-fleet.py tools/plugin_menu_pack.py tools/plugin_backend_abi.py tools/plugin_pillager_abi.py tools/plugin_fleet_rollback.py tools/plugin_pack_properties.py tools/publish-plugin-menu.py chest-artifacts/ + (cd chest-artifacts && sha256sum -- *.jar *.zip *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Planet-DuneChest + path: chest-artifacts/ + if-no-files-found: error + - uses: actions/upload-artifact@v3 + with: + name: DuneChest-Paper-Validation + path: DuneChest/build/libs/DuneChestPaperValidation.jar + if-no-files-found: error diff --git a/.forgejo/workflows/dunegroups.yml b/.forgejo/workflows/dunegroups.yml new file mode 100644 index 00000000..baf8af82 --- /dev/null +++ b/.forgejo/workflows/dunegroups.yml @@ -0,0 +1,44 @@ +name: DuneGroups Replacement Build +on: + workflow_dispatch: + push: + branches: ['feat/dunegroups-replacement-*', 'feat/dunegroups-fleet-*'] + +jobs: + dunegroups: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build and test both replacement plugins + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p JarvisConnector test jar compileLobbyDuneGroupsBridge + gradle --no-daemon -p DuneGroups test jar + python3 tools/test_plugin_dunegroups.py -v + mkdir dunegroups-artifacts + cp JarvisConnector/build/libs/jarvistranslator.jar DuneGroups/build/libs/DuneGroups.jar dunegroups-artifacts/ + cp JarvisConnector/build/classes/lobby-dunegroups/com/dunerealms/jarvis/NativeKeyWorker.class dunegroups-artifacts/lobby-native-key-worker.class + cp tools/{plugin_dunegroups,install-plugin-fleet,write-plugin-manifest,plugin_menu_pack,plugin_backend_abi,plugin_fleet_rollback,plugin_pack_properties,plugin_pillager_abi}.py dunegroups-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > dunegroups-artifacts/SOURCE_COMMIT + (cd dunegroups-artifacts && sha256sum -- *.jar *.py *.class SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-DuneGroups-Replacement + path: dunegroups-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/elytra-anvil.yml b/.forgejo/workflows/elytra-anvil.yml new file mode 100644 index 00000000..b6fe9247 --- /dev/null +++ b/.forgejo/workflows/elytra-anvil.yml @@ -0,0 +1,47 @@ +name: Elytra Anvil Overlay +on: + workflow_dispatch: + push: + branches: ['feat/anvil-elytra-merge-*'] + +jobs: + elytra-anvil: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test JARVIS and build the anvil overlay + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p JarvisConnector test jar + mkdir elytra-anvil + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_elytra_anvil import ADDED, CHANGED, entry + from plugin_wild_update import read_archive, write_archive + source = read_archive(Path("JarvisConnector/build/libs/jarvistranslator.jar").read_bytes()) + Path("elytra-anvil/donor.zip").write_bytes(write_archive({entry(name): source[entry(name)] for name in (*CHANGED, *ADDED)})) + PY + cp tools/{ElytraAnvilOverlay.java,plugin_elytra_anvil.py,plugin_wild_update.py} elytra-anvil/ + printf '%s\n' "$GITHUB_SHA" > elytra-anvil/SOURCE_COMMIT + (cd elytra-anvil && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Elytra-Anvil + path: elytra-anvil + if-no-files-found: error diff --git a/.forgejo/workflows/giedi-nether-pearl.yml b/.forgejo/workflows/giedi-nether-pearl.yml new file mode 100644 index 00000000..9f6cb428 --- /dev/null +++ b/.forgejo/workflows/giedi-nether-pearl.yml @@ -0,0 +1,33 @@ +name: Giedi Nether Ender Pearl Operations Build +on: + workflow_dispatch: + push: + branches: ['ops/giedi-nether-ender-pearl-*'] + +jobs: + giedi-nether-pearl: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Validate and package the scoped native command + shell: bash + run: | + set -euo pipefail + python3 tools/test_giedi_nether_pearl.py -v + mkdir giedi-pearl-artifacts + cp tools/allow-giedi-nether-pearl.py giedi-pearl-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > giedi-pearl-artifacts/SOURCE_COMMIT + (cd giedi-pearl-artifacts && sha256sum -- *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Giedi-Nether-Ender-Pearl + path: giedi-pearl-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/graded-tool-art.yml b/.forgejo/workflows/graded-tool-art.yml new file mode 100644 index 00000000..d8eb6062 --- /dev/null +++ b/.forgejo/workflows/graded-tool-art.yml @@ -0,0 +1,38 @@ +name: Graded Tool Art Build +on: + workflow_dispatch: + push: + branches: ['fix/graded-tool-halo-*'] + +jobs: + graded-tool-art: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Assemble both deployed pack variants + shell: bash + run: | + set -euo pipefail + mkdir graded-tool-art + base=$(PYTHONPATH=tools python3 -c 'from plugin_graded_tool_art import BASE_SOURCE; print(BASE_SOURCE)') + for variant in arrakis fleet; do + curl --fail --location --retry 2 "https://www.dunerealms.com/downloads/DuneRealms-Wild-$base-$variant.zip" -o "$variant.zip" + python3 tools/plugin_graded_tool_art.py "$variant" "$variant.zip" network/resource-pack/central/overlay network/resource-pack/dune-items/publication-pins.json "graded-tool-art/DuneRealms-Wild-$GITHUB_SHA-$variant.zip" > "graded-tool-art/$variant.json" + done + printf '%s\n' "$GITHUB_SHA" > graded-tool-art/SOURCE_COMMIT + cp tools/{plugin_graded_tool_art,plugin_supplied_item_art,plugin_wild_update}.py graded-tool-art/ + (cd graded-tool-art && sha256sum -- * > SHA256SUMS) + - name: Upload both checked packs + uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Graded-Tool-Art + path: graded-tool-art + if-no-files-found: error diff --git a/.forgejo/workflows/guild-cookbook.yml b/.forgejo/workflows/guild-cookbook.yml new file mode 100644 index 00000000..5dca9e92 --- /dev/null +++ b/.forgejo/workflows/guild-cookbook.yml @@ -0,0 +1,54 @@ +name: Guild and Cookbook Overlay +on: + workflow_dispatch: + push: + branches: ['fix/guild-navigator-*'] + +jobs: + guild-cookbook: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test and package exact overlay donors + shell: bash + run: | + set -euo pipefail + for module in DuneRealmsGUI DuneNPC DuneLobby; do + gradle --no-daemon -p "$module" test jar + done + mkdir guild-cookbook + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_guild_cookbook import CLASSES + from plugin_wild_update import read_archive, write_archive + for module, jar in ( + ("gui", "DuneRealmsGUI/build/libs/DunerealmsGUI.jar"), + ("npc", "DuneNPC/build/libs/DuneRealms-NPC.jar"), + ("lobby", "DuneLobby/build/libs/DuneRealms-Lobby.jar"), + ): + entries = read_archive(Path(jar).read_bytes()) + Path(f"guild-cookbook/{module}.zip").write_bytes(write_archive({entry: entries[entry] for entry in CLASSES[module]})) + PY + cp tools/{GuildCookbookMerge.java,plugin_guild_cookbook.py,plugin_wild_update.py} guild-cookbook/ + printf '%s\n' "$GITHUB_SHA" > guild-cookbook/SOURCE_COMMIT + (cd guild-cookbook && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Guild-Cookbook + path: guild-cookbook + if-no-files-found: error diff --git a/.forgejo/workflows/home-dimension.yml b/.forgejo/workflows/home-dimension.yml new file mode 100644 index 00000000..2c4c03f5 --- /dev/null +++ b/.forgejo/workflows/home-dimension.yml @@ -0,0 +1,47 @@ +name: Home Dimension Return Overlay +on: + workflow_dispatch: + push: + branches: ['fix/home-dimension-return-*'] + +jobs: + home-dimension: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test DuneEss and extract the dimension route class + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneEss test jar + mkdir home-dimension + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_home_dimension import ROUTES + from plugin_wild_update import read_archive, write_archive + source = read_archive(Path("DuneEss/build/libs/DuneRealms-Essentials.jar").read_bytes()) + Path("home-dimension/donor.zip").write_bytes(write_archive({ROUTES: source[ROUTES]})) + PY + cp tools/{HomeDimensionOverlay.java,plugin_home_dimension.py,plugin_wild_update.py} home-dimension/ + printf '%s\n' "$GITHUB_SHA" > home-dimension/SOURCE_COMMIT + (cd home-dimension && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Home-Dimension-Return + path: home-dimension + if-no-files-found: error diff --git a/.forgejo/workflows/item-origin-remainders.yml b/.forgejo/workflows/item-origin-remainders.yml new file mode 100644 index 00000000..7164fb2d --- /dev/null +++ b/.forgejo/workflows/item-origin-remainders.yml @@ -0,0 +1,41 @@ +name: Item Origin Remainders Build +on: + workflow_dispatch: + push: + branches: ['feat/item-origin-remainders-*'] + +jobs: + item-origin: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build tested provenance classes + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p JarvisConnector test jar + mkdir item-origin-artifacts + python3 tools/plugin_item_origin.py extract JarvisConnector/build/libs/jarvistranslator.jar item-origin-artifacts/item-origin.overlay.zip + cp tools/{plugin_item_origin,plugin_wild_update}.py item-origin-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > item-origin-artifacts/SOURCE_COMMIT + (cd item-origin-artifacts && sha256sum -- *.zip *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Item-Origin + path: item-origin-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/jerboa-redesign.yml b/.forgejo/workflows/jerboa-redesign.yml new file mode 100644 index 00000000..e2cd0832 --- /dev/null +++ b/.forgejo/workflows/jerboa-redesign.yml @@ -0,0 +1,48 @@ +name: Arrakis Jerboa Redesign Build +on: + workflow_dispatch: + push: + branches: ['feat/arrakis-jerboa-*'] + +jobs: + jerboa: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build Terrain and verify Arrakis jerboa art + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneTerrain test jar + python3 tools/test_plugin_fleet_install.py -v + python3 tools/test_plugin_pack_properties.py -v + mkdir jerboa-artifacts + cp DuneTerrain/build/libs/DuneRealms-Terrain.jar jerboa-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > jerboa-artifacts/SOURCE_COMMIT + pack="jerboa-artifacts/DuneRealms-Resources-${GITHUB_SHA}.zip" + python3 tools/build-unified-resourcepack.py --source "$GITHUB_SHA" --output "$pack" + curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Resources-2faba139906da15741db2702b3bed3e92ad7ee26.zip -o arrakis-baseline.zip + python3 tools/plugin_arrakis_jerboa.py DuneTerrain/build/libs/DuneRealms-Terrain.jar arrakis-baseline.zip "$pack" + python3 tools/write-plugin-manifest.py jerboa-artifacts "$GITHUB_SHA" + cp tools/plugin_arrakis_jerboa.py tools/install-plugin-fleet.py tools/plugin_menu_pack.py tools/plugin_backend_abi.py tools/plugin_pillager_abi.py tools/plugin_fleet_rollback.py tools/plugin_pack_properties.py tools/publish-plugin-menu.py jerboa-artifacts/ + (cd jerboa-artifacts && sha256sum -- *.jar *.zip *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Arrakis-Jerboa + path: jerboa-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/kaitain-typewriter.yml b/.forgejo/workflows/kaitain-typewriter.yml new file mode 100644 index 00000000..faaed2fd --- /dev/null +++ b/.forgejo/workflows/kaitain-typewriter.yml @@ -0,0 +1,31 @@ +name: Kaitain Typewriter Compatibility +on: + workflow_dispatch: + push: + branches: ['ops/kaitain-typewriter-*'] +jobs: + typewriter: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Test guard and verify official matching extension + shell: bash + run: | + set -euo pipefail + python3 tools/test_kaitain_typewriter.py -v + python3 tools/fix-kaitain-typewriter.py --build typewriter-artifacts + printf '%s\n' "$(git rev-parse HEAD)" > typewriter-artifacts/SOURCE_COMMIT + (cd typewriter-artifacts && sha256sum -- *.jar *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Kaitain-Typewriter + path: typewriter-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/lobby-account.yml b/.forgejo/workflows/lobby-account.yml new file mode 100644 index 00000000..61436ebb --- /dev/null +++ b/.forgejo/workflows/lobby-account.yml @@ -0,0 +1,43 @@ +name: Lobby Account Provisioning Build +on: + workflow_dispatch: + push: + branches: ['feat/lobby-first-join-account-*'] + +jobs: + lobby-account: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build and verify the standalone Lobby module + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneLobbyAccount test jar + python3 tools/test_plugin_fleet_install.py -v + mkdir lobby-account-artifacts + cp DuneLobbyAccount/build/libs/DuneLobbyAccount.jar lobby-account-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > lobby-account-artifacts/SOURCE_COMMIT + python3 tools/write-plugin-manifest.py lobby-account-artifacts "$GITHUB_SHA" + cp tools/{install-plugin-fleet,plugin_menu_pack,plugin_backend_abi,plugin_fleet_rollback,plugin_pack_properties,plugin_pillager_abi}.py lobby-account-artifacts/ + (cd lobby-account-artifacts && sha256sum -- *.jar *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Lobby-Account + path: lobby-account-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/lobby-builder-safety.yml b/.forgejo/workflows/lobby-builder-safety.yml new file mode 100644 index 00000000..dc1cb93c --- /dev/null +++ b/.forgejo/workflows/lobby-builder-safety.yml @@ -0,0 +1,51 @@ +name: Profile-safe Lobby Builder +on: + workflow_dispatch: + push: + branches: ['fix/compact-menu-links-*'] +jobs: + builder-safety: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test inventory isolation and package the scoped classes + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneRealms-minecraft-only test jar + gradle --no-daemon -p DuneStaff test jar + mkdir lobby-builder-safety + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_builder_multiverse import CORE, BUILDER, CORE_CLASSES, LEASE, BUILDER_CLASSES + from plugin_wild_update import read_archive, write_archive + for name, jar, entries in [ + ("core", "DuneRealms-minecraft-only/build/libs/DuneRealms-Core.jar", [CORE+n for n in CORE_CLASSES+[LEASE]]), + ("builder", "DuneStaff/build/libs/DuneStaff.jar", [BUILDER+n for n in BUILDER_CLASSES]) + ]: + compiled=read_archive(Path(jar).read_bytes()) + Path("lobby-builder-safety/"+name+".zip").write_bytes(write_archive({n:compiled[n] for n in entries})) + PY + cp tools/{plugin_builder_multiverse.py,plugin_wild_update.py,BuilderProfileCoreOverlay.java} lobby-builder-safety/ + printf '%s\n' "$GITHUB_SHA" > lobby-builder-safety/SOURCE_COMMIT + (cd lobby-builder-safety && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Lobby-Builder-Safety + path: lobby-builder-safety + if-no-files-found: error diff --git a/.forgejo/workflows/lobby-food-startup.yml b/.forgejo/workflows/lobby-food-startup.yml new file mode 100644 index 00000000..704931e6 --- /dev/null +++ b/.forgejo/workflows/lobby-food-startup.yml @@ -0,0 +1,42 @@ +name: Lobby Food Startup Build +on: + workflow_dispatch: + push: + branches: ['fix/lobby-food-startup-*'] + +jobs: + lobby-food: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build Lobby listener patch + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p JarvisConnector test jar + python3 tools/test_plugin_fleet_install.py -v + mkdir lobby-food-artifacts + python3 tools/plugin_lobby_food.py JarvisConnector/build/libs/jarvistranslator.jar lobby-food-artifacts/lobby-food-classes.zip + cp tools/{plugin_lobby_food,install-plugin-fleet,write-plugin-manifest,plugin_menu_pack,plugin_backend_abi,plugin_fleet_rollback,plugin_pack_properties,plugin_pillager_abi}.py lobby-food-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > lobby-food-artifacts/SOURCE_COMMIT + (cd lobby-food-artifacts && sha256sum -- lobby-food-classes.zip *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Lobby-Food-Startup + path: lobby-food-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/lobby-pack-session.yml b/.forgejo/workflows/lobby-pack-session.yml new file mode 100644 index 00000000..e830d1f4 --- /dev/null +++ b/.forgejo/workflows/lobby-pack-session.yml @@ -0,0 +1,49 @@ +name: Lobby Pack Session Overlay +on: + workflow_dispatch: + push: + branches: ['feat/lobby-pack-session-*'] + +jobs: + lobby-pack-session: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test proof handling and package the scoped proxy and GUI artifacts + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneRealmsGUI test jar + gradle --no-daemon -p DunePackProxy jar + mkdir lobby-pack-session + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_network_pack_menu import NEW, PATCHED + from plugin_wild_update import read_archive, write_archive + installed = read_archive(Path("DuneRealmsGUI/build/libs/DunerealmsGUI.jar").read_bytes()) + Path("lobby-pack-session/gui-donor.zip").write_bytes(write_archive({entry: installed[entry] for entry in PATCHED + NEW})) + PY + cp DunePackProxy/build/libs/DunePackProxy.jar lobby-pack-session/ + cp tools/{NetworkPackMenuMerge.java,plugin_network_pack_menu.py,plugin_wild_update.py,build_network_pack.py} lobby-pack-session/ + printf '%s\n' "$GITHUB_SHA" > lobby-pack-session/SOURCE_COMMIT + (cd lobby-pack-session && sha256sum -- *.zip *.jar *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Lobby-Pack-Session + path: lobby-pack-session + if-no-files-found: error diff --git a/.forgejo/workflows/lobby-view-distance.yml b/.forgejo/workflows/lobby-view-distance.yml new file mode 100644 index 00000000..e98ccef5 --- /dev/null +++ b/.forgejo/workflows/lobby-view-distance.yml @@ -0,0 +1,29 @@ +name: Lobby Arrakis View Distance +on: + push: + branches: ['ops/lobby-arrakis-view-distance-*'] + workflow_dispatch: +jobs: + configuration: + runs-on: dune-ci + steps: + - name: Check out exact revision + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Verify and package scoped configuration helper + run: | + python3 tools/test_lobby_arrakis_view_distance.py + mkdir config-artifacts + cp tools/lobby-arrakis-view-distance.py config-artifacts/ + printf '%s\n' "$GITHUB_SHA" > config-artifacts/SOURCE_COMMIT + (cd config-artifacts && sha256sum *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: Lobby-Arrakis-View-Distance + path: config-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/multiverse-core-lobby.yml b/.forgejo/workflows/multiverse-core-lobby.yml new file mode 100644 index 00000000..ba982ee0 --- /dev/null +++ b/.forgejo/workflows/multiverse-core-lobby.yml @@ -0,0 +1,29 @@ +name: Reviewed Lobby Multiverse Core +on: + workflow_dispatch: + push: + branches: ['fix/compact-menu-links-*'] +jobs: + multiverse-core: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Verify the official Core input and package Lobby configuration + shell: bash + run: | + set -euo pipefail + python3 tools/test_multiverse_core.py -v + python3 tools/stage_multiverse_core.py multiverse-core-lobby "$GITHUB_SHA" + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Multiverse-Core-Lobby + path: multiverse-core-lobby + if-no-files-found: error diff --git a/.forgejo/workflows/native-workstation.yml b/.forgejo/workflows/native-workstation.yml new file mode 100644 index 00000000..84c36bf7 --- /dev/null +++ b/.forgejo/workflows/native-workstation.yml @@ -0,0 +1,47 @@ +name: Native Workstation Origin Overlay +on: + workflow_dispatch: + push: + branches: ['fix/native-workstation-outputs-*'] + +jobs: + native-workstation: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test JARVIS and build the producer overlay + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p JarvisConnector test jar + mkdir native-workstation + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_native_workstation import ENTRY, NEW + from plugin_wild_update import read_archive, write_archive + source = read_archive(Path("JarvisConnector/build/libs/jarvistranslator.jar").read_bytes()) + Path("native-workstation/donor.zip").write_bytes(write_archive({entry: source[entry] for entry in [ENTRY, *NEW]})) + PY + cp tools/{NativeWorkstationMerge.java,plugin_native_workstation.py,plugin_wild_update.py} native-workstation/ + printf '%s\n' "$GITHUB_SHA" > native-workstation/SOURCE_COMMIT + (cd native-workstation && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Native-Workstation-Origin + path: native-workstation + if-no-files-found: error diff --git a/.forgejo/workflows/navigator.yml b/.forgejo/workflows/navigator.yml new file mode 100644 index 00000000..08abbb54 --- /dev/null +++ b/.forgejo/workflows/navigator.yml @@ -0,0 +1,49 @@ +name: Guild and Smuggler Navigator Build +on: + workflow_dispatch: + push: + branches: ['feat/smuggler-navigator-*'] + +jobs: + navigator: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build the reviewed Navigator plugin transition + shell: bash + run: | + set -euo pipefail + for module in JarvisConnector DuneRealmsGUI DuneMenus; do + gradle --no-daemon -p "$module" test jar + done + python3 tools/plugin_navigator_transition.py + python3 tools/test_plugin_fleet_install.py -v + python3 tools/test_plugin_pack_properties.py -v + mkdir navigator-artifacts + cp JarvisConnector/build/libs/jarvistranslator.jar DuneRealmsGUI/build/libs/DunerealmsGUI.jar DuneMenus/build/libs/DuneMenus.jar navigator-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > navigator-artifacts/SOURCE_COMMIT + python3 tools/build-unified-resourcepack.py --source "$GITHUB_SHA" --output "navigator-artifacts/DuneRealms-Resources-${GITHUB_SHA}.zip" + echo "446c0b60fa6e6752ff5260bb22c9a76280b7b10ffa03c3cca4b08f4d9320105b navigator-artifacts/DuneRealms-Resources-${GITHUB_SHA}.zip" | sha256sum --check + python3 tools/write-plugin-manifest.py navigator-artifacts "$GITHUB_SHA" + cp tools/install-plugin-fleet.py tools/plugin_menu_pack.py tools/plugin_backend_abi.py tools/plugin_pillager_abi.py tools/plugin_navigator_transition.py tools/plugin_fleet_rollback.py tools/plugin_pack_properties.py tools/publish-plugin-menu.py tools/navigator-transition.json JarvisConnector/src/test/resources/retained-jarvis-public-abi.json navigator-artifacts/ + (cd navigator-artifacts && sha256sum -- *.jar *.zip *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Navigator + path: navigator-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/ordos-sulfur-mushrooms.yml b/.forgejo/workflows/ordos-sulfur-mushrooms.yml new file mode 100644 index 00000000..fed8f997 --- /dev/null +++ b/.forgejo/workflows/ordos-sulfur-mushrooms.yml @@ -0,0 +1,49 @@ +name: Ordos Sulfur Near Mushrooms Build +on: + workflow_dispatch: + push: + branches: ['fix/ordos-sulfur-near-mushrooms-*'] + +jobs: + ordos-sulfur: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build and verify the sulfur range guard + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneTerrain test jar + python3 tools/test_planet_ore_release.py + mkdir ordos-sulfur-artifacts + cp DuneTerrain/build/classes/java/main/com/example/duneterrain/OrdosSulfurRange.class ordos-sulfur-artifacts/ + cp tools/{OrdosSulfurTransition.java,planet_ore_release.py,reset-planet-ores.py,reset-ordos-sulfur.py} ordos-sulfur-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > ordos-sulfur-artifacts/SOURCE_COMMIT + (cd ordos-sulfur-artifacts && sha256sum -- *.class *.java *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '25' + - name: Verify the retained-class transition builder + shell: bash + run: javac -d "$(mktemp -d)" tools/OrdosSulfurTransition.java + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Ordos-Sulfur-Near-Mushrooms + path: ordos-sulfur-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/pillager.yml b/.forgejo/workflows/pillager.yml new file mode 100644 index 00000000..7dfc42b0 --- /dev/null +++ b/.forgejo/workflows/pillager.yml @@ -0,0 +1,52 @@ +name: Pillager Update Build +on: + workflow_dispatch: + +jobs: + pillager: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test and package only the bounded Pillager runtime + shell: bash + run: | + set -euo pipefail + for module in JarvisConnector DuneTerrain DuneMenus DuneRealmsGUI; do + gradle --no-daemon -p "$module" test jar + done + python3 tools/test_plugin_pillager_profile.py -v + python3 tools/test_plugin_pillager_art.py -v + python3 tools/test_plugin_fleet_install.py -v + python3 tools/test_plugin_fleet_rollback.py -v + python3 tools/test_plugin_resource_pack.py -v + python3 tools/plugin_pillager_abi.py JarvisConnector/build/libs/jarvistranslator.jar + python3 tools/verify-arrakis-terrain.py DuneTerrain/build/libs/DuneRealms-Terrain.jar DuneTerrain/src/test/resources/retained-arrakis-terrain.json + mkdir pillager-artifacts + cp JarvisConnector/build/libs/jarvistranslator.jar DuneTerrain/build/libs/DuneRealms-Terrain.jar DuneMenus/build/libs/DuneMenus.jar DuneRealmsGUI/build/libs/DunerealmsGUI.jar pillager-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > pillager-artifacts/SOURCE_COMMIT + python3 tools/build-unified-resourcepack.py --source "$GITHUB_SHA" --output "pillager-artifacts/DuneRealms-Resources-${GITHUB_SHA}.zip" + python3 tools/write-plugin-manifest.py pillager-artifacts "$GITHUB_SHA" + cp tools/install-plugin-fleet.py tools/plugin_menu_pack.py tools/plugin_backend_abi.py tools/plugin_pillager_abi.py tools/plugin_fleet_rollback.py tools/plugin_pack_properties.py tools/publish-plugin-menu.py pillager-artifacts/ + cp DuneMenus/src/test/resources/preserved-backend-abi.json JarvisConnector/src/test/resources/retained-jarvis-public-abi.json JarvisConnector/src/test/resources/medieval-factions-11.1-raid-api.json JarvisConnector/src/test/resources/worldguard-raid-api.json DuneTerrain/src/test/resources/retained-arrakis-terrain.json DuneMenus/src/test/resources/pillager-accepted-frontends.json pillager-artifacts/ + cp docs/PILLAGER-UPDATE-1.0.2.0.md pillager-artifacts/ + (cd pillager-artifacts && sha256sum -- *.jar *.zip *.json *.py *.md SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Pillager-1.0.2.0 + path: pillager-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/planet-ore-profiles.yml b/.forgejo/workflows/planet-ore-profiles.yml new file mode 100644 index 00000000..ade31f41 --- /dev/null +++ b/.forgejo/workflows/planet-ore-profiles.yml @@ -0,0 +1,52 @@ +name: Planet Ore Profiles Build +on: + workflow_dispatch: + push: + branches: ['feat/planet-ore-profiles-*'] + +jobs: + planet-ore-profiles: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build and verify ore sampler + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneTerrain test jar + python3 tools/test_planet_ore_release.py + mkdir planet-ore-artifacts + python3 tools/planet_ore_release.py extract DuneTerrain/build/libs/DuneRealms-Terrain.jar planet-ore-artifacts/ore-heights.zip + cp tools/{PlanetOreTransition.java,planet_ore_release.py,reset-planet-ores.py} planet-ore-artifacts/ + cp DuneTerrain/planet-datapacks/sigma_draconis_iv/data/dunerealms/worldgen/biome/frozen_desert.json planet-ore-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > planet-ore-artifacts/SOURCE_COMMIT + (cd planet-ore-artifacts && sha256sum -- *.java *.json *.py *.zip SOURCE_COMMIT > SHA256SUMS) + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '25' + - name: Verify the class transition builder + shell: bash + run: | + set -euo pipefail + javac -d "$(mktemp -d)" tools/PlanetOreTransition.java + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Planet-Ore-Profiles + path: planet-ore-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/plugins.yml b/.forgejo/workflows/plugins.yml index 19bd3ba4..31358db1 100644 --- a/.forgejo/workflows/plugins.yml +++ b/.forgejo/workflows/plugins.yml @@ -1,65 +1,90 @@ -name: DuneRealms Plugin CI -on: - workflow_dispatch: - push: - branches: [main] - paths: - - '.forgejo/workflows/plugins.yml' - - 'Dune*/**' - - 'JarvisConnector/**' - - 'gui-common/**' - - 'citizens-common/**' - - 'network/resource-pack/shared/**' - - 'network/content-assets/planet-artwork/profiles.json' - - 'tools/*gameplay*' - -jobs: - plugins: - runs-on: dune-ci - steps: - - name: Check out exact revision - shell: bash - env: - REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - set -euo pipefail - git init . - git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" - git checkout --detach FETCH_HEAD - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - uses: gradle/actions/setup-gradle@v4 - with: - gradle-version: '9.2.1' - - name: Test and build first-party plugins - shell: bash - run: | - set -euo pipefail - modules=(DuneEss DuneLobby DuneNPC DuneRealms-minecraft-only DuneRealmsGUI DuneTerrain JarvisConnector) - mkdir -p plugin-artifacts - for module in "${modules[@]}"; do - gradle --no-daemon -p "$module" test jar - for jar in "$module"/build/libs/*.jar; do - test -f "$jar" - artifact="plugin-artifacts/${jar##*/}" - test ! -e "$artifact" - cp "$jar" "$artifact" - done - done - printf '%s\n' "$(git rev-parse HEAD)" > plugin-artifacts/SOURCE_COMMIT - (cd plugin-artifacts && sha256sum -- *.jar SOURCE_COMMIT > SHA256SUMS) - - name: Validate gameplay assets and build pack with original GUI - shell: bash - run: | - set -euo pipefail - python3 tools/test_gameplay_resourcepack.py -v - python3 tools/build-gameplay-resourcepack.py --from-gui-config DuneRealmsGUI/src/main/resources/gui-pack.yml --output "plugin-artifacts/DuneRealms-Gameplay-${GITHUB_SHA}.zip" - python3 tools/write-plugin-manifest.py plugin-artifacts "$GITHUB_SHA" - (cd plugin-artifacts && sha256sum -- *.jar *.zip *.json SOURCE_COMMIT > SHA256SUMS) - - uses: actions/upload-artifact@v3 - with: - name: DuneRealms-Plugins - path: plugin-artifacts/ - if-no-files-found: error +name: DuneRealms Plugin CI +on: + workflow_dispatch: + push: + branches: ['**'] + +jobs: + plugins: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test and build first-party plugins + shell: bash + run: | + set -euo pipefail + modules=(DuneEss DuneLobby DuneLobbyAccount DuneNPC DuneRealms-minecraft-only DuneRealmsGUI DuneTerrain JarvisConnector DuneMenus DuneGroups) + mkdir -p plugin-artifacts + for module in "${modules[@]}"; do + gradle --no-daemon -p "$module" test jar + done + # This release restores presentation only. Never ship the known-incompatible + # rebuilt economy/backend modules as accidental fleet install candidates. + for module in DuneLobby DuneNPC DuneRealmsGUI DuneMenus; do + for jar in "$module"/build/libs/*.jar; do + test -f "$jar" + artifact="plugin-artifacts/${jar##*/}" + test ! -e "$artifact" + cp "$jar" "$artifact" + done + done + printf '%s\n' "$(git rev-parse HEAD)" > plugin-artifacts/SOURCE_COMMIT + (cd plugin-artifacts && sha256sum -- *.jar SOURCE_COMMIT > SHA256SUMS) + - name: Validate rollout contract and build stacked menu overlay + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + python3 tools/test_plugin_ci_policy.py -v + pillager_input="$(mktemp -d)" + python3 tools/plugin_navigator_transition.py --stage-pillager-baseline "$pillager_input/baseline" + DUNE_PILLAGER_BASELINE_DIR="$pillager_input/baseline" python3 tools/test_plugin_pillager_profile.py -v + # Navigator predates the selectable DuneGroups backend. Validate its + # exact historical connector against the original unchanged contract. + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git 5d727d7f59e6af26fba07a3878fd79035a5923ce + git worktree add --detach "$pillager_input/navigator" FETCH_HEAD + gradle --no-daemon -p "$pillager_input/navigator/JarvisConnector" jar + # Check the final accepted Navigator frontends at their source pin; the current + # tree has independent required tests and can legitimately contain newer artwork. + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git 313db14fb4fdda1f7193e86499f1041b15e9d04b + git worktree add --detach "$pillager_input/navigator-frontends" FETCH_HEAD + gradle --no-daemon -p "$pillager_input/navigator-frontends/DuneMenus" jar + gradle --no-daemon -p "$pillager_input/navigator-frontends/DuneRealmsGUI" jar + python3 tools/plugin_navigator_transition.py --historical-jarvis "$pillager_input/navigator/JarvisConnector/build/libs/jarvistranslator.jar" --historical-frontends "$pillager_input/navigator-frontends" + python3 tools/test_plugin_pillager_art.py -v + python3 tools/test_plugin_fleet_install.py -v + python3 tools/test_plugin_menu_pack.py -v + python3 tools/test_plugin_backend_abi.py -v + python3 tools/test_plugin_fleet_rollback.py -v + python3 tools/test_plugin_resource_pack.py -v + python3 tools/test_plugin_vanilla_art.py -v + python3 tools/test_plugin_pack_properties.py -v + python3 tools/test_gameplay_resourcepack.py -v + python3 tools/build-unified-resourcepack.py --source "$GITHUB_SHA" --output "plugin-artifacts/DuneRealms-Resources-${GITHUB_SHA}.zip" + python3 tools/write-plugin-manifest.py plugin-artifacts "$GITHUB_SHA" + cp tools/install-plugin-fleet.py tools/plugin_menu_pack.py tools/plugin_backend_abi.py tools/plugin_fleet_rollback.py tools/plugin_pack_properties.py tools/publish-plugin-menu.py tools/plugin_pillager_abi.py plugin-artifacts/ + cp DuneMenus/src/test/resources/preserved-backend-abi.json plugin-artifacts/ + cp DuneMenus/docs/FLEET-INSTALL.md DuneMenus/docs/MENU-PACK-ROLLOUT.md DuneMenus/docs/CANARY-RECOVERY-20261129.md plugin-artifacts/ + cp DuneMenus/docs/CENTRAL-PACK-INTEGRATION.md plugin-artifacts/ + (cd plugin-artifacts && sha256sum -- *.jar *.zip *.json *.py *.md SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Plugins + path: plugin-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/quest-story-arcs.yml b/.forgejo/workflows/quest-story-arcs.yml new file mode 100644 index 00000000..609adf37 --- /dev/null +++ b/.forgejo/workflows/quest-story-arcs.yml @@ -0,0 +1,51 @@ +name: Quest Arc Presentation Overlay +on: + workflow_dispatch: + push: + branches: ['feat/quest-story-arcs-*'] + +jobs: + quest-story-arcs: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test the journal and package only quest arc classes and art + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneRealmsGUI test jar + mkdir quest-story-arcs + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from quest_arc_artwork import CATALOG, OVERLAY, artwork, gui_entries + from plugin_wild_update import read_archive, write_archive + source = read_archive(Path("DuneRealmsGUI/build/libs/DunerealmsGUI.jar").read_bytes()) + Path("quest-story-arcs/donor.zip").write_bytes(write_archive({entry: source[entry] for entry in gui_entries()})) + assets = artwork(Path(".")) + art = {f"{OVERLAY}/{name}": data for name, data in assets.items()} + art[CATALOG] = Path(CATALOG).read_bytes() + Path("quest-story-arcs/artwork.zip").write_bytes(write_archive(art)) + PY + cp tools/{quest_arc_artwork.py,plugin_wild_update.py} quest-story-arcs/ + printf '%s\n' "$GITHUB_SHA" > quest-story-arcs/SOURCE_COMMIT + (cd quest-story-arcs && sha256sum -- *.zip *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Quest-Story-Arcs + path: quest-story-arcs + if-no-files-found: error diff --git a/.forgejo/workflows/sigma-cold-pigs.yml b/.forgejo/workflows/sigma-cold-pigs.yml new file mode 100644 index 00000000..5ec8e441 --- /dev/null +++ b/.forgejo/workflows/sigma-cold-pigs.yml @@ -0,0 +1,49 @@ +name: Sigma Cold Pigs Overlay +on: + workflow_dispatch: + push: + branches: ['fix/sigma-cold-pigs-*'] + +jobs: + sigma-cold-pigs: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test Terrain and package the reviewed donor class + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneTerrain test jar + mkdir sigma-cold-pigs + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_sigma_cold_pigs import ENTRY + from plugin_wild_update import read_archive, write_archive + jars = list(Path("DuneTerrain/build/libs").glob("*.jar")) + assert len(jars) == 1 + entries = read_archive(jars[0].read_bytes()) + Path("sigma-cold-pigs/donor.zip").write_bytes(write_archive({ENTRY: entries[ENTRY]})) + PY + cp tools/{SigmaColdPigMerge.java,plugin_sigma_cold_pigs.py,plugin_wild_update.py} sigma-cold-pigs/ + printf '%s\n' "$GITHUB_SHA" > sigma-cold-pigs/SOURCE_COMMIT + (cd sigma-cold-pigs && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Sigma-Cold-Pigs + path: sigma-cold-pigs + if-no-files-found: error diff --git a/.forgejo/workflows/sigma-ore-palette.yml b/.forgejo/workflows/sigma-ore-palette.yml new file mode 100644 index 00000000..39f9d9d3 --- /dev/null +++ b/.forgejo/workflows/sigma-ore-palette.yml @@ -0,0 +1,34 @@ +name: Sigma Ore Palette Build +on: + workflow_dispatch: + push: + branches: ['fix/sigma-native-ore-palette-*'] + +jobs: + sigma-ore-palette: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Validate and package the three Sigma biomes + shell: bash + run: | + set -euo pipefail + python3 tools/test_planet_ore_release.py + mkdir sigma-ore-artifacts + cp DuneTerrain/planet-datapacks/sigma_draconis_iv/data/minecraft/worldgen/biome/{badlands,eroded_badlands,sulfur_caves}.json sigma-ore-artifacts/ + cp tools/{planet_ore_release,reset-planet-ores,reset-sigma-ore-pack}.py sigma-ore-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > sigma-ore-artifacts/SOURCE_COMMIT + (cd sigma-ore-artifacts && sha256sum -- *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Sigma-Ore-Palette + path: sigma-ore-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/sigma-snow-weather.yml b/.forgejo/workflows/sigma-snow-weather.yml new file mode 100644 index 00000000..744eda94 --- /dev/null +++ b/.forgejo/workflows/sigma-snow-weather.yml @@ -0,0 +1,42 @@ +name: Sigma Snow Weather Build +on: + workflow_dispatch: + push: + branches: ['fix/sigma-snow-weather-*'] + +jobs: + sigma-snow-weather: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build Sigma soil class patch + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneTerrain test jar + + mkdir sigma-snow-weather-artifacts + python3 tools/plugin_sigma_snow_weather.py DuneTerrain/build/libs/DuneRealms-Terrain.jar sigma-snow-weather-artifacts/sigma-snow-weather-classes.zip + cp tools/plugin_sigma_snow_weather.py sigma-snow-weather-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > sigma-snow-weather-artifacts/SOURCE_COMMIT + (cd sigma-snow-weather-artifacts && sha256sum -- sigma-snow-weather-classes.zip *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Sigma-Snow-Weather + path: sigma-snow-weather-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/spice-cookers-rails.yml b/.forgejo/workflows/spice-cookers-rails.yml new file mode 100644 index 00000000..67749791 --- /dev/null +++ b/.forgejo/workflows/spice-cookers-rails.yml @@ -0,0 +1,55 @@ +name: Spice Cookers and Rails Build +on: + workflow_dispatch: + push: + branches: ['feat/spice-cookers-rails-*'] + +jobs: + spice-cookers-rails: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build tested cookers and patched rails from pinned source + shell: bash + run: | + set -euo pipefail + build="$(mktemp -d)" + mkdir spice-rail-artifacts + git clone --quiet --no-checkout https://github.com/Fridtjof-DE/MinecartTrains.git "$build/rails" + git -C "$build/rails" checkout --detach 2f19054927c96fdf1d025b3e9f6a32c5534aef2a + cmp vendor/minecart-trains/LICENSE.upstream "$build/rails/LICENSE" + git -C "$build/rails" apply "$PWD/vendor/minecart-trains/spice-coal.patch" + curl --fail --location --retry 2 https://cdn.modrinth.com/data/PSN4XhQK/versions/G2YwbBLw/PuddingAPI-2611162255.jar -o "$build/PuddingAPI-2611162255.jar" + (cd "$build" && printf '%s PuddingAPI-2611162255.jar\n' 8c6504f09e6d7b384a4a2651ed33a1b28c7b41a4e42aff89f0e459524697e304 | sha256sum --check) + for module in JarvisConnector DuneRealmsGUI DuneMenus; do + gradle --no-daemon -p "$module" test jar + done + gradle --no-daemon -p vendor/minecart-trains jar "-PrailsSource=$build/rails" "-PpuddingJar=$build/PuddingAPI-2611162255.jar" + python3 tools/build-unified-resourcepack.py --source "$GITHUB_SHA" --output "$build/resource-validation.zip" + python3 tools/plugin_spice_cookers.py extract network/resource-pack/central/overlay JarvisConnector/build/libs/jarvistranslator.jar DuneRealmsGUI/build/libs/DunerealmsGUI.jar DuneMenus/build/libs/DuneMenus.jar spice-rail-artifacts + cp vendor/minecart-trains/build/libs/MinecartTrains-1.4.3-dune1.jar "$build/PuddingAPI-2611162255.jar" spice-rail-artifacts/ + cp vendor/minecart-trains/{build.gradle.kts,settings.gradle.kts,spice-coal.patch} "$build/rails/" + tar -czf spice-rail-artifacts/MinecartTrains-1.4.3-dune1-source.tar.gz -C "$build/rails" LICENSE README.md pom.xml build.gradle.kts settings.gradle.kts spice-coal.patch src + cp tools/{plugin_spice_cookers,plugin_wild_update}.py spice-rail-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > spice-rail-artifacts/SOURCE_COMMIT + (cd spice-rail-artifacts && sha256sum -- *.zip *.tar.gz *.jar *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Spice-Cookers-Rails + path: spice-rail-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/station-origins-doors.yml b/.forgejo/workflows/station-origins-doors.yml new file mode 100644 index 00000000..eb7fda29 --- /dev/null +++ b/.forgejo/workflows/station-origins-doors.yml @@ -0,0 +1,51 @@ +name: Station Origins and Iron Doors Overlay +on: + workflow_dispatch: + push: + branches: ['fix/station-origins-*'] + +jobs: + station-and-doors: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test both plugins and extract exact overlay donors + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p JarvisConnector test jar + gradle --no-daemon -p DuneEss test jar + mkdir station-and-doors + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_station_and_doors import donor_archive + output = Path("station-and-doors") + for role, jar in ( + ("station", "JarvisConnector/build/libs/jarvistranslator.jar"), + ("ess", "DuneEss/build/libs/DuneRealms-Essentials.jar"), + ): + (output / (role + "-donor.zip")).write_bytes(donor_archive(role, Path(jar))) + PY + cp tools/{StationAndDoorOverlay.java,plugin_station_and_doors.py,plugin_wild_update.py} station-and-doors/ + printf '%s\n' "$GITHUB_SHA" > station-and-doors/SOURCE_COMMIT + (cd station-and-doors && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Station-Origins-Iron-Doors + path: station-and-doors + if-no-files-found: error diff --git a/.forgejo/workflows/supplied-item-art.yml b/.forgejo/workflows/supplied-item-art.yml new file mode 100644 index 00000000..9981f1a5 --- /dev/null +++ b/.forgejo/workflows/supplied-item-art.yml @@ -0,0 +1,38 @@ +name: Supplied Dune Item Art Build +on: + workflow_dispatch: + push: + branches: ['feat/supplied-item-art-*'] + +jobs: + supplied-item-art: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Build both retained pack variants + shell: bash + run: | + set -euo pipefail + mkdir supplied-item-art + python3 tools/build-unified-resourcepack.py --source "$GITHUB_SHA" --output candidate-source.zip + curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Resources-ab1b9f8915ba2a68a7388cdf5f55ff76349b0339.zip -o arrakis-baseline.zip + curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Resources-2faba139906da15741db2702b3bed3e92ad7ee26.zip -o fleet-baseline.zip + for variant in arrakis fleet; do + python3 tools/plugin_supplied_item_art.py "$variant" "$variant-baseline.zip" candidate-source.zip network/resource-pack/dune-items/publication-pins.json "supplied-item-art/DuneRealms-ItemArt-$GITHUB_SHA-$variant.zip" > "supplied-item-art/$variant.json" + done + printf '%s\n' "$(git rev-parse HEAD)" > supplied-item-art/SOURCE_COMMIT + cp tools/plugin_supplied_item_art.py network/resource-pack/dune-items/publication-pins.json supplied-item-art/ + (cd supplied-item-art && sha256sum -- *.zip *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Supplied-Item-Art + path: supplied-item-art/ + if-no-files-found: error diff --git a/.forgejo/workflows/unused-vendor-settings.yml b/.forgejo/workflows/unused-vendor-settings.yml new file mode 100644 index 00000000..aabd510d --- /dev/null +++ b/.forgejo/workflows/unused-vendor-settings.yml @@ -0,0 +1,33 @@ +name: Unused Vendor Settings Operations Build +on: + workflow_dispatch: + push: + branches: ['ops/unused-vendor-settings-*'] + +jobs: + unused-vendor-settings: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Validate and package the scoped vendor configuration operation + shell: bash + run: | + set -euo pipefail + python3 tools/test_unused_vendor_settings.py -v + mkdir unused-vendor-artifacts + cp tools/disable-unused-vendor-settings.py tools/unused-vendor-settings.json unused-vendor-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > unused-vendor-artifacts/SOURCE_COMMIT + (cd unused-vendor-artifacts && sha256sum -- *.py *.json SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Unused-Vendor-Settings + path: unused-vendor-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/wild-release.yml b/.forgejo/workflows/wild-release.yml new file mode 100644 index 00000000..6a446ade --- /dev/null +++ b/.forgejo/workflows/wild-release.yml @@ -0,0 +1,70 @@ +name: Wild Update Release +on: + workflow_dispatch: + push: + branches: ['feat/wild-release-*'] + +jobs: + wild-release: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build exact-source runtime overlays, rails and packs + shell: bash + run: | + set -euo pipefail + build="$(mktemp -d)" + release="$PWD/wild-release" + mkdir -p "$release"/{packs,plugins,cookers} + for module in DuneLobby DuneNPC DuneRealmsGUI DuneMenus DuneTerrain JarvisConnector DuneStaff; do + gradle --no-daemon -p "$module" test jar + done + python3 tools/test_plugin_wild_update.py -v + python3 tools/plugin_wild_update.py extract . "$release/wild" "$GITHUB_SHA" + python3 tools/plugin_item_origin.py extract JarvisConnector/build/libs/jarvistranslator.jar "$release/plugins/item-origin.overlay.zip" + python3 tools/plugin_spice_cookers.py extract network/resource-pack/central/overlay JarvisConnector/build/libs/jarvistranslator.jar DuneRealmsGUI/build/libs/DunerealmsGUI.jar DuneMenus/build/libs/DuneMenus.jar "$release/cookers" + cp DuneStaff/build/libs/DuneStaff.jar "$release/plugins/" + git clone --quiet --no-checkout https://github.com/Fridtjof-DE/MinecartTrains.git "$build/rails" + git -C "$build/rails" checkout --detach 2f19054927c96fdf1d025b3e9f6a32c5534aef2a + cmp vendor/minecart-trains/LICENSE.upstream "$build/rails/LICENSE" + git -C "$build/rails" apply "$PWD/vendor/minecart-trains/spice-coal.patch" + curl --fail --location --retry 2 https://cdn.modrinth.com/data/PSN4XhQK/versions/G2YwbBLw/PuddingAPI-2611162255.jar -o "$build/PuddingAPI-2611162255.jar" + (cd "$build" && printf '%s PuddingAPI-2611162255.jar\n' 8c6504f09e6d7b384a4a2651ed33a1b28c7b41a4e42aff89f0e459524697e304 | sha256sum --check) + gradle --no-daemon -p vendor/minecart-trains jar "-PrailsSource=$build/rails" "-PpuddingJar=$build/PuddingAPI-2611162255.jar" + cp vendor/minecart-trains/build/libs/MinecartTrains-1.4.3-dune1.jar "$build/PuddingAPI-2611162255.jar" "$release/plugins/" + cp vendor/minecart-trains/{build.gradle.kts,settings.gradle.kts,spice-coal.patch} "$build/rails/" + tar -czf "$release/plugins/MinecartTrains-1.4.3-dune1-source.tar.gz" -C "$build/rails" LICENSE README.md pom.xml build.gradle.kts settings.gradle.kts spice-coal.patch src + python3 tools/build-unified-resourcepack.py --source "$GITHUB_SHA" --output "$build/candidate-source.zip" + curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Resources-ab1b9f8915ba2a68a7388cdf5f55ff76349b0339.zip -o "$build/arrakis-baseline.zip" + curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Resources-2faba139906da15741db2702b3bed3e92ad7ee26.zip -o "$build/fleet-baseline.zip" + pins=network/resource-pack/dune-items/publication-pins.json + art="$release/cookers/spice-cookers.art.zip" + for variant in arrakis fleet; do + corrected="$build/$variant-corrected.zip" + python3 tools/plugin_supplied_item_art.py "$variant" "$build/$variant-baseline.zip" "$build/candidate-source.zip" "$pins" "$corrected" > "$release/packs/$variant-art-transition.json" + python3 tools/plugin_spice_cookers.py assemble pack "$corrected" "$art" "$release/packs/DuneRealms-Wild-$GITHUB_SHA-$variant.zip" "$(sha256sum "$corrected" | cut -d' ' -f1)" "$(sha256sum "$art" | cut -d' ' -f1)" + done + cp tools/{plugin_citizens_ready,plugin_item_origin,plugin_spice_cookers,plugin_supplied_item_art,plugin_wild_update}.py "$release/" + cp "$pins" network/content-assets/cookbook/spice-crafting.json "$release/" + printf '%s\n' "$(git rev-parse HEAD)" > "$release/SOURCE_COMMIT" + (cd "$release" && find . -type f ! -name SHA256SUMS -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Wild-Beta-1.0.3.0 + path: wild-release/ + if-no-files-found: error diff --git a/.forgejo/workflows/wild-update.yml b/.forgejo/workflows/wild-update.yml new file mode 100644 index 00000000..54649845 --- /dev/null +++ b/.forgejo/workflows/wild-update.yml @@ -0,0 +1,43 @@ +name: The Wild Update Build +on: + workflow_dispatch: + push: + branches: ['feat/quest-journal-bundle-*'] + +jobs: + wild-update: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build tested entry overlays + shell: bash + run: | + set -euo pipefail + for module in DuneLobby DuneNPC DuneRealmsGUI DuneMenus DuneTerrain JarvisConnector; do + gradle --no-daemon -p "$module" test jar + done + python3 tools/test_plugin_wild_update.py -v + python3 tools/plugin_wild_update.py extract . wild-update-artifacts "$GITHUB_SHA" + cp tools/plugin_wild_update.py wild-update-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > wild-update-artifacts/SOURCE_COMMIT + (cd wild-update-artifacts && sha256sum -- *.zip *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Wild-Update + path: wild-update-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/workstation-origin.yml b/.forgejo/workflows/workstation-origin.yml new file mode 100644 index 00000000..c3ec9a0f --- /dev/null +++ b/.forgejo/workflows/workstation-origin.yml @@ -0,0 +1,41 @@ +name: Workstation Origin Overlay +on: + workflow_dispatch: + push: + branches: ['fix/workstation-origin-*'] + +jobs: + workstation-origin: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test and build the single-class overlay + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p JarvisConnector test jar + mkdir workstation-origin + python3 tools/plugin_workstation_origin.py extract JarvisConnector/build/libs/jarvistranslator.jar workstation-origin/workstation-origin.overlay.zip + cp tools/{plugin_workstation_origin,plugin_wild_update}.py tools/WorkstationOriginMerge.java workstation-origin/ + printf '%s\n' "$GITHUB_SHA" > workstation-origin/SOURCE_COMMIT + (cd workstation-origin && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Workstation-Origin + path: workstation-origin + if-no-files-found: error diff --git a/.gitattributes b/.gitattributes index b26e6b46..87dd46dc 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,10 @@ *.pdf binary *.png binary *.zip binary +network/resource-pack/vanilla-art/*.json text eol=lf +network/resource-pack/vanilla-art/**/*.json text eol=lf +network/resource-pack/vanilla-art/**/*.png.mcmeta text eol=lf + +# Preserve reviewed third-party asset bytes, including original JSON line endings. +network/resource-pack/excalibur/overlay/** -text +network/resource-pack/excalibur/CREATOR-LICENSE.txt -text diff --git a/AGENTS.md b/AGENTS.md index c189dd51..53d02bda 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,4 +8,16 @@ - Keep this repository limited to plugins, shared source, resources, tests and required build/CI inputs. - Record exact source commit, JAR filenames/versions and SHA-256 hashes. Test and build the recorded revision; distinguish artifacts, merge and actual verified deployment. - Never commit credentials or print tokens/private keys. No real financial transactions or world regeneration. -- Preserve unrelated local work and earned player progression. Treat expected migration of explicitly requested NPC types separately from deleting gameplay data. \ No newline at end of file +- Preserve unrelated local work and earned player progression. Treat expected migration of explicitly requested NPC types separately from deleting gameplay data. +## Accepted GUI foundation + +- Preserve the current fast supplied-menu renderer and working JARVIS callbacks; polish this design rather than replacing the GUI/backend wholesale. Owner speed feedback is qualitative, not a measured performance benchmark. +- Public command aliases and GUI buttons must enter the same working native service. Preserve uncertain purchase references and idempotent retries. +- Keep text inside measured card bounds. Essential price and stock remain visible before purchase; optional details must not execute or confirm a purchase. +- Use verified item artwork from actual item metadata. Same-ID block textures are flat surface previews, not native 3D renders. Unsupported complex/dynamic icons require an explicit fallback; never infer quality or MK from a title. +- Use the canonical illustrated website logo with proportional containment. Package/cache artwork locally and keep remote requests out of menu opening. + +- Owner approved compact card density across Java menus: standard cards approximately 25% smaller, Exchange navigation as a toolbar, and mission cards in a grid. Preserve readable prices and click targets. +- Before changing this foundation, run the retained NativeMenus public-ABI and lifecycle tests, native route tests, pending-purchase safety tests, and pinned MCGUI renderer checks for containment, icon centering and original action hitboxes. Source tests alone do not prove connected-client actions work. +- Inspect and reuse existing JARVIS keys, records and authoritative service flows first. Preserve callback identity, lifecycle gates and pending payment references; do not create alternate domain engines to work around a presentation fault. +- An accepted release must be tagged and backed up only after actual functional acceptance. Never freeze a known broken candidate or deploy a documentation-only artifact. diff --git a/DuneChat/README.md b/DuneChat/README.md new file mode 100644 index 00000000..2dfebc9c --- /dev/null +++ b/DuneChat/README.md @@ -0,0 +1,17 @@ +# DuneChat + +DuneChat formats public Minecraft chat and provides local private channels. + +| Command | Action | +|---|---| +| /cc [message] | Toggle clan chat or send one message | +| /coc [message] | Toggle company chat or send one message | +| /sc [message] | Toggle staff chat or send one message | +| /g | Return to public chat | +| /chatspy | Toggle clan and company visibility with the explicit spy permission | + +Public prefixes use the existing JARVIS House briefing. Private clan and company delivery requires matching organisation UUIDs and current, explicit membership in the authenticated organisation roster. Public display labels grant no chat access. Staff commands require dunechat.staff. Chat spy requires dunechat.spy. + +The plugin uses Paper's chat pipeline so menu prompts and existing chat cancellation handlers retain precedence. DiscordSRV keeps its public route. The privacy hook suppresses private messages before Discord forwarding. Deploy with DiscordSRV configured to use modern Paper events and respect event cancellation, including menu prompt input. Private console logging defaults off. + +Build with gradle -p DuneChat test jar. The release artifact contains DuneChat.jar. Existing GUI and JARVIS archives are retained. diff --git a/DuneChat/build.gradle.kts b/DuneChat/build.gradle.kts new file mode 100644 index 00000000..bfedb910 --- /dev/null +++ b/DuneChat/build.gradle.kts @@ -0,0 +1,21 @@ +plugins { java } +group = "com.example" +version = "1.0.0" +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") + maven("https://nexus.scarsz.me/content/groups/public/") { + content { includeModule("com.discordsrv", "discordsrv") } + } +} +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + compileOnly("com.discordsrv:discordsrv:1.30.5") { isTransitive = false } + testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} +java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } +tasks.withType { options.encoding = "UTF-8" } +tasks.test { useJUnitPlatform() } +tasks.jar { archiveFileName.set("DuneChat.jar") } diff --git a/DuneChat/settings.gradle.kts b/DuneChat/settings.gradle.kts new file mode 100644 index 00000000..c94dd473 --- /dev/null +++ b/DuneChat/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "DuneChat" diff --git a/DuneChat/src/main/java/com/example/dunechat/ChatIdentitySource.java b/DuneChat/src/main/java/com/example/dunechat/ChatIdentitySource.java new file mode 100644 index 00000000..de431390 --- /dev/null +++ b/DuneChat/src/main/java/com/example/dunechat/ChatIdentitySource.java @@ -0,0 +1,28 @@ +package com.example.dunechat; + +import com.google.gson.JsonObject; +import java.lang.reflect.Method; +import java.util.UUID; +import org.bukkit.plugin.Plugin; + +/** Reuse the installed JARVIS reads without replacing the GUI or the central service. */ +final class ChatIdentitySource { + private final Plugin jarvis; + private final Method house; + private final Method organisations; + + ChatIdentitySource(Plugin jarvis) throws ReflectiveOperationException { + this.jarvis = jarvis; + if (jarvis == null || !jarvis.isEnabled()) throw new IllegalStateException("JARVIS unavailable"); + house = jarvis.getClass().getMethod("requestHouse", UUID.class, String.class, int.class, UUID.class); + organisations = jarvis.getClass().getMethod("requestOrganisations", UUID.class); + } + + JsonObject house(UUID player) throws ReflectiveOperationException { + return (JsonObject) house.invoke(jarvis, player, null, 0, null); + } + + JsonObject organisations(UUID player) throws ReflectiveOperationException { + return (JsonObject) organisations.invoke(jarvis, player); + } +} diff --git a/DuneChat/src/main/java/com/example/dunechat/ChatLogic.java b/DuneChat/src/main/java/com/example/dunechat/ChatLogic.java new file mode 100644 index 00000000..14ab3bac --- /dev/null +++ b/DuneChat/src/main/java/com/example/dunechat/ChatLogic.java @@ -0,0 +1,159 @@ +package com.example.dunechat; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** Pure chat rules: identity parsing, prefixes and who may read a channel. No Bukkit types. */ +final class ChatLogic { + enum Channel { GLOBAL, CLAN, COMPANY, STAFF } + + /** Group keys are exact central membership UUIDs. Blank means no authorized membership. */ + record Identity(String faction, String race, boolean staff, boolean vip, + String clanKey, String clanTag, String companyKey, String companyName) { + static final Identity NONE = new Identity("", "", false, false, "", "", "", ""); + } + + static String clean(String value, int max) { + String safe = value == null ? "" : value.replaceAll("[&ยง%<>\\p{Cntrl}]", "").strip(); + return safe.substring(0, Math.min(Math.max(0, max), safe.length())); + } + + static String color(String faction) { + return switch (faction == null ? "" : faction) { + case "atreides" -> "&a"; case "harkonnen" -> "&c"; case "corrino" -> "&6"; + case "ordos" -> "&e"; case "fremen" -> "&b"; default -> "&f"; + }; + } + + private static boolean flag(JsonObject o, String k) { + return o != null && o.has(k) && o.get(k).isJsonPrimitive() && o.get(k).getAsJsonPrimitive().isBoolean() && o.get(k).getAsBoolean(); + } + + private static String text(JsonObject o, String k) { + JsonElement e = o == null ? null : o.get(k); + return e != null && e.isJsonPrimitive() ? e.getAsString() : ""; + } + + /** First object in an array field, or null. Only the first group counts: one clan and one company per player. */ + private static JsonObject first(JsonObject o, String k) { + JsonElement e = o == null ? null : o.get(k); + if (e == null || !e.isJsonArray()) return null; + JsonArray a = e.getAsJsonArray(); + return a.isEmpty() || !a.get(0).isJsonObject() ? null : a.get(0).getAsJsonObject(); + } + + /** Reads the same central briefing the nameplates use: briefing.identity.{staff,vip,clans[],companies[]}. */ + static Identity parse(JsonObject data, String faction, String race, int max) { + JsonObject id = null; + if (data != null && data.has("briefing") && data.get("briefing").isJsonObject()) { + JsonObject b = data.getAsJsonObject("briefing"); + if (b.has("identity") && b.get("identity").isJsonObject()) id = b.getAsJsonObject("identity"); + } + JsonObject clan = first(id, "clans"), company = first(id, "companies"); + String clanName = text(clan, "name"), clanTag = text(clan, "tag"); + String companyName = text(company, "name"); + return new Identity(faction == null ? "" : faction, clean(race, max), flag(id, "staff"), flag(id, "vip"), + "", clean(clanTag.isBlank() ? clanName : clanTag, max), "", clean(companyName, max)); + } + + static Identity house(JsonObject data, int max) { + if (data == null) return Identity.NONE; + String faction = text(data, "selection"); + JsonArray choices = data.getAsJsonArray("choices"); + if (!faction.isBlank() && choices != null) { + for (JsonElement element : choices) { + JsonObject choice = element.getAsJsonObject(); + if (faction.equals(text(choice, "id"))) return parse(data, faction, text(choice, "name"), max); + } + } + return parse(data, "", "", max); + } + + record Membership(String clan, String company, long observedAt) { + static final Membership NONE = new Membership("", "", 0); + } + + static Membership memberships(JsonObject data, UUID actor, long now) { + if (data == null || !flag(data, "ok") || !"1".equals(text(data, "schema"))) return Membership.NONE; + long observedAt = data.get("observedAt").getAsLong(); + if (observedAt < now - 45_000 || observedAt > now + 5_000) return Membership.NONE; + return new Membership(memberId(data.getAsJsonArray("clans"), actor), + memberId(data.getAsJsonArray("companies"), actor), observedAt); + } + + private static String memberId(JsonArray rows, UUID actor) { + if (rows == null || rows.size() > 512) return ""; + String found = ""; + for (JsonElement element : rows) { + JsonObject row = element.getAsJsonObject(); + if (!"active".equals(text(row, "lifecycle"))) continue; + JsonArray members = row.getAsJsonArray("members"); + if (members == null || members.size() > 5_000) continue; + for (JsonElement member : members) { + if (!actor.toString().equals(text(member.getAsJsonObject(), "uuid"))) continue; + String id = canonicalId(text(row, "id")); + if (id.isEmpty() || !found.isEmpty() && !found.equals(id)) return ""; + found = id; + } + } + return found; + } + + private static String canonicalId(String id) { + try { + String canonical = UUID.fromString(id).toString(); + return canonical.equalsIgnoreCase(id) ? canonical : ""; + } catch (IllegalArgumentException invalid) { + return ""; + } + } + + static Identity withMembership(Identity identity, Membership membership, long now) { + if (membership.observedAt() < now - 45_000) return identity; + return new Identity(identity.faction(), identity.race(), identity.staff(), identity.vip(), + membership.clan(), identity.clanTag(), membership.company(), identity.companyName()); + } + + static boolean inGroup(Channel c, Identity i) { + return switch (c) { + case CLAN -> !i.clanKey().isBlank(); + case COMPANY -> !i.companyKey().isBlank(); + default -> true; + }; + } + + static boolean canSend(Channel c, Identity sender, boolean staffPerm) { + return switch (c) { case STAFF -> staffPerm; case CLAN, COMPANY -> inGroup(c, sender); case GLOBAL -> true; }; + } + + /** Whether {@code viewer} sees a message sent in {@code c} by {@code sender}. */ + static boolean receives(Channel c, Identity sender, Identity viewer, boolean viewerStaff, boolean viewerSpy) { + return switch (c) { + case GLOBAL -> true; + case STAFF -> viewerStaff; + case CLAN -> inGroup(c, viewer) && viewer.clanKey().equals(sender.clanKey()) || viewerSpy; + case COMPANY -> inGroup(c, viewer) && viewer.companyKey().equals(sender.companyKey()) || viewerSpy; + }; + } + + /** Public prefix as legacy ampersand text, in the configured order. Only cleaned values are inserted. */ + static String prefix(Identity i, List order) { + List parts = new ArrayList<>(); + String c = color(i.faction()); + for (String key : order) { + switch (key) { + case "staff" -> { if (i.staff()) parts.add("&c&l[STAFF]&r"); else if (i.vip()) parts.add("&6&l[VIP]&r"); } + case "race" -> { if (!i.race().isBlank()) parts.add(c + "[" + i.race() + "]&r"); } + case "clan" -> { if (!i.clanTag().isBlank()) parts.add("&6[" + i.clanTag() + "]&r"); } + case "company" -> { if (!i.companyName().isBlank()) parts.add("&3[" + i.companyName() + "]&r"); } + default -> { } + } + } + return String.join(" ", parts); + } +} diff --git a/DuneChat/src/main/java/com/example/dunechat/DiscordPrivacy.java b/DuneChat/src/main/java/com/example/dunechat/DiscordPrivacy.java new file mode 100644 index 00000000..fa7d12cf --- /dev/null +++ b/DuneChat/src/main/java/com/example/dunechat/DiscordPrivacy.java @@ -0,0 +1,24 @@ +package com.example.dunechat; + +import github.scarsz.discordsrv.DiscordSRV; +import github.scarsz.discordsrv.api.Subscribe; +import github.scarsz.discordsrv.api.events.GameChatMessagePreProcessEvent; + +/** Leave the existing public relay in place and prevent it from processing private messages. */ +public final class DiscordPrivacy implements AutoCloseable { + private final DuneChat chat; + + DiscordPrivacy(DuneChat chat) { + this.chat = chat; + DiscordSRV.api.subscribe(this); + } + + @Subscribe + public void beforeRelay(GameChatMessagePreProcessEvent event) { + if (event.getPlayer() != null && chat.isPrivate(event.getPlayer())) event.setCancelled(true); + } + + @Override public void close() { + DiscordSRV.api.unsubscribe(this); + } +} diff --git a/DuneChat/src/main/java/com/example/dunechat/DuneChat.java b/DuneChat/src/main/java/com/example/dunechat/DuneChat.java new file mode 100644 index 00000000..d4edf650 --- /dev/null +++ b/DuneChat/src/main/java/com/example/dunechat/DuneChat.java @@ -0,0 +1,205 @@ +package com.example.dunechat; + +import com.example.dunechat.ChatLogic.Channel; +import com.example.dunechat.ChatLogic.Identity; +import io.papermc.paper.event.player.AsyncChatEvent; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Chat prefixes (race, clan, company) and private clan, company and staff channels. + * Identity and private membership come from the installed JARVIS read APIs. + * Chat is per server; there is no cross-server relay. + */ +public final class DuneChat extends JavaPlugin implements Listener, CommandExecutor { + private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacyAmpersand(); + private final Map identities = new ConcurrentHashMap<>(); + private final Map memberships = new ConcurrentHashMap<>(); + private final Map refreshing = new ConcurrentHashMap<>(); + private ChatIdentitySource identitySource; + private final Map mode = new ConcurrentHashMap<>(); + private record CommandMessage(UUID sender, Channel channel) {} + private final ThreadLocal commandMessage = new ThreadLocal<>(); + private DiscordPrivacy discordPrivacy; + private final Set spies = ConcurrentHashMap.newKeySet(); + private List order = List.of("staff", "race", "clan", "company"); + private int max = 16; + + @Override public void onEnable() { + saveDefaultConfig(); + order = getConfig().getStringList("prefix-order"); + max = Math.max(4, getConfig().getInt("max-prefix-length", 16)); + try { + identitySource = new ChatIdentitySource(getServer().getPluginManager().getPlugin("JarvisTranslator")); + } catch (ReflectiveOperationException | IllegalStateException unavailable) { + getLogger().warning("JARVIS identity unavailable; organisation channels are unavailable."); + } + if (getServer().getPluginManager().isPluginEnabled("DiscordSRV")) { + try { + discordPrivacy = new DiscordPrivacy(this); + } catch (RuntimeException | LinkageError unavailable) { + getLogger().warning("DiscordSRV privacy hook failed; private channels are unavailable."); + } + } + getServer().getPluginManager().registerEvents(this, this); + getServer().getScheduler().runTaskTimer(this, () -> Bukkit.getOnlinePlayers().forEach(this::refresh), 20L, 400L); + for (String c : List.of("clanchat", "companychat", "staffchat", "globalchat", "chatspy")) { + var cmd = getCommand(c); + if (cmd != null) cmd.setExecutor(this); + } + } + + @Override public void onDisable() { + if (discordPrivacy != null) discordPrivacy.close(); + } + + @EventHandler public void onJoin(PlayerJoinEvent event) { refresh(event.getPlayer()); } + + private void refresh(Player player) { + UUID id = player.getUniqueId(); + if (identitySource == null || refreshing.putIfAbsent(id, player) != null) return; + getServer().getScheduler().runTaskAsynchronously(this, () -> { + Identity display = Identity.NONE; + ChatLogic.Membership membership = ChatLogic.Membership.NONE; + try { display = ChatLogic.house(identitySource.house(id), max); } + catch (ReflectiveOperationException | RuntimeException unavailable) { /* Default display. */ } + try { membership = ChatLogic.memberships(identitySource.organisations(id), id, System.currentTimeMillis()); } + catch (ReflectiveOperationException | RuntimeException unavailable) { /* Private access fails closed. */ } + Identity nextDisplay = display; + ChatLogic.Membership nextMembership = membership; + if (!isEnabled()) return; + getServer().getScheduler().runTask(this, () -> { + if (!refreshing.remove(id, player) || Bukkit.getPlayer(id) != player || !player.isOnline()) return; + identities.put(id, nextDisplay); + memberships.put(id, nextMembership); + }); + }); + } + + private Identity of(Player p) { + UUID id = p.getUniqueId(); + return ChatLogic.withMembership(identities.getOrDefault(id, Identity.NONE), + memberships.getOrDefault(id, ChatLogic.Membership.NONE), System.currentTimeMillis()); + } + private boolean staff(Player p) { return p.hasPermission("dunechat.staff"); } + private Channel channel(Player player) { + var command = commandMessage.get(); + return command != null && command.sender().equals(player.getUniqueId()) + ? command.channel() : mode.getOrDefault(player.getUniqueId(), Channel.GLOBAL); + } + boolean isPrivate(Player player) { return channel(player) != Channel.GLOBAL; } + + private boolean privateReady() { + return discordPrivacy != null || !getServer().getPluginManager().isPluginEnabled("DiscordSRV"); + } + + @EventHandler public void onQuit(PlayerQuitEvent e) { + UUID id = e.getPlayer().getUniqueId(); identities.remove(id); memberships.remove(id); refreshing.remove(id, e.getPlayer()); mode.remove(id); spies.remove(id); + } + + /** Never un-cancels: if another plugin cancelled the chat (mute, filter), we leave it alone. */ + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onChat(AsyncChatEvent e) { + Player p = e.getPlayer(); + Channel c = channel(p); + Identity me = of(p); + if (c != Channel.GLOBAL) { + if (!privateReady() || !ChatLogic.canSend(c, me, staff(p))) { + e.setCancelled(true); + p.sendMessage(Component.text("Your private channel is unavailable. Use /g to return to public chat.", NamedTextColor.RED)); + return; + } + } + final Channel channel = c; + if (channel != Channel.GLOBAL) { + e.viewers().removeIf(v -> !(v instanceof Player vp) || !ChatLogic.receives(channel, me, of(vp), staff(vp), spies.contains(vp.getUniqueId()) && vp.hasPermission("dunechat.spy"))); + } + e.renderer((source, name, message, viewer) -> render(channel, me, name, message)); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void logAcceptedPrivateChat(AsyncChatEvent event) { + Channel channel = channel(event.getPlayer()); + if (channel != Channel.GLOBAL) logPrivate(channel, event.getPlayer(), event.message()); + } + + private Component render(Channel c, Identity me, Component name, Component message) { + Component sep = Component.text(": ", NamedTextColor.GRAY); + if (c == Channel.GLOBAL) { + String prefix = ChatLogic.prefix(me, order); + Component head = prefix.isEmpty() ? Component.empty() : LEGACY.deserialize(prefix).append(Component.space()); + return head.append(name).append(sep).append(message); + } + String label = switch (c) { + case CLAN -> getConfig().getString("clan-chat-label", "CLAN") + (me.clanTag().isBlank() ? "" : " " + me.clanTag()); + case COMPANY -> getConfig().getString("company-chat-label", "COMPANY") + (me.companyName().isBlank() ? "" : " " + me.companyName()); + default -> getConfig().getString("staff-chat-label", "STAFF"); + }; + NamedTextColor color = c == Channel.CLAN ? NamedTextColor.GOLD : c == Channel.COMPANY ? NamedTextColor.DARK_AQUA : NamedTextColor.RED; + return Component.text("[" + ChatLogic.clean(label, 40) + "] ", color).append(name).append(sep).append(message.color(NamedTextColor.WHITE)); + } + + private void logPrivate(Channel c, Player p, Component message) { + if (getConfig().getBoolean("log-private-chat", false)) + getLogger().info("[" + c + "] " + p.getName() + ": " + net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(message)); + } + + @Override public boolean onCommand(CommandSender s, Command cmd, String label, String[] a) { + if (!(s instanceof Player p)) { s.sendMessage("Players only."); return true; } + Channel c = switch (cmd.getName()) { + case "clanchat" -> Channel.CLAN; case "companychat" -> Channel.COMPANY; case "staffchat" -> Channel.STAFF; + case "globalchat" -> Channel.GLOBAL; default -> null; + }; + if (cmd.getName().equals("chatspy")) { + if (!p.hasPermission("dunechat.spy")) { p.sendMessage(Component.text("No permission.", NamedTextColor.RED)); return true; } + boolean on = spies.add(p.getUniqueId()); if (!on) spies.remove(p.getUniqueId()); + p.sendMessage(Component.text("Chat spy " + (on ? "on" : "off") + ".", NamedTextColor.GOLD)); return true; + } + if (c == null) return false; + Identity me = of(p); + if (c == Channel.GLOBAL) { mode.remove(p.getUniqueId()); p.sendMessage(Component.text("Public chat.", NamedTextColor.GOLD)); return true; } + if (!privateReady()) { + p.sendMessage(Component.text("Private channels are unavailable.", NamedTextColor.RED)); + return true; + } + if (!ChatLogic.canSend(c, me, staff(p))) { + p.sendMessage(Component.text(c == Channel.STAFF ? "No permission." : "You are not in a " + (c == Channel.CLAN ? "clan" : "company") + ".", NamedTextColor.RED)); return true; + } + if (a.length == 0) { + boolean off = mode.get(p.getUniqueId()) == c; + if (off) mode.remove(p.getUniqueId()); else mode.put(p.getUniqueId(), c); + p.sendMessage(Component.text(off ? "Public chat." : c + " chat on. /g to leave.", NamedTextColor.GOLD)); return true; + } + String message = String.join(" ", a).strip(); + if (message.isEmpty() || message.length() > 256 || message.startsWith("/") + || message.chars().anyMatch(ch -> ch == 'ยง' || Character.isISOControl(ch))) { + p.sendMessage(Component.text("Enter ordinary chat text of up to 256 characters.", NamedTextColor.RED)); + return true; + } + commandMessage.set(new CommandMessage(p.getUniqueId(), c)); + try { + p.chat(message); + } finally { + commandMessage.remove(); + } + return true; + } +} diff --git a/DuneChat/src/main/resources/config.yml b/DuneChat/src/main/resources/config.yml new file mode 100644 index 00000000..132da669 --- /dev/null +++ b/DuneChat/src/main/resources/config.yml @@ -0,0 +1,8 @@ +# Prefix order in public chat. Remove an entry to hide it. +prefix-order: [staff, race, clan, company] +max-prefix-length: 16 +clan-chat-label: "CLAN" +company-chat-label: "COMPANY" +staff-chat-label: "STAFF" +# Staff with dunechat.spy can opt in using /chatspy. Private messages stay out of the console by default. +log-private-chat: false diff --git a/DuneChat/src/main/resources/plugin.yml b/DuneChat/src/main/resources/plugin.yml new file mode 100644 index 00000000..787b4821 --- /dev/null +++ b/DuneChat/src/main/resources/plugin.yml @@ -0,0 +1,32 @@ +name: DuneChat +version: 1.0.0 +main: com.example.dunechat.DuneChat +api-version: '1.21.8' +softdepend: [DiscordSRV] +depend: [JarvisTranslator] +description: Chat prefixes for race, clan and company, plus private clan, company and staff channels. +commands: + clanchat: + aliases: [cc] + description: Send to your private clan chat, or toggle it + usage: /cc [message] + companychat: + aliases: [coc] + description: Send to your private company chat, or toggle it + usage: /coc [message] + staffchat: + aliases: [sc] + description: Staff-only chat + usage: /sc [message] + globalchat: + aliases: [gc, g] + description: Return to public chat + usage: /g + chatspy: + description: Staff - watch clan and company chats + usage: /chatspy +permissions: + dunechat.staff: + default: op + dunechat.spy: + default: op diff --git a/DuneChat/src/test/java/com/example/dunechat/ChatLogicTest.java b/DuneChat/src/test/java/com/example/dunechat/ChatLogicTest.java new file mode 100644 index 00000000..729db560 --- /dev/null +++ b/DuneChat/src/test/java/com/example/dunechat/ChatLogicTest.java @@ -0,0 +1,92 @@ +package com.example.dunechat; + +import com.example.dunechat.ChatLogic.Channel; +import com.example.dunechat.ChatLogic.Identity; +import com.google.gson.JsonParser; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class ChatLogicTest { + private static Identity parse(String briefing, String house, String race) { + return ChatLogic.parse(JsonParser.parseString(briefing).getAsJsonObject(), house, race, 16); + } + private static final String CLAN = "aaaaaaaa-0000-0000-0000-000000000001"; + private static final String COMPANY = "bbbbbbbb-0000-0000-0000-000000000001"; + private static final String OTHER = "aaaaaaaa-0000-0000-0000-000000000002"; + private static final java.util.UUID ACTOR = java.util.UUID.fromString("cccccccc-0000-0000-0000-000000000001"); + + private static Identity proof(Identity display, String clan, String company) { + return ChatLogic.withMembership(display, new ChatLogic.Membership(clan, company, 100000L), 100001L); + } + + private static final String DATA = "{\"briefing\":{\"identity\":{\"staff\":false,\"vip\":true,\"clans\":[{\"id\":\"c1\",\"name\":\"Sand Hawks\",\"tag\":\"HAWK\"},{\"name\":\"Second\"}],\"companies\":[{\"id\":\"k1\",\"name\":\"Spice Co\"}]}}}"; + + @Test void parsesClanCompanyAndUsesOnlyTheFirstOfEach() { + Identity i = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY); + assertEquals(CLAN, i.clanKey()); assertEquals("HAWK", i.clanTag()); + assertEquals(COMPANY, i.companyKey()); assertEquals("Spice Co", i.companyName()); + assertTrue(i.vip()); assertFalse(i.staff()); + } + + @Test void prefixFollowsConfiguredOrderAndSkipsMissingParts() { + Identity i = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY); + assertEquals("&6&l[VIP]&r &b[Fremen]&r &6[HAWK]&r &3[Spice Co]&r", ChatLogic.prefix(i, List.of("staff", "race", "clan", "company"))); + assertEquals("&3[Spice Co]&r &b[Fremen]&r", ChatLogic.prefix(i, List.of("company", "race"))); + assertEquals("", ChatLogic.prefix(Identity.NONE, List.of("staff", "race", "clan", "company"))); + } + + @Test void colourAndMarkupCannotBeInjectedThroughNames() { + Identity i = parse("{\"briefing\":{\"identity\":{\"clans\":[{\"tag\":\"&4EVILยงk\"}]}}}", "atreides", "&cRace%"); + assertFalse(ChatLogic.prefix(i, List.of("race", "clan")).contains("ยง")); + assertEquals("4EVILredk", i.clanTag(), "markup characters are removed, nothing is interpreted"); + assertEquals("cRace", i.race()); + } + + @Test void privateChannelsReachOnlyTheSameGroup() { + Identity me = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY); + Identity mate = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY); + Identity otherClan = proof(Identity.NONE, OTHER, COMPANY); + assertTrue(ChatLogic.receives(Channel.CLAN, me, mate, false, false)); + assertFalse(ChatLogic.receives(Channel.CLAN, me, otherClan, false, false)); + assertTrue(ChatLogic.receives(Channel.COMPANY, me, otherClan, false, false), "same company, different clan"); + assertFalse(ChatLogic.receives(Channel.CLAN, me, Identity.NONE, false, false)); + assertTrue(ChatLogic.receives(Channel.CLAN, me, Identity.NONE, true, true), "spy sees it"); + } + + @Test void aClanAndACompanyAreIndependent() { + Identity onlyCompany = proof(Identity.NONE, "", COMPANY); + assertFalse(ChatLogic.canSend(Channel.CLAN, onlyCompany, false)); + assertTrue(ChatLogic.canSend(Channel.COMPANY, onlyCompany, false)); + } + + @Test void staffChatNeedsThePermissionToSendAndToRead() { + assertFalse(ChatLogic.canSend(Channel.STAFF, Identity.NONE, false)); + assertTrue(ChatLogic.canSend(Channel.STAFF, Identity.NONE, true)); + assertTrue(ChatLogic.receives(Channel.STAFF, Identity.NONE, Identity.NONE, true, false)); + assertFalse(ChatLogic.receives(Channel.STAFF, Identity.NONE, Identity.NONE, false, true), "spy alone is not staff chat"); + } + + @Test void missingBriefingGivesNoPrefixAndNoGroups() { + Identity i = ChatLogic.parse(null, null, null, 16); + assertEquals("", ChatLogic.prefix(i, List.of("race", "clan", "company"))); + assertFalse(ChatLogic.inGroup(Channel.CLAN, i)); + } + + @Test void onlyFreshExplicitMembershipAuthorizesPrivateChat() { + var display = parse(DATA, "fremen", "Fremen"); + assertFalse(ChatLogic.canSend(Channel.CLAN, display, false), "public label alone grants nothing"); + var response = JsonParser.parseString(""" + {"ok":true,"schema":1,"observedAt":100000,"clans":[ + {"id":"%s","lifecycle":"active","canManage":true,"members":[]}, + {"id":"%s","lifecycle":"active","members":[{"uuid":"%s"}]} + ],"companies":[]} + """.formatted(OTHER, CLAN, ACTOR)).getAsJsonObject(); + var membership = ChatLogic.memberships(response, ACTOR, 100001L); + assertEquals(CLAN, membership.clan()); + assertTrue(ChatLogic.canSend(Channel.CLAN, ChatLogic.withMembership(display, membership, 100001L), false)); + assertFalse(ChatLogic.canSend(Channel.CLAN, ChatLogic.withMembership(display, membership, 145001L), false)); + } +} diff --git a/DuneChest/build.gradle.kts b/DuneChest/build.gradle.kts new file mode 100644 index 00000000..e4f86494 --- /dev/null +++ b/DuneChest/build.gradle.kts @@ -0,0 +1,28 @@ +plugins { java } +group = "com.example" +version = "1.0.9" +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") + maven("https://repo.opencollab.dev/main/") +} +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT") + testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} +sourceSets.main { java.srcDir("../gui-common/src/main/java") } +tasks.jar { archiveFileName.set("DuneChest.jar") } +java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } +tasks.withType { options.encoding = "UTF-8" } +tasks.test { useJUnitPlatform() } + +val paperValidation by sourceSets.creating { + compileClasspath += sourceSets.main.get().output + configurations.compileClasspath.get() +} +tasks.register("paperValidationJar") { + archiveFileName.set("DuneChestPaperValidation.jar") + from(paperValidation.output) +} diff --git a/DuneChest/settings.gradle.kts b/DuneChest/settings.gradle.kts new file mode 100644 index 00000000..febff850 --- /dev/null +++ b/DuneChest/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "DuneChest" diff --git a/DuneChest/src/main/java/com/example/dunechest/BeaconRules.java b/DuneChest/src/main/java/com/example/dunechest/BeaconRules.java new file mode 100644 index 00000000..c21bda2c --- /dev/null +++ b/DuneChest/src/main/java/com/example/dunechest/BeaconRules.java @@ -0,0 +1,41 @@ +package com.example.dunechest; + +import java.util.List; +import java.util.Set; + +/** Pure vanilla-beacon rules (no Bukkit types): effect availability per pyramid level, range and duration. */ +public final class BeaconRules { + private static final Set COMMODITY_METADATA = Set.of( + "dunerealms:quality", "dunerealms:equipment_mark", "dunerealms:item_class", + "dunerealms:metadata_policy", "dunerealms:metadata_lore_header", "dunerealms:origin_world"); + + static boolean ordinaryPaymentMetadata(Set keys) { + return COMMODITY_METADATA.containsAll(keys); + } + + private BeaconRules() {} + + public static final List LEVEL1 = List.of("SPEED", "HASTE"), LEVEL2 = List.of("RESISTANCE", "JUMP_BOOST"), LEVEL3 = List.of("STRENGTH"); + public static final String SECONDARY_REGEN = "REGENERATION"; + + /** Primary effects available at a pyramid level (0 = none). */ + public static List primaries(int level) { + var out = new java.util.ArrayList(); + if (level >= 1) out.addAll(LEVEL1); if (level >= 2) out.addAll(LEVEL2); if (level >= 3) out.addAll(LEVEL3); + return out; + } + /** Secondary effects: only at level 4 - Regeneration, or the chosen primary at power II (represented by the primary's own name). */ + public static List secondaries(int level, String primary) { + if (level < 4 || primary == null) return List.of(); + return List.of(SECONDARY_REGEN, primary); + } + public static boolean validChoice(int level, String primary, String secondary) { + if (primary == null || !primaries(level).contains(primary)) return false; + return secondary == null || secondaries(level, primary).contains(secondary); + } + public static int range(int level) { return level * 10 + 10; } + public static int durationTicks(int level) { return (level * 2 + 9) * 20; } + /** Amplifier of the primary effect: II when the secondary repeats it. */ + public static int primaryAmplifier(int level, String primary, String secondary) { return level >= 4 && primary != null && primary.equals(secondary) ? 1 : 0; } + public static boolean regeneration(int level, String primary, String secondary) { return level >= 4 && SECONDARY_REGEN.equals(secondary) && !SECONDARY_REGEN.equals(primary); } +} diff --git a/DuneChest/src/main/java/com/example/dunechest/DuneChest.java b/DuneChest/src/main/java/com/example/dunechest/DuneChest.java new file mode 100644 index 00000000..6589323c --- /dev/null +++ b/DuneChest/src/main/java/com/example/dunechest/DuneChest.java @@ -0,0 +1,18 @@ +package com.example.dunechest; + +import java.util.Objects; +import org.bukkit.plugin.java.JavaPlugin; + +/** DuneChest: colour-linked Ender Chests, Speed Hoppers and Auto Crafters, per planet. */ +public final class DuneChest extends JavaPlugin { + private StorageModule storage; + public StorageModule storage() { return storage; } + + @Override public void onEnable() { + storage = new StorageModule(this); + storage.start(); + Objects.requireNonNull(getCommand("dunechest")).setExecutor(storage); + } + + @Override public void onDisable() { if (storage != null) storage.stop(); storage = null; } +} diff --git a/DuneChest/src/main/java/com/example/dunechest/StorageData.java b/DuneChest/src/main/java/com/example/dunechest/StorageData.java new file mode 100644 index 00000000..89ffd21f --- /dev/null +++ b/DuneChest/src/main/java/com/example/dunechest/StorageData.java @@ -0,0 +1,93 @@ +package com.example.dunechest; + +import java.io.File; +import java.io.IOException; +import java.util.*; +import org.bukkit.*; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +/** Persistent state of the custom storage blocks on this planet: placed blocks and colour-frequency inventories. */ +final class StorageData { + enum Kind { ENDER_CHEST, SPEED_HOPPER, AUTO_CRAFTER, BEACON } + + static final class Placed { + Kind kind; int[] colors = new int[3]; UUID owner; boolean priv; int tier = 1; boolean whitelist = false; + List filter = new ArrayList<>(); ItemStack[] recipe = new ItemStack[9]; int cooldown; Location loc; String primary, secondary; + } + + /** Holder of a frequency inventory so listeners recognise it. */ + static final class FreqHolder implements InventoryHolder { + final String key; Inventory inventory; + FreqHolder(String key) { this.key = key; } + @Override public Inventory getInventory() { return inventory; } + } + + private final Plugin plugin; private final File blocksFile, invFile; + final Map blocks = new LinkedHashMap<>(); + final Map inventories = new HashMap<>(); + boolean dirty; + + StorageData(Plugin plugin) { this.plugin = plugin; blocksFile = new File(plugin.getDataFolder(), "storage-blocks.yml"); invFile = new File(plugin.getDataFolder(), "storage-inventories.yml"); } + + static String key(Location l) { return l.getWorld().getName() + ";" + l.getBlockX() + ";" + l.getBlockY() + ";" + l.getBlockZ(); } + static String key(org.bukkit.block.Block b) { return key(b.getLocation()); } + + Placed at(org.bukkit.block.Block b) { return blocks.get(key(b)); } + Placed at(Location l) { return l == null || l.getWorld() == null ? null : blocks.get(key(l)); } + + Inventory inventory(String frequency) { + var holder = inventories.computeIfAbsent(frequency, k -> new FreqHolder(k)); + if (holder.inventory == null) holder.inventory = Bukkit.createInventory(holder, 27, net.kyori.adventure.text.Component.text("Ender Chest")); + return holder.inventory; + } + + // ---------- persistence ---------- + void load() { + blocks.clear(); inventories.clear(); + if (blocksFile.exists()) { + var y = YamlConfiguration.loadConfiguration(blocksFile); var sec = y.getConfigurationSection("blocks"); + if (sec != null) for (String k : sec.getKeys(false)) { + ConfigurationSection s = sec.getConfigurationSection(k); if (s == null) continue; + try { + Placed p = new Placed(); p.kind = Kind.valueOf(s.getString("kind", "ENDER_CHEST")); + p.colors = StorageRules.parseColors(s.getString("colors")); String o = s.getString("owner"); p.owner = o == null ? null : UUID.fromString(o); + p.primary = s.getString("primary"); p.secondary = s.getString("secondary"); p.priv = s.getBoolean("private"); p.tier = s.getInt("tier", 1); p.whitelist = s.getBoolean("whitelist"); + for (String m : s.getStringList("filter")) { Material mat = Material.matchMaterial(m); if (mat != null) p.filter.add(mat); } + List rec = s.getList("recipe"); + if (rec != null) for (int i = 0; i < 9 && i < rec.size(); i++) p.recipe[i] = rec.get(i) instanceof ItemStack st ? st : null; + blocks.put(k, p); + } catch (RuntimeException ex) { plugin.getLogger().warning("Skipped bad storage block " + k + ": " + ex.getMessage()); } + } + } + if (invFile.exists()) { + var y = YamlConfiguration.loadConfiguration(invFile); var sec = y.getConfigurationSection("inventories"); + if (sec != null) for (String k : sec.getKeys(false)) { + String freq = k.replace('/', ':'); var inv = inventory(freq); List items = sec.getList(k); + if (items != null) for (int i = 0; i < items.size() && i < inv.getSize(); i++) inv.setItem(i, items.get(i) instanceof ItemStack st ? st : null); + } + } + } + + void save() { + var yb = new YamlConfiguration(); + for (var e : blocks.entrySet()) { + String b = "blocks." + e.getKey().replace('.', '_'); Placed p = e.getValue(); + yb.set(b + ".kind", p.kind.name()); yb.set(b + ".colors", StorageRules.colorsToString(p.colors)); yb.set(b + ".owner", p.owner == null ? null : p.owner.toString()); + yb.set(b + ".primary", p.primary); yb.set(b + ".secondary", p.secondary); yb.set(b + ".private", p.priv); yb.set(b + ".tier", p.tier); yb.set(b + ".whitelist", p.whitelist); + yb.set(b + ".filter", p.filter.stream().map(Enum::name).toList()); yb.set(b + ".recipe", Arrays.asList(p.recipe)); + } + var yi = new YamlConfiguration(); + for (var e : inventories.entrySet()) { + if (e.getValue().inventory == null) continue; + boolean any = false; for (ItemStack s : e.getValue().inventory.getContents()) if (s != null && !s.getType().isAir()) { any = true; break; } + if (any) yi.set("inventories." + e.getKey().replace(':', '/'), Arrays.asList(e.getValue().inventory.getContents())); + } + try { plugin.getDataFolder().mkdirs(); yb.save(blocksFile); yi.save(invFile); dirty = false; } + catch (IOException ex) { plugin.getLogger().warning("Could not save storage data: " + ex.getMessage()); } + } +} diff --git a/DuneChest/src/main/java/com/example/dunechest/StorageItems.java b/DuneChest/src/main/java/com/example/dunechest/StorageItems.java new file mode 100644 index 00000000..931cf8e1 --- /dev/null +++ b/DuneChest/src/main/java/com/example/dunechest/StorageItems.java @@ -0,0 +1,200 @@ +package com.example.dunechest; + +import java.util.*; +import java.util.function.Predicate; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.*; +import org.bukkit.inventory.*; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.plugin.Plugin; + +/** The three custom items, their recipes, and how to recognise them. */ +public final class StorageItems { + public static final String ENDER = "ender_chest", HOPPER = "speed_hopper", CRAFTER = "auto_crafter", WRENCH = "wrench", BEACON = "dune_beacon"; + static final String POWERCORE_NAME = "Ixian Powercore MK XIV"; + static final String REPLICATOR_NAME = "Ixian Replicator MK XIV"; + + static String hopperName(int tier) { + return "Ixian sorting devices MK " + (StorageRules.Tier.of(tier).ordinal() + 1); + } + + private final Plugin plugin; final NamespacedKey type, tier, colors, owner, priv, filter, whitelist, primary, secondary; + + StorageItems(Plugin plugin) { + this.plugin = plugin; + type = new NamespacedKey(plugin, "storage_type"); tier = new NamespacedKey(plugin, "storage_tier"); colors = new NamespacedKey(plugin, "storage_colors"); + owner = new NamespacedKey(plugin, "storage_owner"); priv = new NamespacedKey(plugin, "storage_private"); + primary = new NamespacedKey(plugin, "beacon_primary"); secondary = new NamespacedKey(plugin, "beacon_secondary"); + filter = new NamespacedKey(plugin, "storage_filter"); whitelist = new NamespacedKey(plugin, "storage_whitelist"); + } + + public ItemStack create(String id, int tierNumber) { + Material base = switch (id) { case ENDER -> Material.ENDER_CHEST; case HOPPER -> Material.HOPPER; case WRENCH -> Material.KNOWLEDGE_BOOK; case BEACON -> Material.SEA_LANTERN; default -> Material.CRAFTING_TABLE; }; + ItemStack item = new ItemStack(base); ItemMeta m = item.getItemMeta(); + var pdc = m.getPersistentDataContainer(); pdc.set(type, PersistentDataType.STRING, id); + List lore = new ArrayList<>(); + switch (id) { + case ENDER -> { m.displayName(name("Ender Chest", NamedTextColor.LIGHT_PURPLE)); pdc.set(colors, PersistentDataType.STRING, "0,0,0"); + lore.add(gray("Chests with the same three colours share one inventory.")); + lore.add(gray("Right-click a dye on a pad, or use the colour menu.")); lore.add(gray("Right-click a diamond to make it private.")); lore.add(gray("Sneak + empty hand: colour menu.")); m.setItemModel(new NamespacedKey("dunerealms", "ender_chest")); } + case HOPPER -> { int t = Math.max(1, Math.min(3, tierNumber)); var tr = StorageRules.Tier.of(t); pdc.set(tier, PersistentDataType.INTEGER, t); + m.displayName(name(hopperName(t), hopperColour(t))); + lore.add(gray(String.format(Locale.ROOT, "%.0f items/s (vanilla 2.5)", tr.itemsPerSecond()))); lore.add(gray("Sneak + empty hand: item filter.")); lore.add(gray("Or left-click with a Wrench.")); m.setItemModel(new NamespacedKey("dunerealms", "speed_hopper_" + t)); } + case BEACON -> { m.displayName(name(POWERCORE_NAME, NamedTextColor.AQUA)); + lore.add(gray("Works like a vanilla beacon, but with no beam")); lore.add(gray("and no need for open sky.")); lore.add(gray("Right-click to choose its effects.")); + m.setItemModel(new NamespacedKey("dunerealms", "dune_beacon")); } + case WRENCH -> { m.displayName(name("Wrench", NamedTextColor.GOLD)); lore.add(gray("Left-click a DuneChest device to open its panel.")); lore.add(gray("Works on Bedrock too.")); m.setItemModel(new NamespacedKey("dunerealms", "wrench")); m.setMaxStackSize(1); } + default -> { m.displayName(name(REPLICATOR_NAME, NamedTextColor.GREEN)); lore.add(gray("Crafts from the container above into the container below.")); lore.add(gray("Right-click to set the recipe.")); } + } + m.lore(lore); m.setEnchantmentGlintOverride(true); + item.setItemMeta(m); return item; + } + + /** Item used by the overlay display on a placed Speed Hopper: custom model, spout down or sideways. */ + ItemStack hopperDisplayItem(int tierNumber, boolean side) { + ItemStack it = new ItemStack(Material.HOPPER); ItemMeta m = it.getItemMeta(); + m.setItemModel(new NamespacedKey("dunerealms", "speed_hopper_" + Math.max(1, Math.min(3, tierNumber)) + (side ? "_side" : ""))); + it.setItemMeta(m); return it; + } + + private static NamedTextColor hopperColour(int tier) { + return tier == 1 ? NamedTextColor.GOLD : tier == 2 ? NamedTextColor.AQUA : NamedTextColor.LIGHT_PURPLE; + } + + private static Component legacyHopperName(int tier) { + return name("Speed Hopper Mk " + "I".repeat(tier), hopperColour(tier)); + } + + private static ItemStack withDisplayName(ItemStack original, Component label) { + ItemStack copy = original.asOne(); + ItemMeta meta = copy.getItemMeta(); + meta.displayName(label); + copy.setItemMeta(meta); + return copy; + } + + private static final NamespacedKey JARVIS_HEADER = new NamespacedKey("dunerealms", "metadata_lore_header"); + private static final NamespacedKey JARVIS_ORIGIN = new NamespacedKey("dunerealms", "origin_world"); + private static final List JARVIS_GRADE_FIELDS = List.of( + "quality", "equipment_mark", "item_class", "metadata_policy").stream() + .map(key -> new NamespacedKey("dunerealms", key)).toList(); + + private RecipeChoice hopperChoice(ItemStack current, int tier) { + try { + var factory = RecipeChoice.class.getMethod("predicateChoice", Predicate.class, ItemStack.class); + Predicate exactDevice = item -> item != null && !item.isEmpty() + && matchesCraftingIngredient(current, item); + return (RecipeChoice) factory.invoke(null, exactDevice, current); + } catch (NoSuchMethodException unavailable) { + return new RecipeChoice.ExactChoice(current, withDisplayName(current, legacyHopperName(tier))); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException("Cannot register the exact hopper upgrade ingredient", failure); + } + } + + boolean matchesCraftingIngredient(ItemStack template, ItemStack source) { + if (template.isSimilar(source)) return true; + if (template.getType() != source.getType()) return false; + ItemStack comparableTemplate = withoutJarvisDecoration(template); + ItemStack comparableSource = withoutJarvisDecoration(source); + if (comparableTemplate.isSimilar(comparableSource)) return true; + if (template.getType() != Material.HOPPER + || !HOPPER.equals(typeOf(template)) || !HOPPER.equals(typeOf(source))) return false; + int tier = tierOf(template); + if (tier < 1 || tier > 3 || tierOf(source) != tier) return false; + Component oldName = legacyHopperName(tier); + Component currentName = name(hopperName(tier), hopperColour(tier)); + Component templateName = comparableTemplate.getItemMeta().displayName(); + Component sourceName = comparableSource.getItemMeta().displayName(); + boolean sameTierRename = oldName.equals(templateName) && currentName.equals(sourceName) + || currentName.equals(templateName) && oldName.equals(sourceName); + return sameTierRename && withDisplayName(comparableTemplate, sourceName).isSimilar(comparableSource); + } + + /** Compare without JARVIS grading and origin display fields. The supplied item is never modified. */ + private static ItemStack withoutJarvisDecoration(ItemStack item) { + ItemMeta meta = item.getItemMeta(); + var data = meta.getPersistentDataContainer(); + if (!data.has(JARVIS_HEADER) && !data.has(JARVIS_ORIGIN) + && JARVIS_GRADE_FIELDS.stream().noneMatch(data::has)) return item; + var lore = new ArrayList<>(meta.hasLore() ? meta.lore() : List.of()); + var plain = PlainTextComponentSerializer.plainText(); + String header = data.get(JARVIS_HEADER, PersistentDataType.STRING); + if (header != null && !lore.isEmpty() && header.equals(plain.serialize(lore.getFirst()))) { + lore.removeFirst(); + if (!lore.isEmpty() && plain.serialize(lore.getFirst()).isBlank()) lore.removeFirst(); + } + if (data.has(JARVIS_ORIGIN, PersistentDataType.STRING) && !lore.isEmpty() + && plain.serialize(lore.getLast()).startsWith("Origin world: ")) lore.removeLast(); + data.remove(JARVIS_HEADER); + data.remove(JARVIS_ORIGIN); + JARVIS_GRADE_FIELDS.forEach(data::remove); + meta.lore(lore.isEmpty() ? null : lore); + ItemStack copy = item.asOne(); + copy.setItemMeta(meta); + return copy; + } + + private static Component name(String s, NamedTextColor c) { return Component.text(s, c).decoration(TextDecoration.ITALIC, false); } + private static Component gray(String s) { return Component.text(s, NamedTextColor.GRAY).decoration(TextDecoration.ITALIC, false); } + + public String typeOf(ItemStack item) { return item == null || !item.hasItemMeta() ? null : item.getItemMeta().getPersistentDataContainer().get(type, PersistentDataType.STRING); } + int tierOf(ItemStack item) { Integer t = item.getItemMeta().getPersistentDataContainer().get(tier, PersistentDataType.INTEGER); return t == null ? 1 : t; } + + /** Item for a picked-up placed block, carrying its settings. */ + ItemStack fromPlaced(StorageData.Placed p) { + String id = switch (p.kind) { case ENDER_CHEST -> ENDER; case SPEED_HOPPER -> HOPPER; case AUTO_CRAFTER -> CRAFTER; case BEACON -> BEACON; }; + ItemStack item = create(id, p.tier); ItemMeta m = item.getItemMeta(); var pdc = m.getPersistentDataContainer(); + if (p.kind == StorageData.Kind.ENDER_CHEST) { + pdc.set(colors, PersistentDataType.STRING, StorageRules.colorsToString(p.colors)); + if (p.priv && p.owner != null) { pdc.set(priv, PersistentDataType.BYTE, (byte) 1); pdc.set(owner, PersistentDataType.STRING, p.owner.toString()); } + } else if (p.kind == StorageData.Kind.BEACON) { + if (p.primary != null) pdc.set(primary, PersistentDataType.STRING, p.primary); + if (p.secondary != null) pdc.set(secondary, PersistentDataType.STRING, p.secondary); + } else if (p.kind == StorageData.Kind.SPEED_HOPPER && !p.filter.isEmpty()) { + pdc.set(filter, PersistentDataType.STRING, String.join(",", p.filter.stream().map(Enum::name).toList())); pdc.set(whitelist, PersistentDataType.BYTE, (byte) (p.whitelist ? 1 : 0)); + } + item.setItemMeta(m); return item; + } + + /** Settings stored on the item being placed. */ + StorageData.Placed toPlaced(ItemStack item, UUID placer) { + String id = typeOf(item); var pdc = item.getItemMeta().getPersistentDataContainer(); var p = new StorageData.Placed(); + switch (id == null ? "" : id) { + case ENDER -> { p.kind = StorageData.Kind.ENDER_CHEST; p.colors = StorageRules.parseColors(pdc.get(colors, PersistentDataType.STRING)); + p.priv = pdc.has(priv, PersistentDataType.BYTE); String o = pdc.get(owner, PersistentDataType.STRING); p.owner = o == null ? null : UUID.fromString(o); if (p.priv && p.owner == null) p.owner = placer; } + case HOPPER -> { p.kind = StorageData.Kind.SPEED_HOPPER; p.tier = tierOf(item); String f = pdc.get(filter, PersistentDataType.STRING); + if (f != null && !f.isEmpty()) for (String s : f.split(",")) { Material m = Material.matchMaterial(s); if (m != null) p.filter.add(m); } + Byte w = pdc.get(whitelist, PersistentDataType.BYTE); p.whitelist = w != null && w == 1; } + case BEACON -> { p.kind = StorageData.Kind.BEACON; p.primary = pdc.get(primary, PersistentDataType.STRING); p.secondary = pdc.get(secondary, PersistentDataType.STRING); } + default -> p.kind = StorageData.Kind.AUTO_CRAFTER; + } + return p; + } + + void registerRecipes() { + ItemStack ender = create(ENDER, 1), mk1 = create(HOPPER, 1), mk2 = create(HOPPER, 2), mk3 = create(HOPPER, 3), crafter = create(CRAFTER, 1); + shaped("ender_chest", ender, new String[]{"OEO", "OBO", "OOO"}, 'O', Material.OBSIDIAN, 'E', Material.ENDER_EYE, 'B', Material.BARREL); + shaped("speed_hopper_1", mk1, new String[]{"GRG", "RHR", "GRG"}, 'G', Material.GOLD_INGOT, 'R', Material.REDSTONE, 'H', Material.HOPPER); + shaped("speed_hopper_2", mk2, new String[]{"DRD", "RIR", "DRD"}, 'D', Material.DIAMOND, 'R', Material.REDSTONE_BLOCK, 'I', hopperChoice(mk1, 1)); + shaped("speed_hopper_3", mk3, new String[]{"NRN", "RIR", "NRN"}, 'N', Material.NETHERITE_INGOT, 'R', Material.REDSTONE_BLOCK, 'I', hopperChoice(mk2, 2)); + var bk = new NamespacedKey(plugin, "dune_beacon"); Bukkit.removeRecipe(bk); + var br = new org.bukkit.inventory.ShapelessRecipe(bk, create(BEACON, 1)); br.addIngredient(Material.BEACON); br.addIngredient(Material.ENDER_EYE); Bukkit.addRecipe(br); + shaped("wrench", create(WRENCH, 1), new String[]{"I I", " I ", " S "}, 'I', Material.IRON_INGOT, 'S', Material.STICK); + shaped("auto_crafter", crafter, new String[]{"IRI", "RTR", "IDI"}, 'I', Material.IRON_INGOT, 'R', Material.REDSTONE, 'T', Material.CRAFTING_TABLE, 'D', Material.DROPPER); + } + + private void shaped(String key, ItemStack result, String[] shape, Object... ingredients) { + var nk = new NamespacedKey(plugin, key); Bukkit.removeRecipe(nk); + var r = new ShapedRecipe(nk, result); r.shape(shape); + for (int i = 0; i < ingredients.length; i += 2) { + char c = (Character) ingredients[i]; + if (ingredients[i + 1] instanceof Material mat) r.setIngredient(c, mat); else r.setIngredient(c, (RecipeChoice) ingredients[i + 1]); + } + Bukkit.addRecipe(r); + } +} diff --git a/DuneChest/src/main/java/com/example/dunechest/StorageModule.java b/DuneChest/src/main/java/com/example/dunechest/StorageModule.java new file mode 100644 index 00000000..45a6f8fb --- /dev/null +++ b/DuneChest/src/main/java/com/example/dunechest/StorageModule.java @@ -0,0 +1,688 @@ +package com.example.dunechest; + +import java.lang.reflect.Method; +import java.util.*; +import java.util.function.Predicate; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.*; +import org.bukkit.block.*; +import org.bukkit.block.data.Directional; +import org.bukkit.block.data.type.Barrel; +import org.bukkit.command.*; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.block.*; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.inventory.*; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.*; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitTask; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Transformation; +import org.joml.AxisAngle4f; +import org.joml.Vector3f; + +/** + * Custom storage blocks for DuneChest, per planet and without client mods: colour-coded Ender Chests (a tagged barrel, vanilla + * chests untouched), faster Speed Hoppers with item filters, and Auto Crafters. Vanilla barrels, hoppers and crafting tables + * behave normally; only blocks placed from the custom items are tracked. + */ +public final class StorageModule implements Listener, CommandExecutor { + private final JavaPlugin plugin; private final StorageData data; final StorageItems items; + private final List tasks = new ArrayList<>(); + private final Map> displays = new HashMap<>(); private final Map signatures = new HashMap<>(); + private int counter; + private Plugin itemGrader; + private Method markCreatedItem; + private final Map recipeSessions = new HashMap<>(); + private record RecipeSession(InventoryView view, Menu menu) {} + + private Menu menuOf(InventoryView view) { + if (view.getTopInventory().getHolder() instanceof Menu menu) return menu; + RecipeSession session = recipeSessions.get(view.getPlayer().getUniqueId()); + return session != null && session.view() == view ? session.menu() : null; + } + + /** Menu holder: kind is tune, filter or recipe; blockKey names the tracked block. */ + private static final class Menu implements InventoryHolder { + final String kind, blockKey; + final StorageData.Placed recipeBlock; + Inventory inventory; + Menu(String kind, String blockKey) { this(kind, blockKey, null); } + Menu(String kind, String blockKey, StorageData.Placed recipeBlock) { + this.kind = kind; + this.blockKey = blockKey; + this.recipeBlock = recipeBlock; + } + @Override public Inventory getInventory() { return inventory; } + } + + public StorageModule(JavaPlugin plugin) { this.plugin = plugin; this.data = new StorageData(plugin); this.items = new StorageItems(plugin); } + + public void start() { + itemGrader = Bukkit.getPluginManager().getPlugin("JarvisTranslator"); + if (itemGrader != null && itemGrader.isEnabled()) { + try { + markCreatedItem = itemGrader.getClass().getMethod("markCreatedItem", ItemStack.class); + } catch (NoSuchMethodException unavailable) { + plugin.getLogger().warning("JARVIS item grading API is unavailable."); + } + } + data.load(); items.registerRecipes(); + Bukkit.getPluginManager().registerEvents(this, plugin); + tasks.add(Bukkit.getScheduler().runTaskTimer(plugin, this::tick, 40L, 2L)); + } + public void stop() { tasks.forEach(BukkitTask::cancel); displays.values().forEach(l -> l.forEach(this::kill)); displays.clear(); data.save(); } + + /** For the JARVIS Exchange: build a custom item by id (ender_chest, speed_hopper with tier, auto_crafter). */ + public ItemStack issue(String id, int tier) { + ItemStack item = items.create(id, tier); + gradeCreated(item); + return item; + } + + private void gradeCreated(ItemStack item) { + if (markCreatedItem == null || !itemGrader.isEnabled()) return; + try { + markCreatedItem.invoke(itemGrader, item); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException("JARVIS could not grade the DuneChest output", failure); + } + } + + // ---------- helpers ---------- + private static boolean isDye(Material m) { return m.name().endsWith("_DYE") && dyeIndex(m) >= 0; } + private static int dyeIndex(Material m) { try { return DyeColor.valueOf(m.name().substring(0, m.name().length() - 4)).ordinal(); } catch (IllegalArgumentException e) { return -1; } } + private static Material wool(int c) { return Material.valueOf(DyeColor.values()[StorageRules.wrap(c)].name() + "_WOOL"); } + private static Material dye(int c) { return Material.valueOf(DyeColor.values()[StorageRules.wrap(c)].name() + "_DYE"); } + private static Component text(String s, NamedTextColor c) { return Component.text(s, c).decoration(TextDecoration.ITALIC, false); } + private void say(Player p, String s) { p.sendMessage(Component.text(s, NamedTextColor.GRAY)); } + + private Location locate(String key, StorageData.Placed p) { + if (p.loc != null) return p.loc; + String[] a = key.split(";"); World w = Bukkit.getWorld(a[0]); if (w == null) return null; + return p.loc = new Location(w, Integer.parseInt(a[1]), Integer.parseInt(a[2]), Integer.parseInt(a[3])); + } + private BlockFace front(Block b) { return b.getBlockData() instanceof Directional facing ? facing.getFacing() : BlockFace.SOUTH; } + private String freq(StorageData.Placed p) { return StorageRules.frequency(p.colors, p.priv ? p.owner : null); } + private boolean canUse(Player pl, StorageData.Placed p) { return !p.priv || p.owner == null || p.owner.equals(pl.getUniqueId()) || pl.hasPermission("dune.admin"); } + + // ---------- placing / breaking ---------- + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void place(BlockPlaceEvent e) { + String id = items.typeOf(e.getItemInHand()); if (id == null) return; + var p = items.toPlaced(e.getItemInHand(), e.getPlayer().getUniqueId()); + Block b = e.getBlockPlaced(); + if (p.kind == StorageData.Kind.ENDER_CHEST && b.getBlockData() instanceof Barrel bar) { + bar.setFacing(e.getPlayer().getFacing().getOppositeFace()); bar.setOpen(false); b.setBlockData(bar); + } + if (p.kind == StorageData.Kind.ENDER_CHEST && b.getBlockData() instanceof org.bukkit.block.data.type.EnderChest chest) { + chest.setFacing(e.getPlayer().getFacing().getOppositeFace()); + b.setBlockData(chest); + } + data.blocks.put(StorageData.key(b), p); data.dirty = true; + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void breakBlock(BlockBreakEvent e) { + var p = data.at(e.getBlock()); if (p == null) return; + boolean drops = e.isDropItems(); + e.setDropItems(false); String key = StorageData.key(e.getBlock()); + if (drops && e.getPlayer().getGameMode() != GameMode.CREATIVE) e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation().add(0.5, 0.5, 0.5), items.fromPlaced(p)); + remove(key); + } + private void remove(String key) { + data.blocks.remove(key); data.dirty = true; signatures.remove(key); + var l = displays.remove(key); if (l != null) l.forEach(this::kill); + } + private void kill(UUID id) { Entity en = Bukkit.getEntity(id); if (en != null) en.remove(); } + + @EventHandler(ignoreCancelled = true) public void piston(BlockPistonExtendEvent e) { for (Block b : e.getBlocks()) if (data.at(b) != null) { e.setCancelled(true); return; } } + @EventHandler(ignoreCancelled = true) public void piston(BlockPistonRetractEvent e) { for (Block b : e.getBlocks()) if (data.at(b) != null) { e.setCancelled(true); return; } } + @EventHandler(ignoreCancelled = true) public void explode(EntityExplodeEvent e) { e.blockList().removeIf(b -> data.at(b) != null); } + @EventHandler(ignoreCancelled = true) public void explode(BlockExplodeEvent e) { e.blockList().removeIf(b -> data.at(b) != null); } + + // ---------- interaction ---------- + /** The wrench is built on a knowledge book, which vanilla consumes on right-click. Never let any right-click use it up. */ + @EventHandler(priority = EventPriority.LOWEST) public void wrenchNotConsumed(PlayerInteractEvent e) { + var a = e.getAction(); if (a != org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK && a != org.bukkit.event.block.Action.RIGHT_CLICK_AIR) return; + ItemStack held = e.getItem(); if (held == null || !StorageItems.WRENCH.equals(items.typeOf(held))) return; + e.setUseItemInHand(Event.Result.DENY); + } + + /** Wrench: left-click a storage block to open its panel (works on Bedrock, and picks the exact block when several are adjacent). */ + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void wrench(PlayerInteractEvent e) { + if (e.getAction() != org.bukkit.event.block.Action.LEFT_CLICK_BLOCK || e.getClickedBlock() == null) return; + if (!StorageItems.WRENCH.equals(items.typeOf(e.getPlayer().getInventory().getItemInMainHand()))) return; + var p = data.at(e.getClickedBlock()); if (p == null) return; + e.setCancelled(true); panel(e.getPlayer(), e.getClickedBlock(), p); + } + @EventHandler(priority = EventPriority.LOWEST) public void wrenchNoBreak(BlockBreakEvent e) { + if (StorageItems.WRENCH.equals(items.typeOf(e.getPlayer().getInventory().getItemInMainHand())) && data.at(e.getBlock()) != null) e.setCancelled(true); + } + private void panel(Player pl, Block b, StorageData.Placed p) { + String key = StorageData.key(b); + switch (p.kind) { + case ENDER_CHEST -> { if (!canUse(pl, p)) say(pl, "This Ender Chest is private."); else tuneMenu(pl, key); } + case SPEED_HOPPER -> openFilter(pl, key, p); + case AUTO_CRAFTER -> openRecipe(pl, key, p); + case BEACON -> beaconMenu(pl, key); + } + } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void interact(PlayerInteractEvent e) { + if (e.getAction() != org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK || e.getHand() != EquipmentSlot.HAND || e.getClickedBlock() == null) return; + Block b = e.getClickedBlock(); var p = data.at(b); if (p == null) return; + Player pl = e.getPlayer(); ItemStack hand = pl.getInventory().getItemInMainHand(); boolean empty = hand.getType().isAir(), sneak = pl.isSneaking(); + String key = StorageData.key(b); + switch (p.kind) { + case ENDER_CHEST -> { + if (sneak && !empty) { + e.setUseInteractedBlock(Event.Result.DENY); + return; + } + e.setCancelled(true); + if (!canUse(pl, p)) { say(pl, "This Ender Chest is private."); return; } + if (isDye(hand.getType()) && e.getBlockFace() == BlockFace.UP && e.getInteractionPoint() != null) { + int pad = StorageRules.padAt(front(b), e.getInteractionPoint().getX() - b.getX(), e.getInteractionPoint().getZ() - b.getZ()); + p.colors[pad] = dyeIndex(hand.getType()); changed(key, p); say(pl, "Frequency: " + describe(p.colors)); return; + } + if (hand.getType() == Material.DIAMOND) { + p.priv = !p.priv; p.owner = p.priv ? pl.getUniqueId() : null; changed(key, p); + say(pl, p.priv ? "Ender Chest is now private to you." : "Ender Chest is now shared."); return; + } + if (sneak) { tuneMenu(pl, key); return; } + pl.openInventory(data.inventory(freq(p))); + } + case SPEED_HOPPER -> { if (sneak && empty) { e.setCancelled(true); openFilter(pl, key, p); } } + case AUTO_CRAFTER -> { if (sneak && !empty) return; e.setCancelled(true); openRecipe(pl, key, p); } + case BEACON -> { if (sneak && !empty) return; e.setCancelled(true); beaconMenu(pl, key); } + } + } + private String describe(int[] c) { return DyeColor.values()[c[0]].name() + " / " + DyeColor.values()[c[1]].name() + " / " + DyeColor.values()[c[2]].name(); } + private void changed(String key, StorageData.Placed p) { data.dirty = true; signatures.remove(key); } + + // ---------- menus ---------- + private Inventory menu(String kind, String key, int size, String title) { + var h = new Menu(kind, key); h.inventory = Bukkit.createInventory(h, size, Component.text(title)); return h.inventory; + } + private ItemStack icon(Material m, String name, String... lore) { + ItemStack i = new ItemStack(m); ItemMeta meta = i.getItemMeta(); meta.displayName(text(name, NamedTextColor.WHITE)); + meta.lore(Arrays.stream(lore).map(s -> text(s, NamedTextColor.GRAY)).toList()); i.setItemMeta(meta); return i; + } + // ---------- colour menu: the shared DuneMenus screen model (Java canvas, Bedrock form, dialog fallback) ---------- + @SuppressWarnings("deprecation") + private ItemStack legacyIcon(Material m, String name, String... lore) { + ItemStack i = new ItemStack(m); ItemMeta meta = i.getItemMeta(); meta.setDisplayName(ChatColor.WHITE + name); + meta.setLore(Arrays.stream(lore).map(l -> ChatColor.GRAY + l).toList()); i.setItemMeta(meta); return i; + } + private static String colourName(int c) { String n = DyeColor.values()[StorageRules.wrap(c)].name().toLowerCase(Locale.ROOT).replace('_', ' '); return Character.toUpperCase(n.charAt(0)) + n.substring(1); } + + private static ChatColor chat(int c) { + return switch (DyeColor.values()[StorageRules.wrap(c)]) { + case WHITE -> ChatColor.WHITE; case ORANGE -> ChatColor.GOLD; case MAGENTA -> ChatColor.LIGHT_PURPLE; case LIGHT_BLUE -> ChatColor.AQUA; + case YELLOW -> ChatColor.YELLOW; case LIME -> ChatColor.GREEN; case PINK -> ChatColor.LIGHT_PURPLE; case GRAY -> ChatColor.DARK_GRAY; + case LIGHT_GRAY -> ChatColor.GRAY; case CYAN -> ChatColor.DARK_AQUA; case PURPLE -> ChatColor.DARK_PURPLE; case BLUE -> ChatColor.BLUE; + case BROWN -> ChatColor.GOLD; case GREEN -> ChatColor.DARK_GREEN; case RED -> ChatColor.RED; case BLACK -> ChatColor.DARK_GRAY; + }; + } + private String coloured(int[] c) { return chat(c[0]) + colourName(c[0]) + ChatColor.GRAY + " \u00b7 " + chat(c[1]) + colourName(c[1]) + ChatColor.GRAY + " \u00b7 " + chat(c[2]) + colourName(c[2]); } + + private void tuneMenu(Player pl, String key) { + var p = data.blocks.get(key); if (p == null || p.kind != StorageData.Kind.ENDER_CHEST) return; + if (!canUse(pl, p)) { say(pl, "This Ender Chest is private."); return; } + Inventory model = Bukkit.createInventory(null, 27); Map actions = new HashMap<>(); + // Info line first, then the three pads, then the actions: the renderer lays tiles out in slot order. + model.setItem(4, legacyIcon(Material.ENDER_EYE, ChatColor.LIGHT_PURPLE + "Frequency", coloured(p.colors), + p.priv ? ChatColor.YELLOW + "Private" + ChatColor.GRAY + " \u00b7 only you can open it" : ChatColor.GREEN + "Shared" + ChatColor.GRAY + " \u00b7 every chest with these colours links")); + int[] slots = {10, 11, 12}; + for (int i = 0; i < 3; i++) { final int pad = i; + model.setItem(slots[i], legacyIcon(wool(p.colors[i]), ChatColor.GOLD + "Pad " + (i + 1), chat(p.colors[i]) + colourName(p.colors[i]), "Click to change")); + actions.put(slots[i], () -> pickerMenu(pl, key, pad)); } + model.setItem(14, legacyIcon(Material.DIAMOND, p.priv ? ChatColor.YELLOW + "Private" : ChatColor.GREEN + "Shared", p.priv ? "Click to share it" : "Click to make it private")); + actions.put(14, () -> { var q = data.blocks.get(key); if (q == null) return; q.priv = !q.priv; q.owner = q.priv ? pl.getUniqueId() : null; changed(key, q); tuneMenu(pl, key); }); + model.setItem(15, legacyIcon(Material.BARREL, ChatColor.AQUA + "Open storage", "27 slots shared by this frequency")); + actions.put(15, () -> { var q = data.blocks.get(key); if (q != null && canUse(pl, q)) pl.openInventory(data.inventory(freq(q))); }); + com.example.dunegui.NativeMenus.inventory(plugin, pl, "Ender Chest", model, actions); + } + + private void pickerMenu(Player pl, String key, int pad) { + var p = data.blocks.get(key); if (p == null || !canUse(pl, p)) return; + Inventory model = Bukkit.createInventory(null, 27); Map actions = new HashMap<>(); + model.setItem(4, legacyIcon(Material.ENDER_EYE, ChatColor.LIGHT_PURPLE + "Pad " + (pad + 1), "Now " + chat(p.colors[pad]) + colourName(p.colors[pad]), "Pick a colour below")); + for (int c = 0; c < 16; c++) { final int colour = c; int slot = 9 + c; + boolean cur = p.colors[pad] == c; + ItemStack icon = legacyIcon(dye(c), chat(c) + colourName(c) + (cur ? ChatColor.GREEN + " (current)" : ""), cur ? "Already set" : "Set pad " + (pad + 1) + " to this colour"); + if (cur) { ItemMeta m = icon.getItemMeta(); m.setEnchantmentGlintOverride(true); icon.setItemMeta(m); } + model.setItem(slot, icon); + actions.put(slot, () -> { var q = data.blocks.get(key); if (q == null) return; q.colors[pad] = colour; changed(key, q); tuneMenu(pl, key); }); + } + model.setItem(26, legacyIcon(Material.ARROW, ChatColor.GRAY + "Back")); + actions.put(26, () -> tuneMenu(pl, key)); + com.example.dunegui.NativeMenus.inventory(plugin, pl, "Ender Chest \u00b7 Pad " + (pad + 1), model, actions); + } + + private void openFilter(Player pl, String key, StorageData.Placed p) { + Inventory inv = menu("filter", key, 9, StorageItems.hopperName(p.tier)); + for (int i = 0; i < 5 && i < p.filter.size(); i++) inv.setItem(i, new ItemStack(p.filter.get(i))); + inv.setItem(6, icon(p.whitelist ? Material.LIME_DYE : Material.RED_DYE, p.whitelist ? "Whitelist" : "Blacklist", "Click to switch", "Empty filter accepts everything.")); + inv.setItem(8, icon(Material.PAPER, "Click a slot with an item to set it", "Click with an empty cursor to clear")); + pl.openInventory(inv); + } + /** Vanilla crafting-table window: slot 0 is the result, slots 1-9 the 3x3 grid. */ + private static int gridSlot(int g) { return g + 1; } + private void openRecipe(Player pl, String key, StorageData.Placed p) { + Menu holder = new Menu("recipe", key, p); + InventoryView view = pl.openInventory(recipePreview(holder, pl.getWorld())); + if (view != null && view.getType() == InventoryType.WORKBENCH) { + recipeSessions.put(pl.getUniqueId(), new RecipeSession(view, holder)); + } + } + + private Inventory recipePreview(Menu holder, World world) { + StorageData.Placed placed = holder.recipeBlock; + Inventory preview = Bukkit.createInventory(holder, InventoryType.WORKBENCH, Component.text(StorageItems.REPLICATOR_NAME)); + holder.inventory = preview; + for (int g = 0; g < placed.recipe.length; g++) { + ItemStack item = placed.recipe[g]; + preview.setItem(gridSlot(g), item == null ? null : item.clone()); + } + previewRecipe(preview, world); + return preview; + } + + private void previewRecipe(Inventory inv, World w) { + ItemStack[] m = new ItemStack[9]; for (int g = 0; g < 9; g++) m[g] = inv.getItem(gridSlot(g)); + Recipe r = Bukkit.getCraftingRecipe(m, w); inv.setItem(0, r == null ? null : r.getResult()); + } + + @EventHandler public void click(InventoryClickEvent e) { + var top = e.getView().getTopInventory(); + if (top.getHolder() instanceof StorageData.FreqHolder) { data.dirty = true; return; } + Menu m = menuOf(e.getView()); + if (m == null) return; + int rawSlot = e.getRawSlot(); + if (rawSlot >= top.getSize() + && e.getClickedInventory() != null + && StorageRules.canUseRecipeCursor(e.getClick(), e.getAction())) { + return; + } + e.setCancelled(true); + var p = data.blocks.get(m.blockKey); if (p == null || !(e.getWhoClicked() instanceof Player pl)) return; + if (rawSlot < 0 || rawSlot >= top.getSize()) return; + int slot = e.getRawSlot(); ItemStack cursor = e.getCursor(); + switch (m.kind) { + case "filter" -> { + if (slot >= 0 && slot < 5) { top.setItem(slot, cursor == null || cursor.getType().isAir() ? null : new ItemStack(cursor.getType())); } + if (slot == 6) { p.whitelist = !p.whitelist; top.setItem(6, icon(p.whitelist ? Material.LIME_DYE : Material.RED_DYE, p.whitelist ? "Whitelist" : "Blacklist", "Click to switch", "Empty filter accepts everything.")); data.dirty = true; } + } + case "recipe" -> { + if (p != m.recipeBlock) return; + for (int g = 0; g < 9; g++) if (slot == gridSlot(g)) { top.setItem(slot, cursor == null || cursor.getType().isAir() ? null : cursor.asOne()); previewRecipe(top, pl.getWorld()); } + } + default -> { } + } + } + @EventHandler public void drag(InventoryDragEvent e) { + if (menuOf(e.getView()) == null) return; + int size = e.getView().getTopInventory().getSize(); + if (e.getRawSlots().stream().anyMatch(slot -> slot < size)) e.setCancelled(true); + } + @EventHandler public void close(InventoryCloseEvent e) { + var inv = e.getInventory(); + if (inv.getHolder() instanceof StorageData.FreqHolder) { data.dirty = true; signatures.clear(); return; } + Menu m = menuOf(e.getView()); + if (m == null) return; + recipeSessions.computeIfPresent(e.getPlayer().getUniqueId(), + (id, session) -> session.view() == e.getView() ? null : session); + var p = data.blocks.get(m.blockKey); + if (m.recipeBlock != null) { + saveRecipeAndClearPreview(inv, m.recipeBlock == p ? p : null); + return; + } + if (p == null) return; + if (m.kind.equals("filter")) { + p.filter = new ArrayList<>(); for (int i = 0; i < 5; i++) { var s = inv.getItem(i); if (s != null && !s.getType().isAir() && !p.filter.contains(s.getType())) p.filter.add(s.getType()); } + data.dirty = true; + } + } + + private void saveRecipeAndClearPreview(Inventory preview, StorageData.Placed target) { + try { + if (target == null) return; + for (int g = 0; g < target.recipe.length; g++) { + ItemStack item = preview.getItem(gridSlot(g)); + target.recipe[g] = item == null || item.isEmpty() ? null : item.asOne(); + } + data.dirty = true; + } finally { + // Nothing in the recipe window is a real player item. + preview.clear(); + } + } + + // ---------- vanilla hopper interplay ---------- + @EventHandler(ignoreCancelled = true) public void move(InventoryMoveItemEvent e) { + var init = data.at(e.getInitiator().getLocation()); if (init != null && init.kind == StorageData.Kind.SPEED_HOPPER) { e.setCancelled(true); return; } + var src = data.at(e.getSource().getLocation()); var dst = data.at(e.getDestination().getLocation()); + if (src != null && src.kind != StorageData.Kind.SPEED_HOPPER) e.setCancelled(true); + if (dst != null && (dst.kind != StorageData.Kind.SPEED_HOPPER || !StorageRules.accepts(dst.whitelist, dst.filter, e.getItem().getType()))) e.setCancelled(true); + } + @EventHandler(ignoreCancelled = true) public void pickup(InventoryPickupItemEvent e) { + var p = data.at(e.getInventory().getLocation()); if (p != null && p.kind == StorageData.Kind.SPEED_HOPPER) e.setCancelled(true); + } + + // ---------- engine ---------- + private void tick() { + counter++; + for (var en : new ArrayList<>(data.blocks.entrySet())) { + var p = en.getValue(); Location loc = locate(en.getKey(), p); if (loc == null || !loc.getWorld().isChunkLoaded(loc.getBlockX() >> 4, loc.getBlockZ() >> 4)) continue; + Block b = loc.getBlock(); + switch (p.kind) { + case SPEED_HOPPER -> { if (b.getType() != Material.HOPPER) { remove(en.getKey()); continue; } hopper(b, p); if (counter % 25 == 0) hopperDisplay(en.getKey(), b, p); } + case AUTO_CRAFTER -> { if (b.getType() != Material.CRAFTING_TABLE) { remove(en.getKey()); continue; } if (counter % 10 == 0) crafter(b, p); } + case BEACON -> { if (b.getType() != Material.SEA_LANTERN) { remove(en.getKey()); continue; } + if (counter % 40 == 0) beaconPulse(b, p); if (counter % 25 == 0) beaconDisplay(en.getKey(), b); } + case ENDER_CHEST -> { if (b.getType() != Material.BARREL && b.getType() != Material.ENDER_CHEST) { remove(en.getKey()); continue; } if (counter % 25 == 0) displays(en.getKey(), b, p); } + } + } + if (counter % 300 == 0 && data.dirty) data.save(); + } + + private Inventory containerAt(Block b) { + var p = data.at(b); + if (p != null && p.kind == StorageData.Kind.ENDER_CHEST) return data.inventory(freq(p)); + if (p != null && p.kind == StorageData.Kind.AUTO_CRAFTER) return null; + return b.getState(false) instanceof Container c ? c.getInventory() : null; + } + + private void hopper(Block b, StorageData.Placed p) { + p.cooldown -= 2; if (p.cooldown > 0) return; + if (!(b.getBlockData() instanceof org.bukkit.block.data.type.Hopper hd) || !hd.isEnabled()) return; + if (!(b.getState(false) instanceof org.bukkit.block.Hopper hs)) return; + var tier = StorageRules.Tier.of(p.tier); Inventory own = hs.getInventory(); boolean moved = false; + Block out = b.getRelative(hd.getFacing()); Inventory target = containerAt(out); + if (target != null && StorageRules.transferable(target.getType().name()) && move(own, target, tier.amount, s -> true, hd.getFacing() == BlockFace.DOWN, false) > 0) moved = true; + Block above = b.getRelative(BlockFace.UP); Inventory source = containerAt(above); + Predicate ok = s -> StorageRules.accepts(p.whitelist, p.filter, s.getType()); + if (source != null && StorageRules.transferable(source.getType().name())) { if (move(source, own, tier.amount, ok, true, true) > 0) moved = true; } + else if (source == null && suck(b, own, tier.amount, ok) > 0) moved = true; + if (moved && (data.at(out) != null || data.at(above) != null)) data.dirty = true; + p.cooldown = tier.interval; + } + + /** The vanilla pickup area covers the hopper bowl and the block above. */ + private int suck(Block hopper, Inventory own, int max, Predicate ok) { + int moved = 0; + BoundingBox area = new BoundingBox(hopper.getX(), hopper.getY() + 11.0 / 16, hopper.getZ(), + hopper.getX() + 1, hopper.getY() + 2, hopper.getZ() + 1); + for (Entity en : hopper.getWorld().getNearbyEntities(area, entity -> entity instanceof Item item && item.isValid())) { + Item item = (Item) en; ItemStack s = item.getItemStack(); if (!ok.test(s)) continue; + int take = Math.min(max - moved, s.getAmount()); ItemStack part = s.clone(); part.setAmount(take); + var left = own.addItem(part); int done = take - (left.isEmpty() ? 0 : left.values().iterator().next().getAmount()); + if (done > 0) { s.setAmount(s.getAmount() - done); if (s.getAmount() <= 0) item.remove(); else item.setItemStack(s); moved += done; } + if (moved >= max) break; + } + return moved; + } + + /** Moves up to max items; returns how many moved. Furnaces are handled slot-correctly. */ + private int move(Inventory src, Inventory dst, int max, Predicate ok, boolean down, boolean pulling) { + int moved = 0; + for (int i = 0; i < src.getSize() && moved < max; i++) { + ItemStack s = src.getItem(i); if (s == null || s.getType().isAir() || !ok.test(s)) continue; + if (src instanceof FurnaceInventory && i != 2) continue; + int take = Math.min(max - moved, s.getAmount()); ItemStack part = s.clone(); part.setAmount(take); + int left = insert(dst, part, down); + int done = take - left; if (done <= 0) continue; + s.setAmount(s.getAmount() - done); src.setItem(i, s.getAmount() <= 0 ? null : s); moved += done; + } + return moved; + } + + private int insert(Inventory dst, ItemStack part, boolean down) { + if (dst instanceof FurnaceInventory f) { + int slot = down ? 0 : 1; ItemStack cur = f.getItem(slot); + if (cur == null || cur.getType().isAir()) { f.setItem(slot, part); return 0; } + if (!cur.isSimilar(part)) return part.getAmount(); + int room = cur.getMaxStackSize() - cur.getAmount(), add = Math.min(room, part.getAmount()); cur.setAmount(cur.getAmount() + add); f.setItem(slot, cur); return part.getAmount() - add; + } + var left = dst.addItem(part); return left.isEmpty() ? 0 : left.values().iterator().next().getAmount(); + } + + private void crafter(Block b, StorageData.Placed p) { + boolean any = false; for (ItemStack s : p.recipe) if (s != null) { any = true; break; } if (!any) return; + Inventory src = containerAt(b.getRelative(BlockFace.UP)), dst = containerAt(b.getRelative(BlockFace.DOWN)); + if (src == null || dst == null || !StorageRules.transferable(src.getType().name()) || !StorageRules.transferable(dst.getType().name())) return; + Recipe r = Bukkit.getCraftingRecipe(p.recipe.clone(), b.getWorld()); if (r == null) return; + ItemStack[] ingredients = src.getStorageContents(); + ItemStack[] actualGrid = new ItemStack[p.recipe.length]; + int[] consumption = StorageRules.matchIngredients(p.recipe, ingredients, actualGrid, items::matchesCraftingIngredient); + if (consumption == null) return; + Recipe actual = Bukkit.getCraftingRecipe(actualGrid, b.getWorld()); + if (!(r instanceof Keyed expected) || !(actual instanceof Keyed matched) + || !expected.getKey().equals(matched.getKey())) return; + ItemStack result = actual.getResult().clone(); + gradeCreated(result); + Inventory probe = Bukkit.createInventory(null, Math.min(54, Math.max(9, (dst.getSize() + 8) / 9 * 9))); + for (int i = 0; i < dst.getSize() && i < probe.getSize(); i++) probe.setItem(i, dst.getItem(i)); + if (!probe.addItem(result.clone()).isEmpty()) return; + for (int slot = 0; slot < consumption.length; slot++) { + if (consumption[slot] == 0) continue; + ItemStack stack = ingredients[slot]; + int remaining = stack.getAmount() - consumption[slot]; + src.setItem(slot, remaining == 0 ? null : stack.asQuantity(remaining)); + } + dst.addItem(result); data.dirty = true; + } + + + // ---------- Dune Beacon: vanilla beacon rules without the beam or the sky requirement ---------- + private static final Set PAYMENT = Set.of(Material.IRON_INGOT, Material.GOLD_INGOT, Material.EMERALD, Material.DIAMOND, Material.NETHERITE_INGOT); + private static PotionEffectType effect(String name) { + return switch (name) { case "SPEED" -> PotionEffectType.SPEED; case "HASTE" -> PotionEffectType.HASTE; case "RESISTANCE" -> PotionEffectType.RESISTANCE; + case "JUMP_BOOST" -> PotionEffectType.JUMP_BOOST; case "STRENGTH" -> PotionEffectType.STRENGTH; case "REGENERATION" -> PotionEffectType.REGENERATION; default -> null; }; + } + private static String pretty(String name) { String n = name.toLowerCase(Locale.ROOT).replace('_', ' '); return Character.toUpperCase(n.charAt(0)) + n.substring(1); } + private static Material effectIcon(String name) { + return switch (name) { case "SPEED" -> Material.SUGAR; case "HASTE" -> Material.GOLDEN_PICKAXE; case "RESISTANCE" -> Material.IRON_CHESTPLATE; + case "JUMP_BOOST" -> Material.RABBIT_FOOT; case "STRENGTH" -> Material.BLAZE_POWDER; default -> Material.GOLDEN_APPLE; }; + } + /** Pyramid level 0-4 from the layers of beacon base blocks below, exactly like vanilla. */ + private int beaconLevel(Block b) { + int level = 0; + for (int layer = 1; layer <= 4; layer++) { + int y = b.getY() - layer; if (y < b.getWorld().getMinHeight()) break; + boolean full = true; + for (int x = -layer; x <= layer && full; x++) for (int z = -layer; z <= layer; z++) + if (!b.getWorld().isChunkLoaded((b.getX() + x) >> 4, (b.getZ() + z) >> 4) + || !Tag.BEACON_BASE_BLOCKS.isTagged(b.getWorld().getBlockAt(b.getX() + x, y, b.getZ() + z).getType())) { full = false; break; } + if (!full) break; level = layer; + } + return level; + } + private void beaconPulse(Block b, StorageData.Placed p) { + if (p.primary == null) return; + int level = beaconLevel(b); if (!BeaconRules.validChoice(level, p.primary, p.secondary)) return; + int range = BeaconRules.range(level), dur = BeaconRules.durationTicks(level); + var primary = effect(p.primary); if (primary == null) return; + int amp = BeaconRules.primaryAmplifier(level, p.primary, p.secondary); boolean regen = BeaconRules.regeneration(level, p.primary, p.secondary); + BoundingBox area = new BoundingBox(b.getX() - range, b.getY() - range, b.getZ() - range, + b.getX() + 1 + range, b.getY() + 1 + range + b.getWorld().getMaxHeight() - b.getWorld().getMinHeight(), + b.getZ() + 1 + range); + for (Player pl : b.getWorld().getPlayers()) { + if (pl.getGameMode() == GameMode.SPECTATOR || !area.overlaps(pl.getBoundingBox())) continue; + pl.addPotionEffect(new PotionEffect(primary, dur, amp, true, true, true)); + if (regen) pl.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, dur, 0, true, true, true)); + } + } + private void beaconDisplay(String key, Block b) { + String sig = "beacon"; var ids = displays.get(key); + if (sig.equals(signatures.get(key)) && ids != null && ids.stream().allMatch(id -> { Entity en = Bukkit.getEntity(id); return en != null && en.isValid(); })) return; + if (ids != null) ids.forEach(this::kill); + var body = b.getWorld().spawn(b.getLocation().add(0.5, 0.5, 0.5), ItemDisplay.class, id -> { + id.setItemStack(items.create(StorageItems.BEACON, 1)); id.setPersistent(false); id.setBrightness(new Display.Brightness(15, 15)); id.setItemDisplayTransform(ItemDisplay.ItemDisplayTransform.NONE); + id.setTransformation(new Transformation(new Vector3f(), new AxisAngle4f(), new Vector3f(1.002f, 1.002f, 1.002f), new AxisAngle4f())); + }); + displays.put(key, new ArrayList<>(List.of(body.getUniqueId()))); signatures.put(key, sig); + } + private String payText() { return "Costs 1 iron ingot, gold ingot, emerald, diamond or netherite ingot"; } + + private void beaconMenu(Player pl, String key) { + var p = data.blocks.get(key); if (p == null || p.kind != StorageData.Kind.BEACON) return; + Block b = currentBeacon(pl, key, p); + if (b == null) return; + int level = beaconLevel(b); + Inventory model = Bukkit.createInventory(null, 27); Map actions = new HashMap<>(); + String now = p.primary == null ? "No effect set" : pretty(p.primary) + (p.secondary == null ? "" : " + " + (p.secondary.equals(p.primary) ? "power II" : pretty(p.secondary))); + model.setItem(4, legacyIcon(Material.SEA_LANTERN, StorageItems.POWERCORE_NAME, level == 0 ? "No pyramid below - build iron, gold, emerald, diamond or netherite blocks" : "Level " + level + " - range " + BeaconRules.range(level) + " blocks", now)); + var options = BeaconRules.primaries(level); int slot = 10; + for (String name : options) { final String choice = name; int sl = slot++; + model.setItem(sl, legacyIcon(effectIcon(name), pretty(name), level >= 4 ? "Choose, then pick a secondary" : "Click to set", level >= 4 ? "" : payText())); + actions.put(sl, () -> { if (level >= 4) beaconSecondary(pl, key, p, choice); else beaconConfirm(pl, key, p, choice, null); }); + } + com.example.dunegui.NativeMenus.inventory(plugin, pl, StorageItems.POWERCORE_NAME, model, actions); + } + private void beaconSecondary(Player pl, String key, StorageData.Placed expected, String primary) { + Block block = currentBeacon(pl, key, expected); + if (block == null) return; + int level = beaconLevel(block); + if (level < 4) { beaconMenu(pl, key); return; } + Inventory model = Bukkit.createInventory(null, 27); Map actions = new HashMap<>(); + model.setItem(4, legacyIcon(effectIcon(primary), pretty(primary), "Pick the secondary effect", payText())); + int slot = 10; + for (String sec : BeaconRules.secondaries(level, primary)) { final String choice = sec; int sl = slot++; + model.setItem(sl, legacyIcon(effectIcon(sec), sec.equals(primary) ? pretty(primary) + " II" : pretty(sec), "Click to set")); + actions.put(sl, () -> beaconConfirm(pl, key, expected, primary, choice)); } + model.setItem(slot, legacyIcon(Material.BARRIER, "No secondary", "Primary only")); + actions.put(slot, () -> beaconConfirm(pl, key, expected, primary, null)); + com.example.dunegui.NativeMenus.inventory(plugin, pl, StorageItems.POWERCORE_NAME, model, actions); + } + private static boolean beaconPayment(ItemStack item) { + if (item == null || item.isEmpty() || !PAYMENT.contains(item.getType())) return false; + ItemMeta meta = item.getItemMeta(); + return !meta.hasDisplayName() && !meta.hasItemName() && !meta.hasItemModel() + && !meta.hasCustomModelData() && !meta.hasEnchants() + && BeaconRules.ordinaryPaymentMetadata(meta.getPersistentDataContainer().getKeys().stream() + .map(NamespacedKey::toString).collect(java.util.stream.Collectors.toSet())); + } + + private Block currentBeacon(Player player, String key, StorageData.Placed expected) { + if (data.blocks.get(key) != expected) return null; + Location at = locate(key, expected); + if (at == null || !at.getWorld().equals(player.getWorld()) || player.getLocation().distanceSquared(at) > 64 + || !at.getWorld().isChunkLoaded(at.getBlockX() >> 4, at.getBlockZ() >> 4)) return null; + Block block = at.getBlock(); + return block.getType() == Material.SEA_LANTERN ? block : null; + } + + private void beaconConfirm(Player pl, String key, StorageData.Placed p, String primary, String secondary) { + Block block = currentBeacon(pl, key, p); + if (block == null) { say(pl, "This beacon is no longer in reach."); return; } + int level = beaconLevel(block); + if (!BeaconRules.validChoice(level, primary, secondary)) { say(pl, "That effect is not available at this beacon's level."); return; } + if (pl.getGameMode() != GameMode.CREATIVE) { + Inventory inventory = pl.getInventory(); + ItemStack[] slots = inventory.getStorageContents(); + int paymentSlot = 0; + while (paymentSlot < slots.length) { + ItemStack item = slots[paymentSlot]; + if (beaconPayment(item)) break; + paymentSlot++; + } + if (paymentSlot == slots.length) { say(pl, payText() + "."); return; } + ItemStack payment = slots[paymentSlot]; + inventory.setItem(paymentSlot, payment.getAmount() == 1 ? null : payment.asQuantity(payment.getAmount() - 1)); + } + p.primary = primary; p.secondary = secondary; data.dirty = true; + say(pl, StorageItems.POWERCORE_NAME + " set: " + pretty(primary) + (secondary == null ? "" : " + " + (secondary.equals(primary) ? "power II" : pretty(secondary))) + "."); + beaconPulse(block, p); + } + + // ---------- display entities (pads on top, most common item on the front) ---------- + /** Custom-model overlay (scaled 1.01) over the vanilla hopper so Speed Hoppers look distinct; spout follows the hopper's facing. */ + private void hopperDisplay(String key, Block b, StorageData.Placed p) { + BlockFace face = b.getBlockData() instanceof org.bukkit.block.data.type.Hopper h ? h.getFacing() : BlockFace.DOWN; + String sig = face + "|" + p.tier; + var ids = displays.get(key); + if (sig.equals(signatures.get(key)) && ids != null && ids.stream().allMatch(id -> { Entity en = Bukkit.getEntity(id); return en != null && en.isValid(); })) return; + if (ids != null) ids.forEach(this::kill); + boolean side = face != BlockFace.DOWN; + Location centre = b.getLocation().add(0.5, 0.5, 0.5); + centre.setYaw(switch (face) { case WEST -> 90f; case NORTH -> 180f; case EAST -> -90f; default -> 0f; }); + var body = b.getWorld().spawn(centre, ItemDisplay.class, id -> { + id.setItemStack(items.hopperDisplayItem(p.tier, side)); id.setPersistent(false); id.setBrightness(new Display.Brightness(15, 15)); id.setItemDisplayTransform(ItemDisplay.ItemDisplayTransform.NONE); + id.setTransformation(new Transformation(new Vector3f(), new AxisAngle4f(), new Vector3f(1.01f, 1.01f, 1.01f), new AxisAngle4f())); + }); + displays.put(key, new ArrayList<>(List.of(body.getUniqueId()))); signatures.put(key, sig); + } + + private void displays(String key, Block b, StorageData.Placed p) { + boolean barrel = b.getType() == Material.BARREL; + BlockFace f = front(b); Material common = StorageRules.mostCommon(Arrays.asList(data.inventory(freq(p)).getContents())); + String sig = f + "|" + StorageRules.colorsToString(p.colors) + "|" + common; + var ids = displays.get(key); + if (sig.equals(signatures.get(key)) && ids != null && ids.stream().allMatch(id -> { Entity en = Bukkit.getEntity(id); return en != null && en.isValid(); })) return; + if (ids != null) ids.forEach(this::kill); + List made = new ArrayList<>(); World w = b.getWorld(); + Location centre = b.getLocation().add(0.5, 0.5, 0.5); + centre.setYaw(switch (f) { case WEST -> 90f; case NORTH -> 180f; case EAST -> -90f; default -> 0f; }); + var body = w.spawn(centre, ItemDisplay.class, id -> { + ItemStack shell = items.create(StorageItems.ENDER, 1); + if (barrel) { + ItemMeta meta = shell.getItemMeta(); + meta.setItemModel(new NamespacedKey("dunerealms", "ender_chest_barrel_display")); + shell.setItemMeta(meta); + } + id.setItemStack(shell); id.setPersistent(false); id.setBrightness(new Display.Brightness(15, 15)); id.setItemDisplayTransform(ItemDisplay.ItemDisplayTransform.NONE); + id.setTransformation(new Transformation(new Vector3f(), new AxisAngle4f(), new Vector3f(1.01f, 1.01f, 1.01f), new AxisAngle4f())); + }); + made.add(body.getUniqueId()); + for (int i = 0; i < 3; i++) { + double[] c = StorageRules.padCentre(f, i); final int idx = i; + float width = barrel ? 0.27f : 0.20f; + float padY = barrel ? 1.012f : 0.879f; + var d = w.spawn(b.getLocation(), BlockDisplay.class, bd -> { + bd.setBlock(wool(p.colors[idx]).createBlockData()); bd.setPersistent(false); bd.setBrightness(new Display.Brightness(15, 15)); + bd.setTransformation(new Transformation(new Vector3f((float) (c[0] - width / 2), padY, (float) (c[1] - width / 2)), + new AxisAngle4f(), new Vector3f(width, barrel ? 0.05f : 0.035f, width), new AxisAngle4f())); + }); + made.add(d.getUniqueId()); + } + if (common != null) { + double depth = barrel ? 0.52 : 0.45; + Location at = b.getLocation().add(0.5 + f.getModX() * depth, barrel ? 0.55 : 0.30, 0.5 + f.getModZ() * depth); + at.setYaw(switch (f) { case WEST -> 90f; case NORTH -> 180f; case EAST -> -90f; default -> 0f; }); + var d = w.spawn(at, ItemDisplay.class, id -> { + id.setItemStack(new ItemStack(common)); id.setPersistent(false); id.setItemDisplayTransform(ItemDisplay.ItemDisplayTransform.FIXED); + id.setTransformation(new Transformation(new Vector3f(), new AxisAngle4f(), new Vector3f(barrel ? 0.45f : 0.32f), new AxisAngle4f())); + }); + made.add(d.getUniqueId()); + } + displays.put(key, made); signatures.put(key, sig); + } + + /** Click-free way in for clients that cannot sneak-click: opens the settings of the storage block being looked at (within 5 blocks). */ + private void settingsAtCrosshair(Player pl) { + Block b = pl.getTargetBlockExact(5); var p = b == null ? null : data.at(b); + if (p == null) { say(pl, "Look at a DuneChest device within 5 blocks, or left-click it with a Wrench."); return; } + panel(pl, b, p); + } + // ---------- /dunechest give ---------- + @Override public boolean onCommand(CommandSender s, Command c, String l, String[] a) { + if (a.length >= 1 && a[0].equalsIgnoreCase("panel") && s instanceof Player pl) { settingsAtCrosshair(pl); return true; } + if (!s.hasPermission("dune.admin")) { s.sendMessage("Look at a DuneChest device and use a Wrench or /dunechest panel."); return true; } + if (a.length < 2 || !a[0].equalsIgnoreCase("give")) { s.sendMessage("/dunechest give [amount]"); return true; } + Player t = Bukkit.getPlayerExact(a[1]); if (t == null || a.length < 3) { s.sendMessage("Player offline or missing item."); return true; } + ItemStack item = switch (a[2].toLowerCase(Locale.ROOT)) { case "ender" -> items.create(StorageItems.ENDER, 1); case "hopper1" -> items.create(StorageItems.HOPPER, 1); + case "hopper2" -> items.create(StorageItems.HOPPER, 2); case "hopper3" -> items.create(StorageItems.HOPPER, 3); case "crafter" -> items.create(StorageItems.CRAFTER, 1); case "wrench" -> items.create(StorageItems.WRENCH, 1); case "beacon" -> items.create(StorageItems.BEACON, 1); default -> null; }; + if (item == null) { s.sendMessage("Unknown item."); return true; } + int n = 1; try { if (a.length > 3) n = Math.max(1, Math.min(64, Integer.parseInt(a[3]))); } catch (NumberFormatException ignored) { } + gradeCreated(item); + item.setAmount(n); t.getInventory().addItem(item).values().forEach(r -> t.getWorld().dropItemNaturally(t.getLocation(), r)); s.sendMessage("Gave " + n + " " + a[2] + " to " + t.getName()); return true; + } +} diff --git a/DuneChest/src/main/java/com/example/dunechest/StorageRules.java b/DuneChest/src/main/java/com/example/dunechest/StorageRules.java new file mode 100644 index 00000000..76eec3c5 --- /dev/null +++ b/DuneChest/src/main/java/com/example/dunechest/StorageRules.java @@ -0,0 +1,110 @@ +package com.example.dunechest; + +import java.util.*; +import java.util.function.BiPredicate; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; +import org.bukkit.inventory.ItemStack; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryAction; + +/** Pure rules for the custom storage blocks: hopper tiers, filters, ender-chest colour frequencies and pad geometry. */ +public final class StorageRules { + private StorageRules() {} + + /** Speed hopper tier: moves {@code amount} items every {@code interval} ticks (vanilla: 1 item every 8 ticks). */ + public enum Tier { + MK1(4, 1), MK2(4, 2), MK3(2, 4); + public final int interval, amount; + Tier(int interval, int amount) { this.interval = interval; this.amount = amount; } + public static Tier of(int n) { return values()[Math.max(1, Math.min(3, n)) - 1]; } + public double itemsPerSecond() { return 20.0 * amount / interval; } + } + + public static final int COLORS = 16; + public static int wrap(int color) { return Math.floorMod(color, COLORS); } + public static int cycle(int color, boolean forward) { return wrap(color + (forward ? 1 : -1)); } + + /** Frequency key: shared "a-b-c", or private "p::a-b-c". */ + public static String frequency(int[] c, UUID privateOwner) { + String f = wrap(c[0]) + "-" + wrap(c[1]) + "-" + wrap(c[2]); + return privateOwner == null ? f : "p:" + privateOwner + ":" + f; + } + public static int[] parseColors(String s) { + String[] p = s == null ? new String[0] : s.split(","); + int[] c = new int[3]; + for (int i = 0; i < 3; i++) try { c[i] = wrap(Integer.parseInt(p[i].trim())); } catch (RuntimeException e) { c[i] = 0; } + return c; + } + public static String colorsToString(int[] c) { return wrap(c[0]) + "," + wrap(c[1]) + "," + wrap(c[2]); } + + /** Empty filter accepts everything; otherwise whitelist accepts listed types, blacklist rejects them. */ + public static boolean accepts(boolean whitelist, Collection filter, Material m) { + if (filter.isEmpty()) return true; + return whitelist == filter.contains(m); + } + + /** Direction the viewer's right hand points when standing in front of a block whose front faces {@code front}. */ + public static int[] rightVector(BlockFace front) { + return switch (front) { case SOUTH -> new int[]{1, 0}; case NORTH -> new int[]{-1, 0}; case EAST -> new int[]{0, -1}; case WEST -> new int[]{0, 1}; default -> new int[]{1, 0}; }; + } + /** Local (0..1) x/z centre of pad i (0 = viewer's left) on the top of a block fronting {@code front}. */ + public static double[] padCentre(BlockFace front, int i) { + double u = (i + 0.5) / 3.0; int[] r = rightVector(front); + double x = r[0] == 0 ? 0.5 : (r[0] > 0 ? u : 1 - u), z = r[1] == 0 ? 0.5 : (r[1] > 0 ? u : 1 - u); + return new double[]{x, z}; + } + /** Which pad (0..2) a click at local x/z hit on the top face. */ + public static int padAt(BlockFace front, double lx, double lz) { + int[] r = rightVector(front); + double u = r[0] != 0 ? (r[0] > 0 ? lx : 1 - lx) : (r[1] > 0 ? lz : 1 - lz); + return Math.max(0, Math.min(2, (int) Math.floor(u * 3))); + } + + /** Most common material among stacks (ties by first seen), or null when empty. */ + public static Material mostCommon(Iterable stacks) { + Map counts = new LinkedHashMap<>(); + for (var s : stacks) if (s != null && !s.getType().isAir()) counts.merge(s.getType(), s.getAmount(), Integer::sum); + return pick(counts); + } + + /** Material with the largest total (first seen wins ties), or null when empty. */ + public static Material pick(Map counts) { + Material best = null; int max = 0; + for (var e : counts.entrySet()) if (e.getValue() > max) { max = e.getValue(); best = e.getKey(); } + return best; + } + + /** Build a grid of real inputs and reserve their source slots without changing the inventory. */ + static int[] matchIngredients(ItemStack[] template, ItemStack[] source, ItemStack[] actualGrid, + BiPredicate matches) { + int[] consumption = new int[source.length]; + for (int gridSlot = 0; gridSlot < template.length; gridSlot++) { + ItemStack ingredient = template[gridSlot]; + if (ingredient == null || ingredient.isEmpty()) continue; + int slot = 0; + while (slot < source.length) { + ItemStack stack = source[slot]; + if (stack != null && stack.getAmount() > consumption[slot] && matches.test(ingredient, stack)) break; + slot++; + } + if (slot == source.length) return null; + consumption[slot]++; + actualGrid[gridSlot] = source[slot].asOne(); + } + return consumption; + } + + /** Only ordinary cursor moves below the preview may be handled by the server. */ + static boolean canUseRecipeCursor(ClickType click, InventoryAction action) { + if (click != ClickType.LEFT && click != ClickType.RIGHT) return false; + return switch (action) { + case PICKUP_ALL, PICKUP_SOME, PICKUP_HALF, PICKUP_ONE, + PLACE_ALL, PLACE_SOME, PLACE_ONE, SWAP_WITH_CURSOR -> true; + default -> false; + }; + } + + static final Set BLOCKED_TARGETS = Set.of("BREWING", "CRAFTER", "JUKEBOX", "LECTERN", "COMPOSTER", "DECORATED_POT", "CHISELED_BOOKSHELF", "BEACON", "ENCHANTING", "ANVIL", "SMITHING"); + public static boolean transferable(String inventoryType) { return !BLOCKED_TARGETS.contains(inventoryType); } +} diff --git a/DuneChest/src/main/resources/plugin.yml b/DuneChest/src/main/resources/plugin.yml new file mode 100644 index 00000000..edec4ce1 --- /dev/null +++ b/DuneChest/src/main/resources/plugin.yml @@ -0,0 +1,11 @@ +name: DuneChest +version: 1.0.9 +main: com.example.dunechest.DuneChest +api-version: '1.21.8' +softdepend: [floodgate, DuneMenus, DuneEss, JarvisTranslator] +prefix: DuneChest +description: DuneChest - colour-linked Ender Chests, Speed Hoppers and Auto Crafters +commands: + dunechest: + description: DuneChest storage panel and admin give + usage: /dunechest panel | /dunechest give [amount] diff --git a/DuneChest/src/paperValidation/java/com/example/dunechest/validation/DuneChestPaperValidation.java b/DuneChest/src/paperValidation/java/com/example/dunechest/validation/DuneChestPaperValidation.java new file mode 100644 index 00000000..abe2e9c5 --- /dev/null +++ b/DuneChest/src/paperValidation/java/com/example/dunechest/validation/DuneChestPaperValidation.java @@ -0,0 +1,184 @@ +package com.example.dunechest.validation; + +import com.example.dunechest.DuneChest; +import com.example.dunechest.StorageModule; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Arrays; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Chest; +import org.bukkit.event.EventHandler; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.Listener; +import org.bukkit.event.server.ServerLoadEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.plugin.java.JavaPlugin; + +/** Test-only plugin for an isolated Paper server with a disposable world. */ +public final class DuneChestPaperValidation extends JavaPlugin implements Listener { + @Override + public void onEnable() { + if (!Boolean.getBoolean("dunechest.validation.disposable")) { + throw new IllegalStateException("This test requires an explicitly disposable server"); + } + Bukkit.getPluginManager().registerEvents(this, this); + } + + @EventHandler + public void onServerLoad(ServerLoadEvent event) { + if (event.getType() != ServerLoadEvent.LoadType.STARTUP) return; + Bukkit.getScheduler().runTask(this, () -> { + try { + validateCrafter(); + getLogger().info("DUNECHEST_VALIDATION {\"ok\":true,\"cases\":9}"); + } catch (Exception | AssertionError failure) { + getLogger().log(java.util.logging.Level.SEVERE, "DUNECHEST_VALIDATION {\"ok\":false}", failure); + } finally { + Bukkit.shutdown(); + } + }); + } + + private void validateCrafter() throws ReflectiveOperationException { + StorageModule module = JavaPlugin.getPlugin(DuneChest.class).storage(); + ItemStack mk1 = module.issue("speed_hopper", 1); + ItemStack mk2 = module.issue("speed_hopper", 2); + ItemStack mk3 = module.issue("speed_hopper", 3); + Block table = Bukkit.getWorlds().getFirst().getSpawnLocation().add(0, 12, 0).getBlock(); + table.setType(Material.CRAFTING_TABLE); + Inventory input = chest(table.getRelative(BlockFace.UP)); + Inventory output = chest(table.getRelative(BlockFace.DOWN)); + + Class placedType = Class.forName("com.example.dunechest.StorageData$Placed", + true, module.getClass().getClassLoader()); + var constructor = placedType.getDeclaredConstructor(); + constructor.setAccessible(true); + Object placed = constructor.newInstance(); + Field recipe = placedType.getDeclaredField("recipe"); + recipe.setAccessible(true); + ItemStack diamond = new ItemStack(Material.DIAMOND); + ItemStack redstone = new ItemStack(Material.REDSTONE_BLOCK); + recipe.set(placed, new ItemStack[]{ + diamond, redstone, diamond, redstone, mk1, redstone, diamond, redstone, diamond + }); + Method craft = module.getClass().getDeclaredMethod("crafter", Block.class, placedType); + craft.setAccessible(true); + + load(input, new ItemStack(Material.HOPPER), 4, redstone); + assertRejected(craft, module, table, placed, input, output); + input.setItem(0, mk3.clone()); + assertRejected(craft, module, table, placed, input, output); + load(input, mk1, 3, redstone); + assertRejected(craft, module, table, placed, input, output); + + load(input, mk3, 4, redstone); + input.setItem(3, mk1.asQuantity(2)); + craft.invoke(module, table, placed); + if (!output.containsAtLeast(mk2, 1) || output.containsAtLeast(mk2, 2) + || !mk3.equals(input.getItem(0)) || input.getItem(1) != null + || input.getItem(2) != null || !mk1.equals(input.getItem(3))) { + throw new AssertionError("Valid upgrade did not credit and debit the exact stacks"); + } + validateRecipePreview(module, table.getWorld(), placedType, placed, mk1, mk2); + + ItemStack legacy = mk1.clone(); + var legacyMeta = legacy.getItemMeta(); + legacyMeta.displayName(Component.text("Speed Hopper Mk I", NamedTextColor.GOLD) + .decoration(TextDecoration.ITALIC, false)); + legacy.setItemMeta(legacyMeta); + load(input, legacy, 4, redstone); + output.clear(); + craft.invoke(module, table, placed); + if (!output.containsAtLeast(mk2, 1) || !input.isEmpty()) { + throw new AssertionError("Renaming the hopper broke upgrades using the previous name"); + } + + ItemStack stamped = jarvisDecorated(legacy); + output.clear(); + load(input, jarvisDecorated(mk3), 4, redstone); + assertRejected(craft, module, table, placed, input, output); + + input.setItem(0, stamped.asQuantity(2)); + input.setItem(1, jarvisDecorated(input.getItem(1))); + input.setItem(2, jarvisDecorated(input.getItem(2))); + craft.invoke(module, table, placed); + if (!output.containsAtLeast(mk2, 1) || !stamped.equals(input.getItem(0)) + || input.getItem(1) != null || input.getItem(2) != null) { + throw new AssertionError("Stamped ingredients did not upgrade with the original metadata preserved"); + } + } + + private static ItemStack jarvisDecorated(ItemStack source) { + ItemStack stamped = source.clone(); + var meta = stamped.getItemMeta(); + var data = meta.getPersistentDataContainer(); + var fields = java.util.Map.of("quality", "common", "equipment_mark", "1", + "item_class", "resource", "metadata_policy", "validation", + "metadata_lore_header", "COMMON | MK I", "origin_world", "arrakis"); + fields.forEach((key, value) -> data.set(new NamespacedKey("dunerealms", key), PersistentDataType.STRING, value)); + var lore = new java.util.ArrayList(); + lore.add(Component.text("COMMON | MK I")); + lore.add(Component.empty()); + if (meta.hasLore()) lore.addAll(meta.lore()); + lore.add(Component.text("Origin world: Arrakis")); + meta.lore(lore); + stamped.setItemMeta(meta); + return stamped; + } + + private void validateRecipePreview(StorageModule module, World world, Class placedType, + Object placed, ItemStack mk1, ItemStack mk2) throws ReflectiveOperationException { + Class holderType = Class.forName("com.example.dunechest.StorageModule$Menu", + true, module.getClass().getClassLoader()); + var holder = holderType.getDeclaredConstructor(String.class, String.class, placedType); + holder.setAccessible(true); + Method open = module.getClass().getDeclaredMethod("recipePreview", holderType, World.class); + open.setAccessible(true); + Method close = module.getClass().getDeclaredMethod("saveRecipeAndClearPreview", Inventory.class, placedType); + close.setAccessible(true); + + Inventory preview = (Inventory) open.invoke(module, holder.newInstance("recipe", "validation", placed), world); + if (preview.getType() != InventoryType.WORKBENCH || preview.getSize() != 10 || preview.getHolder() == null + || !mk2.equals(preview.getItem(0)) || !mk1.equals(preview.getItem(5))) { + throw new AssertionError("Recipe preview did not expose the expected workbench layout"); + } + close.invoke(module, preview, placed); + if (!preview.isEmpty()) throw new AssertionError("Recipe preview did not clear on normal close"); + + Inventory orphan = (Inventory) open.invoke(module, holder.newInstance("recipe", "validation", placed), world); + close.invoke(module, orphan, null); + if (!orphan.isEmpty()) throw new AssertionError("Orphaned recipe preview did not clear"); + } + + private static Inventory chest(Block block) { + block.setType(Material.CHEST); + return ((Chest) block.getState()).getBlockInventory(); + } + + private static void load(Inventory inventory, ItemStack hopper, int diamonds, ItemStack redstone) { + inventory.clear(); + inventory.setItem(0, hopper.clone()); + inventory.setItem(1, new ItemStack(Material.DIAMOND, diamonds)); + inventory.setItem(2, redstone.asQuantity(4)); + } + + private static void assertRejected(Method craft, StorageModule module, Block table, Object placed, + Inventory input, Inventory output) throws ReflectiveOperationException { + ItemStack[] before = Arrays.stream(input.getStorageContents()) + .map(stack -> stack == null ? null : stack.clone()).toArray(ItemStack[]::new); + craft.invoke(module, table, placed); + if (!Arrays.equals(before, input.getStorageContents()) || !output.isEmpty()) { + throw new AssertionError("A rejected craft changed an inventory"); + } + } +} diff --git a/DuneChest/src/paperValidation/resources/plugin.yml b/DuneChest/src/paperValidation/resources/plugin.yml new file mode 100644 index 00000000..4f65c534 --- /dev/null +++ b/DuneChest/src/paperValidation/resources/plugin.yml @@ -0,0 +1,5 @@ +name: DuneChestPaperValidation +version: 1.0.0 +main: com.example.dunechest.validation.DuneChestPaperValidation +api-version: '1.21.8' +depend: [DuneChest] diff --git a/DuneChest/src/test/java/com/example/dunechest/BeaconRulesTest.java b/DuneChest/src/test/java/com/example/dunechest/BeaconRulesTest.java new file mode 100644 index 00000000..eafda411 --- /dev/null +++ b/DuneChest/src/test/java/com/example/dunechest/BeaconRulesTest.java @@ -0,0 +1,40 @@ +package com.example.dunechest; + +import static org.junit.jupiter.api.Assertions.*; +import java.util.List; +import java.util.Set; +import org.junit.jupiter.api.Test; + +class BeaconRulesTest { + @Test void acceptsOrdinaryJarvisMetadataAndRejectsCustomIdentities() { + assertTrue(BeaconRules.ordinaryPaymentMetadata(Set.of())); + assertTrue(BeaconRules.ordinaryPaymentMetadata(Set.of("dunerealms:quality", + "dunerealms:equipment_mark", "dunerealms:item_class", "dunerealms:metadata_policy", + "dunerealms:metadata_lore_header", "dunerealms:origin_world"))); + assertFalse(BeaconRules.ordinaryPaymentMetadata(Set.of("dunerealms:quality", "executableitems:ei-id"))); + assertFalse(BeaconRules.ordinaryPaymentMetadata(Set.of("dunerealms:item"))); + } + + @Test void primariesGrowWithLevel() { + assertEquals(List.of(), BeaconRules.primaries(0)); + assertEquals(List.of("SPEED", "HASTE"), BeaconRules.primaries(1)); + assertEquals(4, BeaconRules.primaries(2).size()); + assertEquals(5, BeaconRules.primaries(3).size()); + assertEquals(5, BeaconRules.primaries(4).size()); + } + @Test void secondaryOnlyAtLevelFour() { + assertTrue(BeaconRules.secondaries(3, "SPEED").isEmpty()); + assertEquals(List.of("REGENERATION", "SPEED"), BeaconRules.secondaries(4, "SPEED")); + assertTrue(BeaconRules.validChoice(4, "SPEED", "REGENERATION")); + assertFalse(BeaconRules.validChoice(3, "SPEED", "REGENERATION")); + assertFalse(BeaconRules.validChoice(1, "STRENGTH", null)); + assertTrue(BeaconRules.validChoice(1, "HASTE", null)); + } + @Test void rangeDurationAndAmplifier() { + assertEquals(20, BeaconRules.range(1)); assertEquals(50, BeaconRules.range(4)); + assertEquals(11 * 20, BeaconRules.durationTicks(1)); assertEquals(17 * 20, BeaconRules.durationTicks(4)); + assertEquals(1, BeaconRules.primaryAmplifier(4, "SPEED", "SPEED")); assertEquals(0, BeaconRules.primaryAmplifier(4, "SPEED", "REGENERATION")); + assertEquals(0, BeaconRules.primaryAmplifier(3, "SPEED", "SPEED")); + assertTrue(BeaconRules.regeneration(4, "SPEED", "REGENERATION")); assertFalse(BeaconRules.regeneration(4, "SPEED", "SPEED")); + } +} diff --git a/DuneChest/src/test/java/com/example/dunechest/StorageRulesTest.java b/DuneChest/src/test/java/com/example/dunechest/StorageRulesTest.java new file mode 100644 index 00000000..f00f3457 --- /dev/null +++ b/DuneChest/src/test/java/com/example/dunechest/StorageRulesTest.java @@ -0,0 +1,103 @@ +package com.example.dunechest; + +import static org.junit.jupiter.api.Assertions.*; +import java.util.*; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; +import org.bukkit.inventory.ItemStack; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryAction; +import org.junit.jupiter.api.Test; + +class StorageRulesTest { + @Test void tiersAreFasterThanVanilla() { + double vanilla = 20.0 / 8; + assertEquals(2.5, vanilla); + double prev = vanilla; + for (var t : StorageRules.Tier.values()) { assertTrue(t.itemsPerSecond() > prev, t.name()); prev = t.itemsPerSecond(); } + assertEquals(5.0, StorageRules.Tier.MK1.itemsPerSecond()); assertEquals(10.0, StorageRules.Tier.MK2.itemsPerSecond()); assertEquals(40.0, StorageRules.Tier.MK3.itemsPerSecond()); + assertEquals(StorageRules.Tier.MK3, StorageRules.Tier.of(9)); assertEquals(StorageRules.Tier.MK1, StorageRules.Tier.of(0)); + } + + @Test void filtersWhitelistAndBlacklist() { + List f = List.of(Material.STONE, Material.BONE); + assertTrue(StorageRules.accepts(true, f, Material.BONE)); assertFalse(StorageRules.accepts(true, f, Material.DIRT)); + assertFalse(StorageRules.accepts(false, f, Material.BONE)); assertTrue(StorageRules.accepts(false, f, Material.DIRT)); + assertTrue(StorageRules.accepts(true, List.of(), Material.DIRT) && StorageRules.accepts(false, List.of(), Material.DIRT)); + } + + @Test void colourFrequenciesGive4096SharedAndPrivateKeys() { + Set keys = new HashSet<>(); + for (int a = 0; a < 16; a++) for (int b = 0; b < 16; b++) for (int c = 0; c < 16; c++) keys.add(StorageRules.frequency(new int[]{a, b, c}, null)); + assertEquals(4096, keys.size()); + UUID u = UUID.fromString("00000000-0000-0000-0000-000000000001"); + assertNotEquals(StorageRules.frequency(new int[]{1, 2, 3}, null), StorageRules.frequency(new int[]{1, 2, 3}, u)); + assertEquals("p:" + u + ":1-2-3", StorageRules.frequency(new int[]{1, 2, 3}, u)); + assertEquals(StorageRules.frequency(new int[]{17, -1, 3}, null), "1-15-3"); + assertArrayEquals(new int[]{4, 5, 6}, StorageRules.parseColors("4,5,6")); + assertArrayEquals(new int[]{0, 0, 0}, StorageRules.parseColors("junk")); + assertEquals("4,5,6", StorageRules.colorsToString(new int[]{4, 5, 6})); + assertEquals(0, StorageRules.cycle(15, true)); assertEquals(15, StorageRules.cycle(0, false)); + } + + @Test void padGeometryIsViewerRelativeAndInvertible() { + for (BlockFace f : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) { + Set positions = new HashSet<>(); + for (int i = 0; i < 3; i++) { + double[] c = StorageRules.padCentre(f, i); + assertEquals(i, StorageRules.padAt(f, c[0], c[1]), f + " pad " + i); + positions.add(c[0] * 10 + c[1]); + } + assertEquals(3, positions.size()); + } + // facing south, viewer looks north and their right is east (+x): pad 0 is the smallest x + assertTrue(StorageRules.padCentre(BlockFace.SOUTH, 0)[0] < StorageRules.padCentre(BlockFace.SOUTH, 2)[0]); + assertTrue(StorageRules.padCentre(BlockFace.NORTH, 0)[0] > StorageRules.padCentre(BlockFace.NORTH, 2)[0]); + } + + @Test void crafterReservesOnlyMatchingHopperTiersAndCountsEachIngredient() { + ItemStack mk1 = new HopperStack(1, 1); + ItemStack mk2 = new HopperStack(2, 2); + ItemStack vanilla = new HopperStack(0, 64); + + assertNull(StorageRules.matchIngredients(new ItemStack[]{mk1}, new ItemStack[]{vanilla, mk2}, new ItemStack[1], ItemStack::isSimilar)); + assertNull(StorageRules.matchIngredients(new ItemStack[]{mk1, mk1}, new ItemStack[]{vanilla, mk1}, new ItemStack[2], ItemStack::isSimilar)); + ItemStack[] actualGrid = new ItemStack[3]; + assertArrayEquals(new int[]{0, 0, 2}, StorageRules.matchIngredients( + new ItemStack[]{mk2, null, mk2}, new ItemStack[]{vanilla, mk1, mk2}, actualGrid, ItemStack::isSimilar)); + assertTrue(mk2.isSimilar(actualGrid[0])); + assertNull(actualGrid[1]); + assertEquals(1, actualGrid[2].getAmount()); + assertEquals(2, mk2.getAmount()); + } + + // Model the Bukkit metadata comparison without booting a Paper server. + private static final class HopperStack extends ItemStack { + private final int tier, amount; + HopperStack(int tier, int amount) { this.tier = tier; this.amount = amount; } + @Override public Material getType() { return Material.HOPPER; } + @Override public boolean isEmpty() { return false; } + @Override public ItemStack asOne() { return new HopperStack(tier, 1); } + @Override public int getAmount() { return amount; } + @Override public boolean isSimilar(ItemStack other) { + return other instanceof HopperStack hopper && tier == hopper.tier; + } + } + + @Test void recipeWindowAllowsCursorMovesButBlocksCrossInventoryActions() { + assertTrue(StorageRules.canUseRecipeCursor(ClickType.LEFT, InventoryAction.PICKUP_ALL)); + assertTrue(StorageRules.canUseRecipeCursor(ClickType.RIGHT, InventoryAction.PICKUP_HALF)); + assertTrue(StorageRules.canUseRecipeCursor(ClickType.RIGHT, InventoryAction.PLACE_ONE)); + assertFalse(StorageRules.canUseRecipeCursor(ClickType.SHIFT_LEFT, InventoryAction.MOVE_TO_OTHER_INVENTORY)); + assertFalse(StorageRules.canUseRecipeCursor(ClickType.DOUBLE_CLICK, InventoryAction.COLLECT_TO_CURSOR)); + assertFalse(StorageRules.canUseRecipeCursor(ClickType.NUMBER_KEY, InventoryAction.HOTBAR_SWAP)); + } + + @Test void mostCommonItemPicksBiggestTotal() { + var counts = new java.util.LinkedHashMap(); + counts.put(Material.DIRT, 50); counts.put(Material.STONE, 40); + assertEquals(Material.DIRT, StorageRules.pick(counts)); + assertNull(StorageRules.pick(new java.util.LinkedHashMap<>())); + assertFalse(StorageRules.transferable("BREWING")); assertTrue(StorageRules.transferable("CHEST")); + } +} diff --git a/DuneChest/tools/dunechest_art.py b/DuneChest/tools/dunechest_art.py new file mode 100644 index 00000000..a25b242b --- /dev/null +++ b/DuneChest/tools/dunechest_art.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Generates DuneChest wrench + Speed Hopper (MK1-3) textures/models/item definitions into a resource-pack overlay dir. +usage: dunechest_art.py """ +import json, os, random, sys +from PIL import Image, ImageDraw +root = sys.argv[1]; rng = random.Random(2049); S = 32 + +def w(rel, obj): + p = os.path.join(root, rel); os.makedirs(os.path.dirname(p), exist_ok=True); open(p, "w").write(json.dumps(obj, separators=(",", ":"))) +def save(rel, im): + p = os.path.join(root, rel); os.makedirs(os.path.dirname(p), exist_ok=True); im.save(p) + +# ---- Speed Hopper textures: dark steel with a tier-coloured accent stripe ---- +STEEL = [(54, 56, 64), (60, 62, 72), (48, 50, 58), (66, 68, 78)] +ACCENT = {1: ((214, 168, 70), (246, 214, 120), (150, 108, 40)), # gold + 2: ((70, 200, 220), (150, 235, 245), (36, 120, 140)), # diamond + 3: ((150, 90, 220), (200, 150, 255), (88, 50, 140))} # netherite/violet +for t in (1, 2, 3): + a, hi, lo = ACCENT[t] + im = Image.new("RGBA", (S, S)); px = im.load() + for y in range(S): + for x in range(S): px[x, y] = rng.choice(STEEL) + (255,) + d = ImageDraw.Draw(im) + d.rectangle([0, 0, S - 1, S - 1], outline=(20, 20, 26, 255)) + d.line([(1, 1), (S - 2, 1)], fill=(96, 98, 112, 255)); d.line([(1, 1), (1, S - 2)], fill=(80, 82, 96, 255)) + for y0 in (6, 24): # accent bands + d.rectangle([0, y0, S - 1, y0 + 3], fill=a + (255,)); d.line([(0, y0), (S - 1, y0)], fill=hi + (255,)); d.line([(0, y0 + 3), (S - 1, y0 + 3)], fill=lo + (255,)) + for x in (4, S - 5): d.ellipse([x - 1, 14, x + 1, 16], fill=hi + (255,), outline=lo + (255,)) + for i in range(t): # one pip per tier + d.rectangle([13 + i * 4, 13, 15 + i * 4, 17], fill=a + (255,), outline=lo + (255,)) + save(f"textures/block/speed_hopper_{t}.png", im) + +WALLS = [([0,10,0],[16,16,2]), ([0,10,14],[16,16,16]), ([0,10,2],[2,16,14]), ([14,10,2],[16,16,14])] +def hopper_elements(side): + els = [{"from": f, "to": t, "faces": {k: {"texture": "#t"} for k in ("down","up","north","south","west","east")}} for f, t in WALLS] + els.append({"from": [2,10,2], "to": [14,11,14], "faces": {k: {"texture": "#t"} for k in ("down","up")}}) + els.append({"from": [4,4,4], "to": [12,10,12], "faces": {k: {"texture": "#t"} for k in ("down","up","north","south","west","east")}}) + spout = ([6,4,10],[10,8,16]) if side else ([6,0,6],[10,4,10]) + els.append({"from": spout[0], "to": spout[1], "faces": {k: {"texture": "#t"} for k in ("down","up","north","south","west","east")}}) + return els +for t in (1, 2, 3): + for side in (False, True): + n = f"speed_hopper_{t}" + ("_side" if side else "") + w(f"models/block/{n}.json", {"parent": "minecraft:block/block", "textures": {"particle": f"dunerealms:block/speed_hopper_{t}", "t": f"dunerealms:block/speed_hopper_{t}"}, "elements": hopper_elements(side)}) + w(f"models/item/{n}.json", {"parent": f"dunerealms:block/{n}"}) + w(f"items/{n}.json", {"model": {"type": "minecraft:model", "model": f"dunerealms:item/{n}"}}) + +# ---- Wrench: 32px handheld sprite, diagonal brass-and-iron spanner ---- +im = Image.new("RGBA", (S, S), (0, 0, 0, 0)); d = ImageDraw.Draw(im) +IRON = (150, 154, 164, 255); IRON_HI = (200, 204, 214, 255); IRON_LO = (88, 92, 102, 255); BR = (214, 168, 70, 255); BR_HI = (246, 214, 120, 255); BR_LO = (150, 108, 40, 255); OUT = (24, 24, 30, 255) +for i in range(7, 24): # handle, bottom-left to upper-right + x, y = i, S - 1 - i + for dx in (-1, 0, 1): + d.point((x + dx, y), fill=IRON); d.point((x, y + dx), fill=IRON) + d.point((x - 1, y - 1), fill=IRON_HI); d.point((x + 1, y + 1), fill=IRON_LO) +for i in range(3, 9): # brass grip + x, y = i, S - 1 - i + for dx in (-1, 0, 1): + d.point((x + dx, y), fill=BR); d.point((x, y + dx), fill=BR) + d.point((x - 1, y - 1), fill=BR_HI); d.point((x + 1, y + 1), fill=BR_LO) +d.ellipse([19, 2, 29, 12], fill=IRON, outline=OUT) # open-ended head +d.ellipse([22, 5, 27, 10], fill=(0, 0, 0, 0)); d.rectangle([25, 2, 30, 7], fill=(0, 0, 0, 0)) +d.arc([19, 2, 29, 12], 110, 330, fill=IRON_HI) +# outline pass +src = im.copy(); sp = src.load(); op = im.load() +for y in range(S): + for x in range(S): + if sp[x, y][3] == 0: + for dx, dy in ((1,0),(-1,0),(0,1),(0,-1)): + nx, ny = x + dx, y + dy + if 0 <= nx < S and 0 <= ny < S and sp[nx, ny][3] and sp[nx, ny][:3] != OUT[:3]: op[x, y] = OUT; break +save("textures/item/wrench.png", im) +w("models/item/wrench.json", {"parent": "minecraft:item/handheld", "textures": {"layer0": "dunerealms:item/wrench"}}) +w("items/wrench.json", {"model": {"type": "minecraft:model", "model": "dunerealms:item/wrench"}}) +print("wrote DuneChest art to", root) + +# ---- Dune Beacon: opaque frame-and-crystal cube drawn over a sea lantern (no beam; the base block supplies the light) ---- +FR = [(20, 16, 32), (26, 20, 42), (14, 11, 26), (32, 24, 52)] +fr = Image.new("RGBA", (S, S)); fp = fr.load() +for y in range(S): + for x in range(S): fp[x, y] = rng.choice(FR) + (255,) +fd = ImageDraw.Draw(fr); fd.rectangle([0, 0, S - 1, S - 1], outline=(8, 6, 16, 255)); fd.rectangle([2, 2, S - 3, S - 3], outline=(60, 44, 100, 255)) +save("textures/block/dune_beacon_frame.png", fr) +cr = Image.new("RGBA", (S, S)); cp = cr.load() +for y in range(S): + for x in range(S): + t = y / (S - 1); cp[x, y] = (int(40 + 40 * (1 - t)), int(170 + 50 * (1 - t)), int(190 + 50 * (1 - t)), 255) +cd = ImageDraw.Draw(cr); cd.rectangle([0, 0, S - 1, S - 1], outline=(20, 110, 130, 255)); cd.rectangle([1, 1, S - 2, S - 2], outline=(150, 235, 245, 255)) +cx = cy = S // 2 # nether-star style sparkle +for r in range(1, 9): cd.point((cx - r, cy), fill=(235, 255, 255, 255)); cd.point((cx + r, cy), fill=(235, 255, 255, 255)); cd.point((cx, cy - r), fill=(235, 255, 255, 255)); cd.point((cx, cy + r), fill=(235, 255, 255, 255)) +cd.rectangle([cx - 2, cy - 2, cx + 2, cy + 2], fill=(255, 255, 255, 255)) +save("textures/block/dune_beacon_crystal.png", cr) +allf = lambda t: {k: {"texture": "#" + t} for k in ("down", "up", "north", "south", "west", "east")} +w("models/block/dune_beacon.json", {"parent": "minecraft:block/block", + "textures": {"particle": "dunerealms:block/dune_beacon_frame", "frame": "dunerealms:block/dune_beacon_frame", "crystal": "dunerealms:block/dune_beacon_crystal"}, + "elements": [{"from": [0, 0, 0], "to": [16, 3, 16], "faces": allf("frame")}, {"from": [0, 13, 0], "to": [16, 16, 16], "faces": allf("frame")}, + {"from": [1, 3, 1], "to": [15, 13, 15], "faces": allf("crystal")}]}) +w("models/item/dune_beacon.json", {"parent": "dunerealms:block/dune_beacon"}) +w("items/dune_beacon.json", {"model": {"type": "minecraft:model", "model": "dunerealms:item/dune_beacon"}}) diff --git a/DuneChest/tools/ender_chest_art.py b/DuneChest/tools/ender_chest_art.py new file mode 100644 index 00000000..e231cc17 --- /dev/null +++ b/DuneChest/tools/ender_chest_art.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Generates the DuneRealms Ender Chest block textures, model and item definition into a resource-pack overlay dir. +usage: ender_chest_art.py """ +import json, os, random, sys +from PIL import Image, ImageDraw + +S = 32 +root = sys.argv[1] +rng = random.Random(1701) + +BODY = [(18, 14, 30), (24, 18, 38), (13, 10, 24), (30, 22, 48)] # obsidian +BRASS = [(74, 62, 112), (110, 92, 160), (46, 38, 74)] # dim violet-steel trim +EDGE = (8, 6, 16) +SPECK = [(96, 56, 170), (140, 90, 220), (60, 36, 110)] + +def body(): + im = Image.new("RGBA", (S, S)) + px = im.load() + for y in range(S): + for x in range(S): + px[x, y] = rng.choice(BODY) + (255,) + for _ in range(S * S // 40): # violet obsidian flecks + px[rng.randrange(S), rng.randrange(S)] = rng.choice(SPECK) + (255,) + return im + +def bevel(im): + d = ImageDraw.Draw(im) + d.rectangle([0, 0, S - 1, S - 1], outline=EDGE + (255,)) + d.line([(1, 1), (S - 2, 1)], fill=(52, 36, 84, 255)); d.line([(1, 1), (1, S - 2)], fill=(44, 30, 70, 255)) + return im + +def band(im, y0, y1): + d = ImageDraw.Draw(im) + for y in range(y0, y1 + 1): + c = BRASS[0] if y not in (y0, y1) else BRASS[2] + d.line([(0, y), (S - 1, y)], fill=c + (255,)) + d.line([(0, y0), (S - 1, y0)], fill=BRASS[1] + (255,)) + +def rivets(im, y): + d = ImageDraw.Draw(im) + for x in (3, S - 4): + d.ellipse([x - 1, y - 1, x + 1, y + 1], fill=BRASS[1] + (255,), outline=BRASS[2] + (255,)) + +def eye(im): + d = ImageDraw.Draw(im) + cx, cy = S // 2, 19 + d.rectangle([cx - 7, cy - 6, cx + 6, cy + 6], fill=(18, 10, 28, 255), outline=BRASS[0] + (255,)) + d.ellipse([cx - 5, cy - 3, cx + 4, cy + 3], fill=(63, 208, 176, 255), outline=(30, 120, 104, 255)) + d.ellipse([cx - 2, cy - 2, cx + 1, cy + 1], fill=(8, 20, 24, 255)) + d.point((cx + 1, cy - 2), fill=(220, 255, 245, 255)) + +side = bevel(body()); band(side, 1, 5); band(side, S - 6, S - 2); rivets(side, 3); rivets(side, S - 4) +front = bevel(body()); band(front, 1, 7); band(front, S - 6, S - 2); eye(front); rivets(front, 4) +d = ImageDraw.Draw(front); d.rectangle([S // 2 - 2, 6, S // 2 + 1, 10], fill=(222, 178, 92, 255), outline=(160, 118, 52, 255)) # brass latch + +top = bevel(body()) +d = ImageDraw.Draw(top) +for i in range(3): # three recessed pad slots, matching the wool pads placed on top + cx = int(round((i + 0.5) / 3 * S)) + d.rectangle([cx - 5, S // 2 - 5, cx + 5, S // 2 + 5], fill=(6, 4, 12, 255), outline=BRASS[1] + (255,)) + d.rectangle([cx - 4, S // 2 - 4, cx + 4, S // 2 + 4], outline=(40, 28, 64, 255)) +bottom = bevel(body()) + +os.makedirs(os.path.join(root, "textures/block"), exist_ok=True) +for name, im in (("ender_chest_side", side), ("ender_chest_front", front), ("ender_chest_top", top), ("ender_chest_bottom", bottom)): + im.save(os.path.join(root, "textures/block", name + ".png")) + +def w(rel, obj): + p = os.path.join(root, rel); os.makedirs(os.path.dirname(p), exist_ok=True) + open(p, "w").write(json.dumps(obj, separators=(",", ":"))) + +def face(tex, uv, cull=None): + f = {"texture": "#" + tex, "uv": uv} + if cull: f["cullface"] = cull + return f +# Chest-shaped model (14x14x14 footprint like the vanilla ender chest it is drawn over): base, lid, brass latch. +w("models/block/ender_chest.json", { + "parent": "minecraft:block/block", + "textures": {"particle": "dunerealms:block/ender_chest_side", "side": "dunerealms:block/ender_chest_side", "front": "dunerealms:block/ender_chest_front", + "top": "dunerealms:block/ender_chest_top", "bottom": "dunerealms:block/ender_chest_bottom"}, + "elements": [ + {"from": [1, 0, 1], "to": [15, 10, 15], "faces": { + "down": face("bottom", [1, 1, 15, 15]), "up": face("side", [1, 1, 15, 15]), + "north": face("side", [1, 6, 15, 16]), "south": face("front", [1, 6, 15, 16]), + "west": face("side", [1, 6, 15, 16]), "east": face("side", [1, 6, 15, 16])}}, + {"from": [1, 10, 1], "to": [15, 14, 15], "faces": { + "up": face("top", [1, 1, 15, 15]), "down": face("side", [1, 1, 15, 15]), + "north": face("side", [1, 0, 15, 4]), "south": face("front", [1, 0, 15, 4]), + "west": face("side", [1, 0, 15, 4]), "east": face("side", [1, 0, 15, 4])}}, + {"from": [7, 9, 15], "to": [9, 13, 16], "faces": { + "south": face("front", [7, 3, 8.5, 5]), "north": face("front", [7, 3, 8.5, 5]), "up": face("front", [7, 3, 8.5, 5]), + "down": face("front", [7, 3, 8.5, 5]), "west": face("front", [7, 3, 8.5, 5]), "east": face("front", [7, 3, 8.5, 5])}}]}) +w("models/item/ender_chest.json", {"parent": "dunerealms:block/ender_chest"}) +w("items/ender_chest.json", {"model": {"type": "minecraft:model", "model": "dunerealms:item/ender_chest"}}) +w("models/block/ender_chest_barrel_display.json", {'parent': 'minecraft:block/block', 'textures': {'particle': 'dunerealms:block/ender_chest_side', 'side': 'dunerealms:block/ender_chest_side', 'front': 'dunerealms:block/ender_chest_front', 'top': 'dunerealms:block/ender_chest_top', 'bottom': 'dunerealms:block/ender_chest_bottom'}, 'elements': [{'from': [0, 0, 0], 'to': [16, 16, 16], 'faces': {'down': {'texture': '#bottom', 'cullface': 'down'}, 'up': {'texture': '#top', 'cullface': 'up'}, 'north': {'texture': '#side', 'cullface': 'north'}, 'south': {'texture': '#front', 'cullface': 'south'}, 'west': {'texture': '#side', 'cullface': 'west'}, 'east': {'texture': '#side', 'cullface': 'east'}}}]}) +w("items/ender_chest_barrel_display.json", {"model": {"type": "minecraft:model", "model": "dunerealms:block/ender_chest_barrel_display"}}) +print("wrote ender chest art to", root) diff --git a/DuneEss/src/main/java/com/example/duneess/DuneEss.java b/DuneEss/src/main/java/com/example/duneess/DuneEss.java index ac743255..17e398f6 100644 --- a/DuneEss/src/main/java/com/example/duneess/DuneEss.java +++ b/DuneEss/src/main/java/com/example/duneess/DuneEss.java @@ -90,6 +90,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom command.setExecutor(this); command.setTabCompleter(this); getServer().getPluginManager().registerEvents(this, this); + getServer().getPluginManager().registerEvents(new IronDoorInteraction(), this); basics=new EssentialsBasics(this); basics.register(); StaffItemTools.start(this); diff --git a/DuneEss/src/main/java/com/example/duneess/HomeDimensionRoutes.java b/DuneEss/src/main/java/com/example/duneess/HomeDimensionRoutes.java new file mode 100644 index 00000000..d0ff886a --- /dev/null +++ b/DuneEss/src/main/java/com/example/duneess/HomeDimensionRoutes.java @@ -0,0 +1,21 @@ +package com.example.duneess; + +import java.util.Set; +import org.bukkit.World; + +/** Dimension returns on one backend, preserving the Guild boundary between planets. */ +final class HomeDimensionRoutes { + private static final Set MAIN_WORLDS = Set.of( + "arrakis", "caladan", "giedi_prime", "kaitain", "sigma_draconis_iv", "lobby_base"); + + private HomeDimensionRoutes() {} + + static boolean canReturn(World source, Object destination) { + if (source == null || !(destination instanceof World target)) return false; + if (source.equals(target)) return true; + String main = target.getName(); + if (target.getEnvironment() != World.Environment.NORMAL || !MAIN_WORLDS.contains(main)) return false; + return source.getEnvironment() == World.Environment.NETHER && source.getName().equals(main + "_nether") + || source.getEnvironment() == World.Environment.THE_END && source.getName().equals(main + "_the_end"); + } +} diff --git a/DuneEss/src/main/java/com/example/duneess/IronDoorInteraction.java b/DuneEss/src/main/java/com/example/duneess/IronDoorInteraction.java new file mode 100644 index 00000000..cf17f615 --- /dev/null +++ b/DuneEss/src/main/java/com/example/duneess/IronDoorInteraction.java @@ -0,0 +1,45 @@ +package com.example.duneess; + +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.SoundCategory; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.Bisected; +import org.bukkit.block.data.type.Door; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; + +/** Give iron doors a manual interaction while retaining their redstone behavior. */ +final class IronDoorInteraction implements Listener { + @EventHandler(priority = EventPriority.HIGHEST) + public void interact(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getHand() != EquipmentSlot.HAND + || event.useInteractedBlock() == Event.Result.DENY) return; + var clicked = event.getClickedBlock(); + if (clicked == null || clicked.getType() != Material.IRON_DOOR + || !(clicked.getBlockData() instanceof Door door)) return; + var player = event.getPlayer(); + if (player.getGameMode() == GameMode.SPECTATOR) return; + if (player.isSneaking() && (!player.getInventory().getItemInMainHand().isEmpty() + || !player.getInventory().getItemInOffHand().isEmpty())) return; + + var other = clicked.getRelative(door.getHalf() == Bisected.Half.TOP ? BlockFace.DOWN : BlockFace.UP); + if (other.getType() != Material.IRON_DOOR || !(other.getBlockData() instanceof Door otherDoor) + || otherDoor.getHalf() == door.getHalf()) return; + boolean open = !door.isOpen(); + door.setOpen(open); + otherDoor.setOpen(open); + clicked.setBlockData(door, false); + other.setBlockData(otherDoor, false); + clicked.getWorld().playSound(clicked.getLocation().add(.5, .5, .5), + open ? "minecraft:block.iron_door.open" : "minecraft:block.iron_door.close", + SoundCategory.BLOCKS, 1, 1); + event.setUseInteractedBlock(Event.Result.DENY); + event.setUseItemInHand(Event.Result.DENY); + } +} diff --git a/DuneEss/src/main/java/com/example/duneess/PersonalHomeTravel.java b/DuneEss/src/main/java/com/example/duneess/PersonalHomeTravel.java index 96ae9935..a4a43548 100644 --- a/DuneEss/src/main/java/com/example/duneess/PersonalHomeTravel.java +++ b/DuneEss/src/main/java/com/example/duneess/PersonalHomeTravel.java @@ -50,7 +50,7 @@ final class PersonalHomeTravel implements Listener { private void begin(Player p,Location destination,String mode){ boolean rescue=mode.equals("rescue"); if(!valid(destination)){p.sendMessage("That saved home is unavailable or outside the world's playable bounds.");return;} - if(!p.getWorld().equals(destination.getWorld())){p.sendMessage("Travel to that world through the Guild first, then use /home.");return;} + if(rescue?!p.getWorld().equals(destination.getWorld()):!HomeDimensionRoutes.canReturn(p.getWorld(),destination.getWorld())){p.sendMessage("Travel to that world through the Guild first, then use /home.");return;} String id=p.getUniqueId().toString();if(waiting.containsKey(p.getUniqueId())||journal.contains(id)){p.sendMessage("Your home journey is already being completed.");return;} var connector=Bukkit.getPluginManager().getPlugin("JarvisTranslator");if(connector==null||!connector.isEnabled()){p.sendMessage("Central home travel is unavailable. No payment was made.");return;} UUID token=UUID.randomUUID(),world=p.getWorld().getUID();waiting.put(p.getUniqueId(),token);Location target=destination.clone(); @@ -91,7 +91,7 @@ final class PersonalHomeTravel implements Listener { if(!state.equals("pending")){journal.set(id,null);persist();return;} if(!stage.equals("reserve"))return; Player current=Bukkit.getPlayer(UUID.fromString(id));Location target=journal.getLocation(id+".destination"); - if(current==null||!current.isOnline()||current.isDead()||!valid(target)||rescue&&!safe(target)||!current.getWorld().equals(target.getWorld())){stage(id,"cancel");return;} + if(current==null||!current.isOnline()||current.isDead()||!valid(target)||(rescue?!safe(target)||!current.getWorld().equals(target.getWorld()):!HomeDimensionRoutes.canReturn(current.getWorld(),target.getWorld()))){stage(id,"cancel");return;} // Keep the busy latch until the actual native result. Crash recovery re-delivers the same destination. current.teleportAsync(target).whenComplete((success,failure)->Bukkit.getScheduler().runTask(plugin,()->{ boolean arrived=Boolean.TRUE.equals(success)&&failure==null; diff --git a/DuneEss/src/test/java/com/example/duneess/HomeDimensionRoutesTest.java b/DuneEss/src/test/java/com/example/duneess/HomeDimensionRoutesTest.java new file mode 100644 index 00000000..77b1f5a2 --- /dev/null +++ b/DuneEss/src/test/java/com/example/duneess/HomeDimensionRoutesTest.java @@ -0,0 +1,34 @@ +package com.example.duneess; + +import org.bukkit.World; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class HomeDimensionRoutesTest { + @Test void onlyReturnsToTheOwningMainWorld() { + var sigma = world("sigma_draconis_iv", World.Environment.NORMAL); + var end = world("sigma_draconis_iv_the_end", World.Environment.THE_END); + var giedi = world("giedi_prime", World.Environment.NORMAL); + var nether = world("giedi_prime_nether", World.Environment.NETHER); + var build = world("lobby_arrakis", World.Environment.NORMAL); + assertTrue(HomeDimensionRoutes.canReturn(end, sigma)); + assertTrue(HomeDimensionRoutes.canReturn(nether, giedi)); + assertTrue(HomeDimensionRoutes.canReturn(giedi, giedi)); + assertFalse(HomeDimensionRoutes.canReturn(end, giedi)); + assertFalse(HomeDimensionRoutes.canReturn(nether, sigma)); + assertFalse(HomeDimensionRoutes.canReturn(sigma, end)); + assertFalse(HomeDimensionRoutes.canReturn(end, nether)); + assertFalse(HomeDimensionRoutes.canReturn(build, sigma)); + assertFalse(HomeDimensionRoutes.canReturn(end, null)); + assertFalse(HomeDimensionRoutes.canReturn(world("sigma_draconis_iv_the_end", World.Environment.CUSTOM), sigma)); + } + + private static World world(String name, World.Environment environment) { + var world = mock(World.class); + when(world.getName()).thenReturn(name); + when(world.getEnvironment()).thenReturn(environment); + return world; + } +} diff --git a/DuneEss/src/test/java/com/example/duneess/IronDoorInteractionTest.java b/DuneEss/src/test/java/com/example/duneess/IronDoorInteractionTest.java new file mode 100644 index 00000000..bfb58f16 --- /dev/null +++ b/DuneEss/src/test/java/com/example/duneess/IronDoorInteractionTest.java @@ -0,0 +1,84 @@ +package com.example.duneess; + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.SoundCategory; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.Bisected; +import org.bukkit.block.data.type.Door; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +class IronDoorInteractionTest { + private final IronDoorInteraction listener = new IronDoorInteraction(); + private final PlayerInteractEvent event = mock(PlayerInteractEvent.class); + private final Player player = mock(Player.class); + private final Block upper = mock(Block.class); + private final Block lower = mock(Block.class); + private final Door top = mock(Door.class); + private final Door bottom = mock(Door.class); + private final World world = mock(World.class); + + @BeforeEach void door() { + when(event.getAction()).thenReturn(Action.RIGHT_CLICK_BLOCK); + when(event.getHand()).thenReturn(EquipmentSlot.HAND); + when(event.useInteractedBlock()).thenReturn(Event.Result.DEFAULT); + when(event.getPlayer()).thenReturn(player); + when(player.getGameMode()).thenReturn(GameMode.SURVIVAL); + when(upper.getType()).thenReturn(Material.IRON_DOOR); + when(lower.getType()).thenReturn(Material.IRON_DOOR); + when(upper.getBlockData()).thenReturn(top); + when(lower.getBlockData()).thenReturn(bottom); + when(top.getHalf()).thenReturn(Bisected.Half.TOP); + when(bottom.getHalf()).thenReturn(Bisected.Half.BOTTOM); + when(upper.getRelative(BlockFace.DOWN)).thenReturn(lower); + when(lower.getRelative(BlockFace.UP)).thenReturn(upper); + when(upper.getWorld()).thenReturn(world); + when(lower.getWorld()).thenReturn(world); + when(upper.getLocation()).thenReturn(new Location(world, 1, 2, 1)); + when(lower.getLocation()).thenReturn(new Location(world, 1, 1, 1)); + } + + @Test void topClickOpensBothHalvesWithoutChangingPower() { + when(event.getClickedBlock()).thenReturn(upper); + listener.interact(event); + verify(top).setOpen(true); + verify(bottom).setOpen(true); + verify(top, never()).setPowered(anyBoolean()); + verify(bottom, never()).setPowered(anyBoolean()); + verify(upper).setBlockData(top, false); + verify(lower).setBlockData(bottom, false); + verify(world).playSound(any(Location.class), eq("minecraft:block.iron_door.open"), eq(SoundCategory.BLOCKS), eq(1f), eq(1f)); + verify(event).setUseItemInHand(Event.Result.DENY); + } + + @Test void bottomClickClosesBothHalves() { + when(event.getClickedBlock()).thenReturn(lower); + when(bottom.isOpen()).thenReturn(true); + listener.interact(event); + verify(top).setOpen(false); + verify(bottom).setOpen(false); + verify(world).playSound(any(Location.class), eq("minecraft:block.iron_door.close"), eq(SoundCategory.BLOCKS), eq(1f), eq(1f)); + } + + @Test void protectedAndOffHandClicksNeverToggle() { + when(event.getClickedBlock()).thenReturn(upper); + when(event.useInteractedBlock()).thenReturn(Event.Result.DENY); + listener.interact(event); + when(event.useInteractedBlock()).thenReturn(Event.Result.DEFAULT); + when(event.getHand()).thenReturn(EquipmentSlot.OFF_HAND); + listener.interact(event); + verifyNoInteractions(top, bottom, world); + } +} diff --git a/DuneGroups/README.md b/DuneGroups/README.md new file mode 100644 index 00000000..5a6eeca9 --- /dev/null +++ b/DuneGroups/README.md @@ -0,0 +1,53 @@ +# DuneGroups: replaces Towny and Medieval Factions + +Built from canonical plugins main `5d727d7f59e6af26fba07a3878fd79035a5923ce`. Web main `8c25f491...` was not touched or needed. Nothing is pushed to DuneGit. `/plot` and wilderness drafts are not included. + +## Switch +`JarvisConnector config.yml: native.backend: legacy | dunegroups` (default `legacy`). +- `legacy`: unchanged behaviour. If DuneGroups is installed it is told to deactivate, so the jar alone changes nothing. +- `dunegroups`: JARVIS activates DuneGroups. If DuneGroups or WorldGuard is missing, JARVIS logs SEVERE and disables itself instead of running without Home Block and WorldGuard projection. +Rollback: set `legacy`, restart. DuneGroups drops every rule and its in-memory projection. Its `homes.yml` is kept for the next activation. + +## What replaced what +| Before | Now | +|---|---| +| Towny town home block / Factions home claim | DuneGroups home chunk registry (clans, companies, protected offices, expanded estate chunks, claim revisions) | +| Towny `setPVP(false)` | DuneGroups: nobody can hurt anybody on a company or protected-office home chunk (melee, projectiles, TNT, tamed pets, fire, splash, lingering clouds). Clans stay PvP. Only ever cancels; never clears another plugin's cancellation | +| NativeWorldGuard estate regions | Unchanged class, now also run by the new worker for clans, companies and offices, with wars | +| Home NPCs, Kaitain Emperor NPC | Same code, driven by the new worker | +| Faction roster/roles/neutrality/parents/wars | `OrganisationDirectory`: central projection persisted in `organisation-directory.json` | +| ImperialRaid asking MedievalFactions | `ClanDirectory` (central projection). Paid receipt validation, spawn checks, journal recovery and refunds are unchanged. New: the target claim revision must match the permit | +| Faction AT_WAR/LIEGE edges, Towny nations, mayor/caretaker, power | Retired. No consumer outside the old worker was found. `WarCampaignWorker` is untouched | + +## Relocation cleanup +Acknowledged only after verified absence of: DuneGroups claims, WorldGuard regions, the Home NPC, and any legacy Towny/Factions projection (if those plugins are still installed). The cleanup is written to `dunegroups-worker.yml` before the original requestId/keyId is acknowledged, and an unacknowledged one is re-sent first after a restart. No block is ever removed. + +## Bank +No bank, balance or Vault code was added or touched. Native roles grant nothing. The shared-inventory SQL (`ExchangeInventory`) is untouched. + +## Verified (CI, unimatrixgit/mcdune-backup branch claude/menus-ci) +- DuneGroups builds; 12 unit tests: chunk maths, conflicts, malformed UUID/world/coordinates/revision, stale revision, unresolved vs archived, storage round trip, PvP policy. +- JarvisConnector compiles with all changes; OrganisationDirectoryTest (rosters, roles, neutrality, parents, wars, review retention, duplicate war key, storage); existing TerrainAuthority/NativeCommandPolicy tests pass. + +## NOT verified (needs a server) +Reflection into Paper and WorldGuard, the PvP listener on real events, WorldGuard region writes, Home NPC placement, relocation and restart recovery end to end, paid travel, a real raid, and running with both vendor jars absent. Run the canary below before removing either plugin. + +## Canary checklist (one planet, vendor jars removed, vendor data kept) +1. Start with `legacy`, confirm normal. Switch to `dunegroups`, restart: expect `DuneGroups active`, no SEVERE. +2. `/jarvis status`: clans/companies/offices/wars/home chunks counts match the website. +3. `/dunegroups here` on a clan, company and office home chunk; hit a player from outside and inside a company chunk; throw a harmful splash and lingering potion. +4. WorldGuard: outsider cannot build in an estate; member can. +5. Home NPC present for a clan and a company. Kaitain: Emperor NPC. +6. Relocate a clan home: old chunk, region and NPC gone, then acknowledged once. Kill the server between persist and ack: after restart it acknowledges once. +7. Break `homes.yml` write permission: sync must fail loudly and keep the old projection. +8. Raid: paid order accepted, spawn checks pass, refund path on a stale revision. +9. Switch back to `legacy`: DuneGroups rules stop immediately. + +## Open items found by the audit (not changed) +- `tools/install-plugin-fleet.py:277` still requires a reviewed MedievalFactions runtime. Fleet install fails without it. +- `tools/allow-giedi-nether-pearl.py` and `tools/disable-unused-vendor-settings.*` configure Towny; Giedi Prime's Ender Pearl rule lives in Towny's unclaimed-zone settings and disappears with Towny. +- `DuneTerrain/trails/*-config.yml` carry Towny path settings; harmless without Towny. +- `NativeCommandPolicy` still intercepts `/town`, `/f`, `/mf` etc.; harmless but now redundant. +- Company PvP has no exemption for active war campaigns. If wars on company land must allow PvP, say so. +- Claim revision is read from `homeBlock.claimRevision` (fallback `claimRevision`); confirm the website uses that field. +- The Towny nation/office tree is not reproduced anywhere; only protected neutrality and parents are kept as data. diff --git a/DuneGroups/build.gradle.kts b/DuneGroups/build.gradle.kts new file mode 100644 index 00000000..35991453 --- /dev/null +++ b/DuneGroups/build.gradle.kts @@ -0,0 +1,14 @@ +plugins { java } +group = "com.example" +version = "1.0.0" +repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/") } +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} +java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } +tasks.withType { options.encoding = "UTF-8" } +tasks.test { useJUnitPlatform() } +tasks.jar { archiveFileName.set("DuneGroups.jar") } diff --git a/DuneGroups/settings.gradle.kts b/DuneGroups/settings.gradle.kts new file mode 100644 index 00000000..a3cc54fe --- /dev/null +++ b/DuneGroups/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "DuneGroups" diff --git a/DuneGroups/src/main/java/com/example/dunegroups/DuneGroups.java b/DuneGroups/src/main/java/com/example/dunegroups/DuneGroups.java new file mode 100644 index 00000000..31290b53 --- /dev/null +++ b/DuneGroups/src/main/java/com/example/dunegroups/DuneGroups.java @@ -0,0 +1,148 @@ +package com.example.dunegroups; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.bukkit.Location; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import org.yaml.snakeyaml.Yaml; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.*; + +/** + * Home blocks for JARVIS clans, companies and protected offices. JARVIS stays the source of truth and calls + * {@link #activate()}, {@link #sync(String)}, {@link #claimCount(String, String)} and {@link #deactivate()} by reflection. + * Installing the jar alone changes nothing: until JARVIS activates it there are no rules and no cached projection in force. + */ +public final class DuneGroups extends JavaPlugin implements CommandExecutor { + private final HomeRegistry registry = new HomeRegistry(); + private volatile boolean active; + private boolean fresh; + private File cache; + private Set pvpFreeKinds = Set.of("company", "protected"); + private String pvpFreeMessage = "PvP is disabled on company land."; + + @Override public void onEnable() { + saveDefaultConfig(); + cache = new File(getDataFolder(), "homes.yml"); + loadConfigValues(); + getServer().getPluginManager().registerEvents(new PvpListener(this), this); + var cmd = getCommand("dunegroups"); + if (cmd != null) cmd.setExecutor(this); + getLogger().info("DuneGroups installed and inactive. It starts only when JARVIS uses native.backend: dunegroups."); + } + + @Override public void onDisable() { deactivate(); } + + private void loadConfigValues() { + reloadConfig(); + Set kinds = new HashSet<>(); + for (String k : getConfig().getStringList("pvp-free-kinds")) kinds.add(k.toLowerCase(Locale.ROOT)); + pvpFreeKinds = kinds; + pvpFreeMessage = getConfig().getString("pvp-free-message", pvpFreeMessage); + } + + boolean active() { return active; } + + /** Starts the rules and loads the last stored projection. Throws if the stored projection is unreadable. */ + public synchronized void activate() { + if (active) return; + if (!fresh) throw new IllegalStateException("Waiting for fresh central state"); + active = true; + getLogger().info("DuneGroups active with " + registry.size() + " home chunk(s)."); + } + + private void readCache() throws IOException { + if (cache.exists()) { + try (var in = Files.newBufferedReader(cache.toPath())) { + Object raw = new Yaml().load(in); + if (raw instanceof Map m) registry.install(HomeRegistry.fromMap((Map) m.get("chunks")), String.valueOf(m.get("state") == null ? "" : m.get("state"))); + } catch (RuntimeException broken) { throw new IOException("homes.yml is unreadable: " + broken.getMessage(), broken); } + } + } + + /** Stops every rule at once and forgets the in-memory projection. The stored file is kept for the next activation. */ + public synchronized void deactivate() { + if (!active && !fresh && registry.size() == 0) return; + active = false; + fresh = false; + registry.install(Map.of(), ""); + getLogger().info("DuneGroups deactivated; no rules are in force."); + } + + private void store(Map next, String state) throws IOException { + Files.createDirectories(cache.toPath().getParent()); + String text = new Yaml().dump(Map.of("state", state, "chunks", HomeRegistry.toMap(next))); + File tmp = new File(getDataFolder(), "homes.yml.tmp"); + Files.writeString(tmp.toPath(), text); + try { Files.move(tmp.toPath(), cache.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } + catch (java.nio.file.AtomicMoveNotSupportedException unsupported) { Files.move(tmp.toPath(), cache.toPath(), StandardCopyOption.REPLACE_EXISTING); } + } + + private static JsonArray rows(JsonObject o, String field) { + JsonElement e = o.get(field); + return e == null || e.isJsonNull() ? null : e.getAsJsonArray(); + } + + /** + * Payload: {"stateId":"...","clans":[],"companies":[],"offices":[],"unresolved":[{"kind":"clan","id":"..."}]}. + * Replaces every home chunk atomically. Throws on malformed or conflicting data (the last valid projection stays) and on + * any storage failure (nothing is swapped in). Returns the number of home chunks now registered. + */ + public synchronized int sync(String json) throws IOException { + if (!fresh) readCache(); + JsonObject o = JsonParser.parseString(json).getAsJsonObject(); + Map by = new HashMap<>(); + by.put("clan", rows(o, "clans")); by.put("company", rows(o, "companies")); by.put("protected", rows(o, "offices")); + List unresolved = new ArrayList<>(); + if (o.has("unresolved") && o.get("unresolved").isJsonArray()) + for (JsonElement v : o.getAsJsonArray("unresolved")) { + JsonObject r = v.getAsJsonObject(); + unresolved.add(new HomeRegistry.Ref(r.get("kind").getAsString(), r.get("id").getAsString())); + } + String state = o.has("stateId") ? o.get("stateId").getAsString() : ""; + Map next = HomeRegistry.parse(by, unresolved, registry.snapshot()); + if (!next.equals(registry.snapshot()) || !state.equals(registry.stateId())) { + store(next, state); + registry.install(next, state); + } + fresh = true; + return registry.size(); + } + + /** Number of home chunks currently owned by this group. Zero proves the old claim is gone. */ + public long claimCount(String kind, String id) { return registry.claimCount(kind, id); } + + HomeRegistry.Entry ownerAt(Location at) { + if (!active || at == null || at.getWorld() == null) return null; + return registry.at(at.getWorld().getUID().toString(), Math.floorDiv(at.getBlockX(), 16), Math.floorDiv(at.getBlockZ(), 16)); + } + + boolean pvpFree(Location at) { var e = ownerAt(at); return e != null && pvpFreeKinds.contains(e.kind()); } + String pvpFreeMessage() { return pvpFreeMessage; } + + @Override public boolean onCommand(CommandSender s, Command c, String l, String[] a) { + String sub = a.length == 0 ? "here" : a[0].toLowerCase(Locale.ROOT); + switch (sub) { + case "here" -> { + if (!(s instanceof Player p)) { s.sendMessage("Players only."); return true; } + var e = ownerAt(p.getLocation()); + s.sendMessage(!active ? "DuneGroups is inactive." : e == null ? "This block is not a home block." + : "Home block of " + e.kind() + " " + e.name() + (e.tag().isBlank() ? "" : " [" + e.tag() + "]") + (pvpFree(p.getLocation()) ? " (PvP-free)." : ".")); + } + case "list" -> { if (!s.hasPermission("dunegroups.admin")) s.sendMessage("No permission."); else s.sendMessage((active ? "Active, " : "Inactive, ") + registry.size() + " home chunk(s)."); } + case "reload" -> { if (!s.hasPermission("dunegroups.admin")) s.sendMessage("No permission."); else { loadConfigValues(); s.sendMessage("DuneGroups config reloaded."); } } + default -> s.sendMessage("/dunegroups "); + } + return true; + } +} diff --git a/DuneGroups/src/main/java/com/example/dunegroups/HomeRegistry.java b/DuneGroups/src/main/java/com/example/dunegroups/HomeRegistry.java new file mode 100644 index 00000000..f80800ee --- /dev/null +++ b/DuneGroups/src/main/java/com/example/dunegroups/HomeRegistry.java @@ -0,0 +1,171 @@ +package com.example.dunegroups; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.util.*; + +/** + * Which central clan, company or protected office owns which home chunk. Pure logic, no Bukkit types. + * A bad or conflicting payload is rejected as a whole so the last valid projection stays in force. + */ +final class HomeRegistry { + static final Set KINDS = Set.of("clan", "company", "protected"); + private static final int MAX_CHUNKS_PER_GROUP = 10_000, MAX_ROWS = 2_000; + private static final int CHUNK_LIMIT = 1_875_000; // world border 30,000,000 blocks / 16 + + record Entry(String kind, String id, String name, String tag, long revision) {} + record Ref(String kind, String id) {} + + /** Thrown for malformed rows, conflicting ownership and stale revisions. Never applied partially. */ + static final class Rejected extends IllegalArgumentException { + Rejected(String message) { super(message); } + } + + private volatile Map chunks = Map.of(); + private volatile String stateId = ""; + + static String key(String world, int chunkX, int chunkZ) { return world + ":" + chunkX + ":" + chunkZ; } + + Entry at(String world, int chunkX, int chunkZ) { return chunks.get(key(world, chunkX, chunkZ)); } + int size() { return chunks.size(); } + Map snapshot() { return chunks; } + String stateId() { return stateId; } + + long claimCount(String kind, String id) { + return chunks.values().stream().filter(e -> e.kind().equals(kind) && e.id().equals(id)).count(); + } + + void install(Map next, String state) { chunks = Map.copyOf(next); stateId = state == null ? "" : state; } + + // ---- parsing ---- + private static String str(JsonObject o, String f) { + JsonElement e = o.get(f); + return e == null || e.isJsonNull() || !e.isJsonPrimitive() ? "" : e.getAsString(); + } + + private static int integer(JsonObject o, String f, String what) { + JsonElement e = o.get(f); + if (e == null || !e.isJsonPrimitive() || !e.getAsJsonPrimitive().isNumber()) throw new Rejected(what + " is not a number"); + double d = e.getAsDouble(); + if (d != Math.rint(d) || Math.abs(d) > 30_000_000) throw new Rejected(what + " is out of range"); + return (int) d; + } + + private static boolean uuid(String s) { + try { UUID.fromString(s); return true; } catch (IllegalArgumentException bad) { return false; } + } + + private static boolean bool(JsonObject o, String f) { + JsonElement e = o.get(f); + return e != null && e.isJsonPrimitive() && e.getAsJsonPrimitive().isBoolean() && e.getAsBoolean(); + } + + private static void chunk(int cx, int cz, String what) { + if (Math.abs(cx) > CHUNK_LIMIT || Math.abs(cz) > CHUNK_LIMIT) throw new Rejected(what + " chunk is out of range"); + } + + /** + * Builds the next chunk map. Lifecycle {@code active} projects. {@code archived} or {@code retired}, hidden rows and ids + * that vanished from the payload are dropped. Any other lifecycle, and every id in {@code unresolved}, keeps whatever + * it owned before: an unresolved record is never treated as an absence. + */ + static Map parse(Map rowsByKind, Collection unresolved, Map previous) { + Map out = new HashMap<>(); + Set keep = new HashSet<>(unresolved); + int rows = 0; + for (var group : new TreeMap<>(rowsByKind).entrySet()) { + String kind = group.getKey(); + if (!KINDS.contains(kind)) throw new Rejected("Unknown group kind " + kind); + if (group.getValue() == null) continue; + TreeMap sorted = new TreeMap<>(); + for (JsonElement v : group.getValue()) { + if (!v.isJsonObject()) throw new Rejected("Row is not an object"); + JsonObject r = v.getAsJsonObject(); + String id = str(r, "id"); + if (!uuid(id)) throw new Rejected("Invalid " + kind + " id"); + if (sorted.put(id, r) != null) throw new Rejected("Duplicate " + kind + " " + id); + if (++rows > MAX_ROWS) throw new Rejected("Too many rows"); + } + for (JsonObject r : sorted.values()) { + String id = str(r, "id"), life = str(r, "lifecycle"); + if (life.equals("archived") || life.equals("retired") || bool(r, "hidden")) continue; + if (!life.equals("active")) { keep.add(new Ref(kind, id)); continue; } + project(out, kind, id, r, previous); + } + } + for (var entry : previous.entrySet()) { + Entry e = entry.getValue(); + if (!keep.contains(new Ref(e.kind(), e.id()))) continue; + Entry now = out.get(entry.getKey()); + if (now != null && !(now.kind().equals(e.kind()) && now.id().equals(e.id()))) + throw new Rejected("Chunk " + entry.getKey() + " is claimed by an active record while " + e.kind() + " " + e.id() + " is unresolved"); + out.putIfAbsent(entry.getKey(), e); + } + return out; + } + + private static void project(Map out, String kind, String id, JsonObject r, Map previous) { + if (!r.has("homeBlock") || !r.get("homeBlock").isJsonObject()) return; + JsonObject home = r.getAsJsonObject("homeBlock"); + if (!"minecraft".equals(str(home, "source"))) return; + String world = str(home, "worldUuid"); + if (!uuid(world)) throw new Rejected(kind + " " + id + " has an invalid world"); + if (!home.has("position") || !home.get("position").isJsonObject()) throw new Rejected(kind + " " + id + " has no position"); + JsonObject pos = home.getAsJsonObject("position"); + int x = integer(pos, "x", "x"), z = integer(pos, "z", "z"); + long revision = 0; + JsonElement rev = home.has("revision") ? home.get("revision") : r.get("claimRevision"); + if (rev != null && !rev.isJsonNull()) { + if (!rev.isJsonPrimitive() || !rev.getAsJsonPrimitive().isNumber() || rev.getAsDouble() < 0 || rev.getAsDouble() != Math.rint(rev.getAsDouble())) + throw new Rejected(kind + " " + id + " has an invalid claim revision"); + revision = rev.getAsLong(); + if (home.has("revision") && r.has("claimRevision") && (!r.get("claimRevision").isJsonPrimitive() || r.get("claimRevision").getAsLong() != revision)) + throw new Rejected(kind + " " + id + " claim revisions disagree"); + } + for (Entry old : previous.values()) + if (old.kind().equals(kind) && old.id().equals(id) && old.revision() > revision) + throw new Rejected(kind + " " + id + " claim revision " + revision + " is older than the applied " + old.revision()); + Entry entry = new Entry(kind, id, str(r, "name"), str(r, "tag"), revision); + Set mine = new LinkedHashSet<>(); + mine.add(key(world, Math.floorDiv(x, 16), Math.floorDiv(z, 16))); + if (r.has("claimedChunks") && r.get("claimedChunks").isJsonArray()) { + JsonArray c = r.getAsJsonArray("claimedChunks"); + if (c.size() > MAX_CHUNKS_PER_GROUP) throw new Rejected(kind + " " + id + " exceeds the estate bound"); + for (JsonElement v : c) { + if (!v.isJsonObject()) throw new Rejected(kind + " " + id + " has a malformed chunk"); + JsonObject o = v.getAsJsonObject(); + int cx = integer(o, "x", "chunk x"), cz = integer(o, "z", "chunk z"); + chunk(cx, cz, kind + " " + id); + mine.add(key(world, cx, cz)); + } + } + for (String k : mine) { + Entry other = out.get(k); + if (other != null && !(other.kind().equals(kind) && other.id().equals(id))) + throw new Rejected("Chunk " + k + " is claimed by both " + other.kind() + " " + other.id() + " and " + kind + " " + id); + out.put(k, entry); + } + } + + // ---- storage ---- + static Map toMap(Map m) { + Map out = new LinkedHashMap<>(); + new TreeMap<>(m).forEach((k, e) -> out.put(k, Map.of("kind", e.kind(), "id", e.id(), "name", e.name(), "tag", e.tag(), "revision", e.revision()))); + return out; + } + + static Map fromMap(Map raw) { + Map out = new HashMap<>(); + if (raw == null) return out; + raw.forEach((k, v) -> { + if (!(v instanceof Map o)) throw new Rejected("Cached entry is malformed"); + String kind = String.valueOf(o.get("kind")), id = String.valueOf(o.get("id")); + if (!KINDS.contains(kind) || !uuid(id)) throw new Rejected("Cached entry is malformed"); + long rev = o.get("revision") instanceof Number n ? n.longValue() : 0; + out.put(String.valueOf(k), new Entry(kind, id, String.valueOf(o.get("name")), String.valueOf(o.get("tag")), rev)); + }); + return out; + } +} diff --git a/DuneGroups/src/main/java/com/example/dunegroups/PvpListener.java b/DuneGroups/src/main/java/com/example/dunegroups/PvpListener.java new file mode 100644 index 00000000..8f440e98 --- /dev/null +++ b/DuneGroups/src/main/java/com/example/dunegroups/PvpListener.java @@ -0,0 +1,67 @@ +package com.example.dunegroups; + +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.*; +import org.bukkit.potion.PotionEffect; + +import java.util.Collection; + +/** Cancels player-versus-player harm on PvP-free home blocks. Uses ignoreCancelled and never clears a cancellation. */ +final class PvpListener implements Listener { + private final DuneGroups plugin; + + PvpListener(DuneGroups plugin) { this.plugin = plugin; } + + /** The player a damage source belongs to, or null. Covers arrows, tridents, snowballs, TNT, clouds and tamed pets. */ + static Player attribution(Entity source) { + if (source instanceof Player p) return p; + if (source instanceof Projectile pr && pr.getShooter() instanceof Player p) return p; + if (source instanceof TNTPrimed tnt && tnt.getSource() instanceof Player p) return p; + if (source instanceof AreaEffectCloud cloud && cloud.getSource() instanceof Player p) return p; + if (source instanceof Tameable pet && pet.getOwner() instanceof Player p) return p; + return null; + } + + private boolean blocked(Player attacker, Player victim) { + return plugin.active() && PvpPolicy.blocked(attacker == victim, plugin.pvpFree(attacker.getLocation()), plugin.pvpFree(victim.getLocation())); + } + + private static boolean harmful(Collection effects) { + for (PotionEffect e : effects) if (PvpPolicy.harmful(e.getType().getKey().getKey())) return true; + return false; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDamage(EntityDamageByEntityEvent e) { + if (!(e.getEntity() instanceof Player victim)) return; + Player attacker = attribution(e.getDamager()); + if (attacker == null || !blocked(attacker, victim)) return; + e.setCancelled(true); + attacker.sendMessage(plugin.pvpFreeMessage()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onCombust(EntityCombustByEntityEvent e) { + if (e.getEntity() instanceof Player victim && attribution(e.getCombuster()) instanceof Player attacker && blocked(attacker, victim)) e.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSplash(PotionSplashEvent e) { + if (!(e.getEntity().getShooter() instanceof Player thrower) || !harmful(e.getPotion().getEffects())) return; + for (LivingEntity hit : e.getAffectedEntities()) + if (hit instanceof Player victim && blocked(thrower, victim)) e.setIntensity(victim, 0); + } + + /** Lingering potions: remove protected players from the cloud's current hit list. */ + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onCloud(AreaEffectCloudApplyEvent e) { + if (!(e.getEntity().getSource() instanceof Player thrower)) return; + AreaEffectCloud cloud = e.getEntity(); + boolean bad = harmful(cloud.getCustomEffects()) || cloud.getBasePotionType() != null && harmful(cloud.getBasePotionType().getPotionEffects()); + if (!bad) return; + e.getAffectedEntities().removeIf(hit -> hit instanceof Player victim && blocked(thrower, victim)); + } +} diff --git a/DuneGroups/src/main/java/com/example/dunegroups/PvpPolicy.java b/DuneGroups/src/main/java/com/example/dunegroups/PvpPolicy.java new file mode 100644 index 00000000..c6f8bbfe --- /dev/null +++ b/DuneGroups/src/main/java/com/example/dunegroups/PvpPolicy.java @@ -0,0 +1,19 @@ +package com.example.dunegroups; + +import java.util.Set; + +/** Pure rules for the company protection. Only ever decides to cancel; never to re-allow. */ +final class PvpPolicy { + private PvpPolicy() {} + + /** Potion effect keys (namespaced path names) that harm or hinder the target. */ + static final Set HARMFUL = Set.of("poison", "instant_damage", "weakness", "slowness", "wither", "blindness", + "hunger", "mining_fatigue", "nausea", "levitation", "darkness", "infested", "oozing", "weaving", "wind_charged", "bad_omen", "raid_omen"); + + static boolean harmful(String effectKey) { return HARMFUL.contains(effectKey == null ? "" : effectKey); } + + /** Players in a PvP-free chunk can neither hurt nor be hurt, whoever stands outside. Self damage is untouched. */ + static boolean blocked(boolean sameActor, boolean attackerInFree, boolean victimInFree) { + return !sameActor && (attackerInFree || victimInFree); + } +} diff --git a/DuneGroups/src/main/resources/config.yml b/DuneGroups/src/main/resources/config.yml new file mode 100644 index 00000000..25058fc0 --- /dev/null +++ b/DuneGroups/src/main/resources/config.yml @@ -0,0 +1,4 @@ +# DuneGroups only projects JARVIS home blocks. It has no claims, build protection or commands that create groups. +# Kinds that are PvP-free on their home chunk: company, protected (offices). Clans stay PvP. +pvp-free-kinds: [company, protected] +pvp-free-message: "PvP is disabled on company land." diff --git a/DuneGroups/src/main/resources/plugin.yml b/DuneGroups/src/main/resources/plugin.yml new file mode 100644 index 00000000..91c765c1 --- /dev/null +++ b/DuneGroups/src/main/resources/plugin.yml @@ -0,0 +1,15 @@ +name: DuneGroups +version: 1.0.0 +main: com.example.dunegroups.DuneGroups +api-version: '1.21.8' +load: STARTUP +description: Home blocks for JARVIS clans and companies. Companies are PvP-free on their home block. Replaces Towny and Medieval Factions. +commands: + dunegroups: + description: Show who owns the home block you stand on, or reload + usage: /dunegroups +permissions: + dunegroups.here: + default: true + dunegroups.admin: + default: op diff --git a/DuneGroups/src/test/java/com/example/dunegroups/HomeRegistryTest.java b/DuneGroups/src/test/java/com/example/dunegroups/HomeRegistryTest.java new file mode 100644 index 00000000..16336f83 --- /dev/null +++ b/DuneGroups/src/test/java/com/example/dunegroups/HomeRegistryTest.java @@ -0,0 +1,101 @@ +package com.example.dunegroups; + +import com.google.gson.JsonArray; +import com.google.gson.JsonParser; +import org.junit.jupiter.api.Test; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; + +class HomeRegistryTest { + private static final String W = "11111111-1111-1111-1111-111111111111"; + private static final String A = "aaaaaaaa-0000-0000-0000-000000000001", B = "bbbbbbbb-0000-0000-0000-000000000002", C = "cccccccc-0000-0000-0000-000000000003"; + + private static JsonArray rows(String... json) { return JsonParser.parseString("[" + String.join(",", json) + "]").getAsJsonArray(); } + + private static String row(String id, String life, boolean hidden, int x, int z, String claims, String revision) { + return "{\"id\":\"" + id + "\",\"name\":\"N" + id.charAt(0) + "\",\"tag\":\"T\",\"lifecycle\":\"" + life + "\",\"hidden\":" + hidden + + ",\"homeBlock\":{\"source\":\"minecraft\",\"worldUuid\":\"" + W + "\",\"position\":{\"x\":" + x + ",\"y\":64,\"z\":" + z + "}" + revision + "},\"claimedChunks\":" + claims + "}"; + } + + private static Map parse(JsonArray clans, JsonArray companies, JsonArray offices, List unresolved, Map previous) { + Map by = new HashMap<>(); + by.put("clan", clans); by.put("company", companies); by.put("protected", offices); + return HomeRegistry.parse(by, unresolved, previous); + } + + private static Map parse(JsonArray clans, JsonArray companies) { return parse(clans, companies, null, List.of(), Map.of()); } + + @Test void negativeCoordinatesUseFloorDivisionAndExpandedChunksAreIncluded() { + var m = parse(null, rows(row(A, "active", false, -1, -17, "[{\"x\":3,\"z\":4}]", ""))); + assertEquals("company", m.get(HomeRegistry.key(W, -1, -2)).kind()); + assertNotNull(m.get(HomeRegistry.key(W, 3, 4))); + assertEquals(2, m.size()); + } + + @Test void archivedHiddenAndNonMinecraftAreDropped() { + var m = parse(rows(row(A, "archived", false, 0, 0, "[]", ""), row(B, "active", true, 100, 100, "[]", "")), rows( + "{\"id\":\"" + C + "\",\"lifecycle\":\"active\",\"hidden\":false,\"homeBlock\":{\"source\":\"discord\"}}")); + assertTrue(m.isEmpty()); + } + + @Test void overlappingOwnershipRejectsTheWholePayload() { + var ex = assertThrows(HomeRegistry.Rejected.class, () -> parse(rows(row(A, "active", false, 0, 0, "[]", "")), rows(row(B, "active", false, 5, 5, "[]", "")))); + assertTrue(ex.getMessage().contains("claimed by both")); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[]", ""), row(B, "active", false, 0, 0, "[{\"x\":0,\"z\":0}]", "")))); + } + + @Test void malformedRowsAreRejected() { + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row("not-a-uuid", "active", false, 0, 0, "[]", "")))); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[]", "").replace(W, "bad-world")))); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 99_999_999, 0, "[]", "")))); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[{\"x\":\"a\",\"z\":1}]", "")))); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[]", ",\"revision\":-3")))); + assertThrows(HomeRegistry.Rejected.class, () -> parse(rows(row(A, "active", false, 0, 0, "[]", ""), row(A, "active", false, 50, 50, "[]", "")), null)); + } + + @Test void aStaleClaimRevisionIsRejectedAndKeepsTheOldProjection() { + var first = parse(null, rows(row(A, "active", false, 0, 0, "[]", ",\"revision\":5"))); + assertEquals(5, first.values().iterator().next().revision()); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 200, 200, "[]", ",\"revision\":4")), null, List.of(), first)); + var newer = parse(null, rows(row(A, "active", false, 200, 200, "[]", ",\"revision\":6")), null, List.of(), first); + assertNull(newer.get(HomeRegistry.key(W, 0, 0)), "old home chunk is released"); + assertNotNull(newer.get(HomeRegistry.key(W, 12, 12))); + } + + @Test void unresolvedRecordsKeepWhatTheyOwnedAndMissingOnesDoNot() { + var before = parse(rows(row(A, "active", false, 0, 0, "[]", ""), row(B, "active", false, 100, 100, "[]", "")), null); + assertEquals(2, before.size()); + // A is under review (listed unresolved and absent from rows); B vanished and is not in review. + var after = parse(rows(), null, null, List.of(new HomeRegistry.Ref("clan", A)), before); + assertEquals(1, after.size()); + assertEquals(A, after.values().iterator().next().id()); + // A row with an unknown lifecycle counts as unresolved too. + var odd = parse(rows(row(A, "pending-review", false, 0, 0, "[]", "")), null, null, List.of(), before); + assertNotNull(odd.get(HomeRegistry.key(W, 0, 0))); + } + + @Test void anUnresolvedRecordCannotHoldAChunkAnActiveRecordNowClaims() { + var before = parse(rows(row(A, "active", false, 0, 0, "[]", "")), null); + assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(B, "active", false, 0, 0, "[]", "")), null, List.of(new HomeRegistry.Ref("clan", A)), before)); + } + + @Test void officesProjectAsProtectedAndStorageRoundTrips() { + var m = parse(null, null, rows(row(A, "active", false, 0, 0, "[]", ",\"revision\":7")), List.of(), Map.of()); + assertEquals("protected", m.values().iterator().next().kind()); + assertEquals(m, HomeRegistry.fromMap(HomeRegistry.toMap(m))); + var r = new HomeRegistry(); + r.install(m, "s1"); + assertEquals(1, r.claimCount("protected", A)); + assertEquals(0, r.claimCount("clan", A)); + assertEquals("s1", r.stateId()); + r.install(Map.of(), ""); + assertEquals(0, r.claimCount("protected", A)); + } + + @Test void aCorruptCacheEntryIsRejected() { + assertThrows(HomeRegistry.Rejected.class, () -> HomeRegistry.fromMap(Map.of("k", Map.of("kind", "wizard", "id", A)))); + assertThrows(HomeRegistry.Rejected.class, () -> HomeRegistry.fromMap(Map.of("k", "oops"))); + } +} diff --git a/DuneGroups/src/test/java/com/example/dunegroups/PvpPolicyTest.java b/DuneGroups/src/test/java/com/example/dunegroups/PvpPolicyTest.java new file mode 100644 index 00000000..e8f04aa8 --- /dev/null +++ b/DuneGroups/src/test/java/com/example/dunegroups/PvpPolicyTest.java @@ -0,0 +1,23 @@ +package com.example.dunegroups; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PvpPolicyTest { + @Test void insideTheChunkNobodyCanHurtAnybodyAndOutsidersAreIncluded() { + assertTrue(PvpPolicy.blocked(false, false, true), "outsider hits someone standing on company land"); + assertTrue(PvpPolicy.blocked(false, true, false), "someone on company land shoots out"); + assertTrue(PvpPolicy.blocked(false, true, true)); + } + + @Test void outsideCompanyLandNothingChangesAndSelfDamageIsLeftAlone() { + assertFalse(PvpPolicy.blocked(false, false, false)); + assertFalse(PvpPolicy.blocked(true, true, true)); + } + + @Test void harmfulEffectsCoverPotionsAndClouds() { + for (String k : new String[]{"poison", "instant_damage", "slowness", "weakness", "wither", "levitation", "blindness"}) assertTrue(PvpPolicy.harmful(k), k); + for (String k : new String[]{"speed", "regeneration", "instant_health", "fire_resistance", "", null}) assertFalse(PvpPolicy.harmful(k), String.valueOf(k)); + } +} diff --git a/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java b/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java index 1f44298c..9142ba78 100644 --- a/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java +++ b/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java @@ -41,7 +41,7 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec @Override public boolean shouldGenerateStructures() { return false; } } @Override public void onEnable() { - saveDefaultConfig(); roleKey=new NamespacedKey(this,"role"); com.dunerealms.npc.CitizensBridge.start(this,roleKey); + saveDefaultConfig(); roleKey=new NamespacedKey(this,"role"); com.dunerealms.npc.CitizensBridge.start(this, () -> { if(lobby!=null)ensureNpcs(); }, roleKey); getCommand("lobby").setExecutor(this); getCommand("dunelobby").setExecutor(this); Bukkit.getPluginManager().registerEvents(this,this); Bukkit.getMessenger().registerOutgoingPluginChannel(this,"BungeeCord"); @@ -93,12 +93,8 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec } private void npc(String role,String name,int x,int y,int z,Villager.Profession profession) { for(LivingEntity entity:lobby.getEntitiesByClass(LivingEntity.class)) if(role.equals(entity.getPersistentDataContainer().get(roleKey,PersistentDataType.STRING))) return; - lobby.spawn(new Location(lobby,x+.5,y,z+.5,180,0),Villager.class,v->{ - v.setCustomName(ChatColor.GOLD+name); v.setCustomNameVisible(true); v.setAI(false); v.setSilent(true); - v.setInvulnerable(true); v.setPersistent(true); v.setRemoveWhenFarAway(false); v.setProfession(profession); - v.setVillagerType(role.equals("water")||role.equals("spice")?Villager.Type.SWAMP:Villager.Type.DESERT); - v.getPersistentDataContainer().set(roleKey,PersistentDataType.STRING,role); v.setRecipes(List.of()); - }); + if(!com.dunerealms.npc.CitizensBridge.ready()||com.dunerealms.npc.CitizensBridge.exists(this,lobby,roleKey,role))return; + com.dunerealms.npc.CitizensBridge.spawnContact(this,new Location(lobby,x+.5,y,z+.5,180,0),ChatColor.GOLD+name,roleKey,role,true); } @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) { if(command.getName().equals("lobby")) { @@ -179,8 +175,12 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec String role=e.getRightClicked().getPersistentDataContainer().get(roleKey,PersistentDataType.STRING); if(role==null) return; e.setCancelled(true); if(e.getHand()!=EquipmentSlot.HAND) return; switch(role) { - case "liaison" -> { if(Bukkit.getPluginCommand("duneess")!=null) e.getPlayer().performCommand("duneess travel"); else departure(e.getPlayer(),"arrakis"); } - case "exchange" -> { if(Bukkit.getPluginCommand("dune")!=null) e.getPlayer().performCommand("dune exchange"); else e.getPlayer().sendMessage(ChatColor.GOLD+"Koopkring market integration requires DuneCore on this backend."); } + case "liaison" -> { + if (!e.getPlayer().performCommand("dunerealmsgui:guildtravel")) { + e.getPlayer().sendMessage("The Spacing Guild menu is unavailable."); + } + } + case "exchange" -> { if(!e.getPlayer().performCommand("dunerealmsgui:exchange")) e.getPlayer().sendMessage("The Exchange service is temporarily unavailable."); } case "water","spice" -> trade(e.getPlayer(),role); } } @@ -207,29 +207,11 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec } } - private void departure(Player player,String planet) { - TravelMenu menu=new TravelMenu(planet); ItemStack confirm=new ItemStack(Material.LIME_CONCRETE); ItemMeta meta=confirm.getItemMeta(); - meta.setDisplayName("Confirm departure: "+planet); meta.setLore(List.of("DuneEss fares and access rules apply when installed.")); confirm.setItemMeta(meta); - menu.inventory.setItem(4,confirm); - com.example.dunegui.NativeMenus.show(this,player,"Guild departure",List.of( - new com.example.dunegui.NativeMenus.Choice("Confirm departure: "+planet,"DuneEss fares and access rules apply.",()->depart(player,planet)), - new com.example.dunegui.NativeMenus.Choice("Cancel","",player::closeInventory))); - } + private void departure(Player player,String planet) { depart(player,planet); } private void depart(Player player,String planet) { - long now=System.currentTimeMillis(); if(now-travelCooldown.getOrDefault(player.getUniqueId(),0L)<5000) return; - travelCooldown.put(player.getUniqueId(),now); - Bukkit.getScheduler().runTask(this,()-> { - player.closeInventory(); - if(Bukkit.getPluginCommand("duneess")!=null) { player.performCommand("duneess travel "+planet); return; } - World target=Bukkit.getWorld(planet); - if(target!=null) { player.teleport(target.getSpawnLocation()); return; } - String server=getConfig().getString("servers."+planet,""); - if(server.isBlank()) { player.sendMessage("No destination configured."); return; } - try { - ByteArrayOutputStream bytes=new ByteArrayOutputStream(); DataOutputStream out=new DataOutputStream(bytes); out.writeUTF("Connect"); out.writeUTF(server); - player.sendPluginMessage(this,"BungeeCord",bytes.toByteArray()); player.sendMessage("Guild departure requested. If you remain here, the destination or proxy is unavailable."); - } catch(IOException ex) { player.sendMessage("Guild departure could not be requested."); } - }); + // Boarding remains with the authenticated current Guild quote and confirmation flow. + if (!player.performCommand("dunerealmsgui:guildtravel")) + player.sendMessage("The Spacing Guild menu is temporarily unavailable."); } @EventHandler public void drag(InventoryDragEvent e) { if(e.getView().getTopInventory().getHolder() instanceof TravelMenu) e.setCancelled(true); } @EventHandler public void quit(PlayerQuitEvent e) { travelCooldown.remove(e.getPlayer().getUniqueId()); } diff --git a/DuneLobby/src/main/resources/plugin.yml b/DuneLobby/src/main/resources/plugin.yml index 9667fb85..e7db53c5 100644 --- a/DuneLobby/src/main/resources/plugin.yml +++ b/DuneLobby/src/main/resources/plugin.yml @@ -3,7 +3,7 @@ version: 1.1.0 main: com.example.dunelobby.DuneLobby api-version: '1.21.8' load: POSTWORLD -softdepend: [Citizens, Citizens, floodgate, ViaVersion, ImageFrame, DuneEss, DuneCore] +softdepend: [Citizens, floodgate, ViaVersion, ImageFrame, DuneEss, DuneCore] commands: lobby: description: Return to the Vaerkring lobby diff --git a/DuneLobbyAccount/build.gradle.kts b/DuneLobbyAccount/build.gradle.kts new file mode 100644 index 00000000..cf253776 --- /dev/null +++ b/DuneLobbyAccount/build.gradle.kts @@ -0,0 +1,20 @@ +plugins { java } +group = "com.dunerealms" +version = "1.0.1" + +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") +} + +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("com.google.code.gson:gson:2.11.0") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } +tasks.test { useJUnitPlatform() } +tasks.jar { archiveFileName.set("DuneLobbyAccount.jar") } +tasks.withType { options.encoding = "UTF-8" } diff --git a/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/AccountJournal.java b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/AccountJournal.java new file mode 100644 index 00000000..28043839 --- /dev/null +++ b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/AccountJournal.java @@ -0,0 +1,94 @@ +package com.dunerealms.lobbyaccount; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.UUID; + +final class AccountJournal { + enum Phase { PENDING, ACK, DONE, HELD } + + record Entry(UUID player, UUID request, String name, Phase phase) { + Entry advance(Phase next) { + return new Entry(player, request, name, next); + } + } + + private final Path folder; + private final boolean posix; + + AccountJournal(Path folder) throws IOException { + this.folder = folder.toAbsolutePath().normalize(); + posix = folder.getFileSystem().supportedFileAttributeViews().contains("posix"); + Files.createDirectories(this.folder, permissions("rwx------")); + if (!this.folder.toRealPath().equals(this.folder)) throw new IOException("Invalid provisioning journal directory"); + if (posix && !Files.getPosixFilePermissions(this.folder).equals(PosixFilePermissions.fromString("rwx------"))) { + throw new IOException("Provisioning journal directory must be private"); + } + } + + Entry read(UUID player) throws IOException { + Path path = path(player); + if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return null; + if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.size(path) > 256) + throw new IOException("Invalid provisioning receipt"); + try { + var rows = Files.readAllLines(path, StandardCharsets.UTF_8); + if (rows.size() != 4 || !player.equals(UUID.fromString(rows.get(0))) || !validName(rows.get(2))) + throw new IllegalArgumentException(); + return new Entry(player, UUID.fromString(rows.get(1)), rows.get(2), Phase.valueOf(rows.get(3))); + } catch (IllegalArgumentException invalid) { + throw new IOException("Invalid provisioning receipt"); + } + } + + Entry admit(UUID player, String name) throws IOException { + Entry entry = read(player); + if (entry != null) return entry; + entry = new Entry(player, UUID.randomUUID(), name, Phase.PENDING); + write(entry); + return entry; + } + + void write(Entry entry) throws IOException { + if (!validName(entry.name())) throw new IOException("Invalid verified player name"); + Path tmp = Files.createTempFile(folder, ".receipt-", ".tmp", permissions("rw-------")); + try { + String text = entry.player() + "\n" + entry.request() + "\n" + entry.name() + "\n" + entry.phase() + "\n"; + try (FileChannel output = FileChannel.open(tmp, StandardOpenOption.WRITE)) { + ByteBuffer buffer = StandardCharsets.UTF_8.encode(text); + while (buffer.hasRemaining()) output.write(buffer); + output.force(true); + } + Files.move(tmp, path(entry.player()), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + if (posix) { + try (FileChannel directory = FileChannel.open(folder, StandardOpenOption.READ)) { + directory.force(true); + } + } + } finally { + Files.deleteIfExists(tmp); + } + } + + static boolean validName(String name) { + return name != null && name.matches("[A-Za-z0-9_.-]{1,32}"); + } + + private Path path(UUID player) { + return folder.resolve(player + ".receipt"); + } + + private FileAttribute[] permissions(String mode) { + return posix ? new FileAttribute[]{PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(mode))} + : new FileAttribute[0]; + } +} diff --git a/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/DuneLobbyAccount.java b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/DuneLobbyAccount.java new file mode 100644 index 00000000..d71d65c1 --- /dev/null +++ b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/DuneLobbyAccount.java @@ -0,0 +1,223 @@ +package com.dunerealms.lobbyaccount; + +import static com.dunerealms.lobbyaccount.AccountJournal.Phase.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.java.JavaPlugin; + +public final class DuneLobbyAccount extends JavaPlugin implements Listener { + private static final Path LOBBY = Path.of("/opt/dunerealms/lobby"); + private static final Path TOKEN = Path.of("/etc/dunerealms/lobby-account.token"); + private static final Component HELP = Component.text("Visit cp.dunerealms.com to link or recover your account."); + + private final Set active = new HashSet<>(); + private final Set finished = new HashSet<>(); + private final Map firstAdmissions = new HashMap<>(); + private volatile boolean running; + private ThreadPoolExecutor executor; + private AccountJournal journal; + private LobbyAccountApi api; + + @Override public void onEnable() { + try { + Path root = getDataFolder().toPath().toAbsolutePath().normalize().getParent().getParent(); + if (!LOBBY.equals(root) || !LOBBY.equals(root.toRealPath())) throw new IOException("Invalid Lobby root"); + verifyForwarding(root); + api = new LobbyAccountApi(TOKEN); + api.verifyCredential(); + journal = new AccountJournal(getDataFolder().toPath().resolve("receipts")); + } catch (IOException | RuntimeException unavailable) { + getLogger().warning("Lobby account provisioning is disabled. Check the Lobby installation and credential."); + getServer().getPluginManager().disablePlugin(this); + return; + } + executor = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(96), task -> { + Thread worker = new Thread(task, "DuneLobbyAccount"); + worker.setDaemon(true); + return worker; + }); + running = true; + getServer().getPluginManager().registerEvents(this, this); + getServer().getScheduler().runTaskTimer(this, () -> Bukkit.getOnlinePlayers().forEach(this::attempt), 600, 600); + } + + private void verifyForwarding(Path root) throws IOException { + Path config = root.resolve("config/paper-global.yml"); + Path spigot = root.resolve("spigot.yml"); + if (!"127.0.0.1".equals(getServer().getIp()) || !Files.isRegularFile(config) || !Files.isRegularFile(spigot)) + throw new IOException("Expected the local authenticated Lobby backend"); + var velocity = readConfig(config).getConfigurationSection("proxies.velocity"); + if (velocity == null || !velocity.getBoolean("enabled") || !velocity.getBoolean("online-mode") + || velocity.getString("secret", "").isBlank() + || readConfig(spigot).getBoolean("settings.bungeecord", true)) + throw new IOException("Expected authenticated Velocity forwarding"); + } + + private static YamlConfiguration readConfig(Path path) throws IOException { + var config = new YamlConfiguration(); + try { + config.load(path.toFile()); + } catch (InvalidConfigurationException invalid) { + throw new IOException("Invalid Lobby forwarding configuration"); + } + return config; + } + + @Override public void onDisable() { + running = false; + if (executor != null) executor.shutdownNow(); + if (api != null) api.close(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void joined(PlayerJoinEvent event) { + Player player = event.getPlayer(); + if (!player.hasPlayedBefore() && AccountJournal.validName(player.getName())) { + firstAdmissions.putIfAbsent(player.getUniqueId(), player.getName()); + } + attempt(player); + } + + private void attempt(Player player) { + UUID uuid = player.getUniqueId(); + String liveName = player.getName(); + String admittedName = firstAdmissions.get(uuid); + if (admittedName != null) { + try { + journal.admit(uuid, admittedName); + firstAdmissions.remove(uuid); + } catch (IOException unavailable) { + return; // Retry the local receipt before admitting any network work. + } + } + if (!running || !AccountJournal.validName(liveName) || finished.contains(uuid) || !active.add(uuid)) return; + try { + executor.execute(() -> process(player, uuid, liveName)); + } catch (RejectedExecutionException full) { + active.remove(uuid); + } + } + + private void process(Player player, UUID uuid, String liveName) { + boolean terminal = false; + try { + AccountJournal.Entry entry = journal.read(uuid); + if (entry == null) { + terminal = true; + return; + } + if (entry.phase() == DONE || entry.phase() == HELD) { + terminal = true; + return; + } + terminal = advance(player, liveName, entry); + } catch (InterruptedException stopped) { + Thread.currentThread().interrupt(); + } catch (IOException | TimeoutException | ExecutionException unavailable) { + // An uncertain response is retried using the same durable request on the next timer or join. + } finally { + boolean complete = terminal; + onMain(() -> { + active.remove(uuid); + if (complete) finished.add(uuid); + }); + } + } + + private boolean advance(Player player, String liveName, AccountJournal.Entry entry) + throws IOException, InterruptedException, TimeoutException, ExecutionException { + AccountJournal.Entry next = entry; + try { + if (next.phase() == PENDING) { + if (!next.name().equals(liveName)) return hold(player, liveName, next); + LobbyAccountApi.Reply reply = api.send(next, false); + boolean sent = deliver(player, liveName, next.player(), reply); + if (!sent) return false; + if (!reply.state().equals("created")) { + journal.write(next.advance(DONE)); + return true; + } + next = next.advance(ACK); + journal.write(next); + } + api.send(next, true); + journal.write(next.advance(DONE)); + return true; + } catch (LobbyAccountApi.Rejected rejected) { + return hold(player, liveName, next); + } + } + + private boolean hold(Player player, String name, AccountJournal.Entry entry) throws IOException { + journal.write(entry.advance(HELD)); + onMain(() -> { if (sameOnlineSession(player, entry.player(), name)) player.sendMessage(HELP); }); + return true; + } + + private boolean deliver(Player player, String name, UUID uuid, LobbyAccountApi.Reply reply) + throws InterruptedException, ExecutionException, TimeoutException { + var delivered = new CompletableFuture(); + onMain(() -> { + if (delivered.isDone()) return; + try { + if (!sameOnlineSession(player, uuid, name)) { + delivered.complete(false); + return; + } + switch (reply.state()) { + case "created" -> player.sendMessage(Component.text("DuneRealms account at cp.dunerealms.com\n" + + "Username: " + reply.username() + "\nTemporary password: " + reply.password() + + "\nChange your password after signing in.")); + case "existing" -> player.sendMessage(Component.text("Your DuneRealms account is already linked.")); + case "manual_link_required", "recovery_required" -> player.sendMessage(HELP); + default -> { } + } + delivered.complete(true); + } catch (RuntimeException failed) { + delivered.complete(false); + } + }); + try { + return delivered.get(10, TimeUnit.SECONDS); + } finally { + delivered.cancel(false); + } + } + + private boolean sameOnlineSession(Player player, UUID uuid, String name) { + return running && player.isOnline() && Bukkit.getPlayer(uuid) == player + && uuid.equals(player.getUniqueId()) && name.equals(player.getName()); + } + + private void onMain(Runnable action) { + if (!running) return; + try { + getServer().getScheduler().runTask(this, action); + } catch (org.bukkit.plugin.IllegalPluginAccessException disabled) { + // Receipts remain durable for the next plugin start. + } + } +} diff --git a/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java new file mode 100644 index 00000000..feaf5a76 --- /dev/null +++ b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java @@ -0,0 +1,108 @@ +package com.dunerealms.lobbyaccount; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.time.Duration; +import java.util.Set; + +final class LobbyAccountApi implements AutoCloseable { + private static final URI ENDPOINT = URI.create("https://cp.dunerealms.com/internal/game/lobby-account"); + private static final int MAX_RESPONSE = 4096; + private static final Set PROVISION_STATES = Set.of( + "created", "existing", "delivered", "manual_link_required", "recovery_required"); + + record Reply(String state, String username, String password) { + @Override public String toString() { return "Provisioning reply: " + state; } + } + + static final class Rejected extends IOException { + Rejected() { super("Provisioning request rejected"); } + } + + private final Path tokenPath; + private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)) + .followRedirects(HttpClient.Redirect.NEVER).build(); + + LobbyAccountApi(Path tokenPath) { this.tokenPath = tokenPath; } + + void verifyCredential() throws IOException { credential(); } + + Reply send(AccountJournal.Entry entry, boolean ack) throws IOException, InterruptedException { + JsonObject payload = request(entry, ack); + var request = HttpRequest.newBuilder(ENDPOINT).timeout(Duration.ofSeconds(12)) + .header("Authorization", "Bearer " + credential()) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(payload.toString())).build(); + var response = http.send(request, HttpResponse.BodyHandlers.ofInputStream()); + try (var stream = response.body()) { + if (response.statusCode() == 403 || response.statusCode() == 409) throw new Rejected(); + if (response.statusCode() != 200 && response.statusCode() != 201) throw unavailable(); + byte[] body = stream.readNBytes(MAX_RESPONSE + 1); + if (body.length > MAX_RESPONSE) throw unavailable(); + return parse(new String(body, StandardCharsets.UTF_8), entry, ack); + } + } + + static JsonObject request(AccountJournal.Entry entry, boolean ack) { + var payload = new JsonObject(); + payload.addProperty("schema", 1); + payload.addProperty("action", ack ? "ack" : "provision"); + payload.addProperty("requestId", entry.request().toString()); + payload.addProperty("uuid", entry.player().toString()); + if (!ack) payload.addProperty("name", entry.name()); + return payload; + } + + static Reply parse(String body, AccountJournal.Entry entry, boolean ack) throws IOException { + try { + JsonObject data = JsonParser.parseString(body).getAsJsonObject(); + if (!data.getAsJsonPrimitive("ok").isBoolean() || !data.get("ok").getAsBoolean() + || !data.getAsJsonPrimitive("schema").isNumber() || !data.get("schema").getAsString().equals("1") + || !(ack ? "ack" : "provision").equals(string(data, "action")) + || !entry.request().toString().equals(string(data, "requestId")) + || !entry.player().toString().equals(string(data, "uuid"))) throw unavailable(); + String state = string(data, "state"); + if (ack ? !"delivered".equals(state) : state == null || !PROVISION_STATES.contains(state)) throw unavailable(); + String username = string(data, "username"); + String password = string(data, "password"); + if ("manual_link_required".equals(state) && "".equals(username)) username = null; + if (username != null && !username.matches("[a-z0-9_]{1,64}")) throw unavailable(); + if ("created".equals(state)) { + if (username == null || password == null || !password.matches("[!-~]{20,128}")) throw unavailable(); + } else if (data.has("password")) { + throw unavailable(); + } + return new Reply(state, username, password); + } catch (RuntimeException invalid) { + throw unavailable(); + } + } + + private static String string(JsonObject data, String key) { + var value = data.get(key); + return value != null && value.isJsonPrimitive() && value.getAsJsonPrimitive().isString() ? value.getAsString() : null; + } + + private String credential() throws IOException { + if (!Files.isRegularFile(tokenPath, LinkOption.NOFOLLOW_LINKS) || Files.size(tokenPath) > 1024 + || !Files.getPosixFilePermissions(tokenPath).equals(PosixFilePermissions.fromString("rw-------"))) + throw unavailable(); + String token = Files.readString(tokenPath, StandardCharsets.US_ASCII).strip(); + if (!token.matches("[A-Za-z0-9._~+/-]{32,512}={0,2}")) throw unavailable(); + return token; + } + + private static IOException unavailable() { return new IOException("Provisioning service unavailable"); } + + @Override public void close() { http.shutdownNow(); } +} diff --git a/DuneLobbyAccount/src/main/resources/plugin.yml b/DuneLobbyAccount/src/main/resources/plugin.yml new file mode 100644 index 00000000..b7dcfa0e --- /dev/null +++ b/DuneLobbyAccount/src/main/resources/plugin.yml @@ -0,0 +1,5 @@ +name: DuneLobbyAccount +version: 1.0.1 +main: com.dunerealms.lobbyaccount.DuneLobbyAccount +api-version: '1.21.8' +description: Provisions ordinary DuneRealms accounts from authenticated first Lobby joins diff --git a/DuneLobbyAccount/src/test/java/com/dunerealms/lobbyaccount/LobbyAccountContractTest.java b/DuneLobbyAccount/src/test/java/com/dunerealms/lobbyaccount/LobbyAccountContractTest.java new file mode 100644 index 00000000..e9632d16 --- /dev/null +++ b/DuneLobbyAccount/src/test/java/com/dunerealms/lobbyaccount/LobbyAccountContractTest.java @@ -0,0 +1,92 @@ +package com.dunerealms.lobbyaccount; + +import static com.dunerealms.lobbyaccount.AccountJournal.Phase.*; +import static org.junit.jupiter.api.Assertions.*; + +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class LobbyAccountContractTest { + private final AccountJournal.Entry request = new AccountJournal.Entry(UUID.randomUUID(), UUID.randomUUID(), ".Bedrock-Name", PENDING); + private static final String PASSWORD = "TestSecretNeverInReceipt_123"; + + @Test void journalSurvivesRestartAndNeverStoresPassword(@TempDir Path temp) throws Exception { + Path folder = temp.resolve("receipts"); + var first = new AccountJournal(folder); + assertNull(first.read(request.player())); + first.write(request); + var restarted = new AccountJournal(folder); + assertEquals(request, restarted.read(request.player())); + restarted.write(request.advance(ACK)); + assertEquals(request.advance(ACK), first.read(request.player())); + String text = Files.readString(folder.resolve(request.player() + ".receipt")); + assertFalse(text.contains(PASSWORD)); + assertEquals(4, text.lines().count()); + assertThrows(IOException.class, () -> restarted.write(new AccountJournal.Entry(request.player(), request.request(), "x\ny", PENDING))); + } + + @Test void aPendingFirstJoinCanBeRecoveredBeforeAnyWorkerRan(@TempDir Path temp) throws Exception { + UUID player = request.player(); + var first = new AccountJournal(temp.resolve("receipts")); + var admitted = first.admit(player, request.name()); + var restarted = new AccountJournal(temp.resolve("receipts")); + assertEquals(admitted, restarted.read(player)); + assertEquals(PENDING, admitted.phase()); + assertEquals(admitted, restarted.admit(player, "Renamed")); + restarted.write(admitted.advance(ACK)); + assertEquals(admitted.advance(ACK), first.admit(player, request.name())); + } + + @Test void requestAndAcknowledgementHaveExactWireFields() { + JsonObject provision = LobbyAccountApi.request(request, false); + assertEquals(Set.of("action", "schema", "requestId", "uuid", "name"), provision.keySet()); + assertEquals(request.name(), provision.get("name").getAsString()); + JsonObject ack = LobbyAccountApi.request(request.advance(ACK), true); + assertEquals(Set.of("action", "schema", "requestId", "uuid"), ack.keySet()); + assertEquals(provision.get("requestId"), ack.get("requestId")); + assertEquals(provision.get("uuid"), ack.get("uuid")); + } + + @Test void onlyExactBoundCreatedResponseMayExposePassword() throws Exception { + JsonObject reply = response(false, "created"); + reply.addProperty("username", "bedrock_name"); + reply.addProperty("password", PASSWORD); + assertEquals(PASSWORD, LobbyAccountApi.parse(reply.toString(), request, false).password()); + assertFalse(LobbyAccountApi.parse(reply.toString(), request, false).toString().contains(PASSWORD)); + reply.addProperty("requestId", UUID.randomUUID().toString()); + assertThrows(IOException.class, () -> LobbyAccountApi.parse(reply.toString(), request, false)); + reply.addProperty("requestId", request.request().toString()); + reply.addProperty("uuid", UUID.randomUUID().toString()); + assertThrows(IOException.class, () -> LobbyAccountApi.parse(reply.toString(), request, false)); + } + + @Test void existingRecoveryAndAcknowledgementDoNotAcceptSecrets() throws Exception { + for (String state : Set.of("existing", "manual_link_required", "recovery_required", "delivered")) { + JsonObject reply = response(false, state); + reply.add("username", JsonNull.INSTANCE); + assertNull(LobbyAccountApi.parse(reply.toString(), request, false).password()); + reply.addProperty("password", PASSWORD); + assertThrows(IOException.class, () -> LobbyAccountApi.parse(reply.toString(), request, false)); + } + assertEquals("delivered", LobbyAccountApi.parse(response(true, "delivered").toString(), request, true).state()); + assertThrows(IOException.class, () -> LobbyAccountApi.parse(response(true, "created").toString(), request, true)); + JsonObject manual = response(false, "manual_link_required"); + manual.addProperty("username", ""); + assertNull(LobbyAccountApi.parse(manual.toString(), request, false).username()); + } + + private JsonObject response(boolean ack, String state) { + JsonObject reply = LobbyAccountApi.request(request, ack); + reply.remove("name"); + reply.addProperty("ok", true); + reply.addProperty("state", state); + return reply; + } +} diff --git a/DuneMenus/README.md b/DuneMenus/README.md new file mode 100644 index 00000000..2ee8e176 --- /dev/null +++ b/DuneMenus/README.md @@ -0,0 +1,9 @@ +# DuneMenus presentation + +Owner-supplied DuneMenus layouts, wired to the existing JARVIS public API. The Java presentation uses the installed MC GUI canvas transport. Bedrock uses native Floodgate forms from the same definitions. No demo backend, ChestCommands or additional confirmation intermediary is installed. + +Build and deployment are exclusively through the canonical plugin CI workflow. Keep DunerealmsGUI.jar (NPC/backend services and canvas transport), DuneNPC.jar, and jarvistranslator.jar. DuneMenus.jar contains the supplied presentation definitions and adapter. Do not run the historical installer that removes DunerealmsGUI. + +`/dm` and the existing GUI commands open the replacement. Existing NPC contact/service callbacks are presented through ServiceMenu, preserving their permissions, quotes and revisions. `/sellall`, administration commands and scoreboard controls stay with their original handlers. + +The source ZIP and its SHA-256 are recorded in REFERENCE.md. Previews are reference artwork, not evidence of a deployed or pixel-identical screen. Runtime rendering and every callback family must be verified before deployment is reported complete. diff --git a/DuneMenus/REFERENCE.md b/DuneMenus/REFERENCE.md new file mode 100644 index 00000000..02a1972f --- /dev/null +++ b/DuneMenus/REFERENCE.md @@ -0,0 +1,3 @@ +Presentation reference: owner-supplied DuneMenus.zip. +SHA-256: e0862cf79874d3c551f8fb2e563d1a4412a7176367c572a53f8667b0f470b358 +The versioned JARVIS adapter preserves authoritative quotes and revisions. Existing DuneRealmsGUI services and DuneNPC remain installed. diff --git a/DuneMenus/build.gradle.kts b/DuneMenus/build.gradle.kts new file mode 100644 index 00000000..2d0b8fcb --- /dev/null +++ b/DuneMenus/build.gradle.kts @@ -0,0 +1,78 @@ +import java.security.MessageDigest +plugins { java } +group = "com.dunerealms" +version = "2.0.10-housecompact1" +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") + maven("https://repo.opencollab.dev/main/") +} +dependencies { + compileOnly(project(":JarvisConnector")) + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testImplementation("org.mockito:mockito-core:5.15.2") + testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation(project(":JarvisConnector")) + testRuntimeOnly("org.junit.platform:junit-platform-launcher") + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT") // same coordinates as DunerealmsGUI +} +java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } +tasks.withType { options.encoding = "UTF-8" } +tasks.jar { archiveFileName.set("DuneMenus.jar") } +tasks.processResources { inputs.property("pluginVersion",project.version.toString()); filesMatching("plugin.yml") { expand("version" to project.version) } } + +tasks.test { useJUnitPlatform() } + +// Optional, reproducible verification against the privately supplied, pinned MCGUI runtime. +// The third-party JAR is never bundled or committed. +val mcguiRuntime = providers.gradleProperty("mcguiRuntime") +val rendererRuntimeFiles = mcguiRuntime.map { files(it) }.getOrElse(files()) +val rendererTest by sourceSets.creating { + compileClasspath += sourceSets.main.get().output + rendererRuntimeFiles + runtimeClasspath += sourceSets.main.get().output + rendererRuntimeFiles +} +val verifyRendererRuntime by tasks.registering { + doLast { + require(mcguiRuntime.isPresent) { "Supply -PmcguiRuntime=" } + val jar = file(mcguiRuntime.get()) + require(jar.isFile) { "MCGUI runtime file not found" } + val hash = MessageDigest.getInstance("SHA-256").digest(jar.readBytes()).joinToString("") { "%02x".format(it) } + require(hash == "69a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300") { "MCGUI runtime differs from reviewed test input" } + logger.lifecycle("Renderer verification: MCGUI0.8.6 SHA-256 {}", hash) + } +} +tasks.named(rendererTest.compileJavaTaskName) { dependsOn(verifyRendererRuntime) } +tasks.register("verifyMenuRenderer") { + dependsOn(rendererTest.classesTaskName) + classpath = rendererTest.runtimeClasspath + mainClass.set("com.dunerealms.menus.RendererVerification") + jvmArgs("-Djava.awt.headless=true") + args(providers.gradleProperty("rendererOutput").getOrElse(layout.buildDirectory.dir("renderer-verification").get().asFile.absolutePath)) +} + +// Reuse committed central artwork. No network requests occur when a menu opens. +tasks.processResources { + from("../network/resource-pack/vanilla-art/overlay") { into("menu-art/pack") } + from("../network/resource-pack/central/overlay") { + into("menu-art/pack") + include("assets/dunerealms/items/**", "assets/dunerealms/models/**", "assets/dunerealms/textures/**") + // These Arrakis gameplay models are delivered by the server pack. + for (item in listOf("crysknife", "maker_tooth", "wrench")) { + exclude("assets/dunerealms/items/$item.json", "assets/dunerealms/models/item/$item.json", + "assets/dunerealms/textures/item/$item.png") + } + exclude("assets/dunerealms/items/dune_beacon.json", "assets/dunerealms/models/item/dune_beacon.json", + "assets/dunerealms/models/block/dune_beacon.json", "assets/dunerealms/textures/block/dune_beacon_*.png") + exclude("assets/dunerealms/items/ender_chest.json", "assets/dunerealms/models/item/ender_chest.json", + "assets/dunerealms/models/block/ender_chest.json", "assets/dunerealms/models/block/ender_chest_barrel_display.json", + "assets/dunerealms/items/ender_chest_barrel_display.json", "assets/dunerealms/textures/block/ender_chest_*.png") + for (tier in 1..3) { + for (model in listOf("speed_hopper_$tier", "speed_hopper_${tier}_side")) { + exclude("assets/dunerealms/items/$model.json", "assets/dunerealms/models/item/$model.json", + "assets/dunerealms/models/block/$model.json") + } + exclude("assets/dunerealms/textures/block/speed_hopper_$tier.png") + } + } +} diff --git a/DuneMenus/docs/BACKEND.md b/DuneMenus/docs/BACKEND.md new file mode 100644 index 00000000..a65279a2 --- /dev/null +++ b/DuneMenus/docs/BACKEND.md @@ -0,0 +1,7 @@ +# Existing JARVIS backend + +JarvisBackend invokes JarvisTranslator public methods. Mutations retain quoted listing identity/version/price, membership identity and authority revision, Guild key/version/fare, equipment quote IDs, cash denominations and request references. The central backend remains authoritative. JarvisConnector source is unchanged by this presentation integration. + +Native NPC services retain their existing callbacks through DunerealmsGUI's SuppliedMenus bridge. The bridge preserves the original GuiSession claim and uses the new frontend only for presentation. A renderer session must not create another GuiSession that replaces that native claim. + +No demo backend is packaged. An unavailable backend fails closed; no locally invented balances, missions or permissions are substituted. diff --git a/DuneMenus/docs/CANARY-RECOVERY-20261129.md b/DuneMenus/docs/CANARY-RECOVERY-20261129.md new file mode 100644 index 00000000..7555ea3d --- /dev/null +++ b/DuneMenus/docs/CANARY-RECOVERY-20261129.md @@ -0,0 +1,13 @@ +# GUI canary recovery and revised boundary + +Source e19acd25497de3501a9d9b62e9b9e23e5c1521ce passed canonical CI16 (API985). Its immutable composite menu pack was published and independently hash-verified. The lobby-only canary loaded MCGUI0.8.6, DunerealmsGUI1.1.32 and DuneMenus2.0.1 and reached Paper Done in 87.397 seconds. This is startup evidence, not connected-client proof. + +At 02:23:39 the incoming rebuilt Essentials failed its Solaris database initialisation: PostgreSQL `UUID PRIMARY KEY` DDL was rejected by the actual MySQL backend. The wider rollout stopped. No planet was installed. This is a known unresolved compatibility limitation of the rebuilt Essentials module; excluding it from the GUI release does not fix it. + +The authorised coordinator restored exact receipt-backed original lobby JAR/configuration bytes at 02:24:57 and verified original hashes. Original Paper reached Done at 02:26:23. The recovery report is stored alongside the canary receipt under the host's gui-e19acd2 backup. The incoming GUI runtime JARs were removed/restored with the receipt. All four restored original JARs were independently rechecked as UID988/GID988/mode0644. The legacy receipt had not recorded original owners; those recovered metadata values were explicitly set using independently verified service ownership, not recovered from the receipt. + +Missing native-food projection warnings for chukka_cooked_meat and water_of_life also occurred with the original restored JARVIS. They are pre-existing baseline warnings, not evidence of a newly introduced JARVIS regression. They are outside this presentation correction. + +The revised release preserves every live Essentials/JARVIS/Core/Terrain JAR. Only presentation/NPC/Lobby adapters and the private pinned MCGUI prerequisite may be installed. The frontend wraps only exact no-target Essentials menu/travel/exchange entry points; targeted travel, purchases, payments, permissions and other operations delegate unchanged to the existing executor. ABI fixtures contain public signatures and reviewed hashes from two live JARVIS, four Core and three Essentials variants, not private binaries or configuration. The tests audit compiled incoming JARs against every JARVIS/Core variant combination and verify the Essentials command roots. This verifies linkage boundaries, not a player session or a live transaction. + +New receipt-based explicit rollback supports plugin-level readiness failure after systemd reports active. It verifies backup/current bytes, restores original filenames and metadata, and keeps world resource-pack properties untouched. A new successful canary and fleet readiness verification remain required before claiming deployment. Citizens conversion remains pending a verified compatible vendor runtime. diff --git a/DuneMenus/docs/CENTRAL-PACK-DEPLOYMENT-20261129.md b/DuneMenus/docs/CENTRAL-PACK-DEPLOYMENT-20261129.md new file mode 100644 index 00000000..bed7f93e --- /dev/null +++ b/DuneMenus/docs/CENTRAL-PACK-DEPLOYMENT-20261129.md @@ -0,0 +1,56 @@ +# Central pack deployment evidence โ€” 29 November 2026 + +## Execution brief and result + +Objective: deliver the owner-supplied custom item artwork, retained card fonts/custom assets and MCGUI transport as one complete pinned pack across all six existing backends, preserving the working backend. Correct the demonstrated configuration-phase menu readiness failure through source, review and canonical CI. + +This report and guide correction are documentation only. Installed runtime remains source `a3dee6dfd8289b8c6d5c00b70b798661e96a62b9`, GUI1.1.35, from canonical CI22/API1006/job1019/artifact6915. Do not deploy artifacts built from this documentation commit. + +The authorised host coordinator independently verified the delivered artifact, applied only the built publisher/installer and supplied the seven sanitised JSON evidence files in [evidence/central-a3dee6d](evidence/central-a3dee6d/central-a3dee6d-summary.json). No direct SSH was used from the plugin source chat. No quest or vanilla-artwork drafts were deployed. + +## Exact tested release + +- Source/PR: a3dee6dfd8289b8c6d5c00b70b798661e96a62b9, plugin PR7; verified on main and stale-open PR closed after integration. +- Canonical CI22 succeeded: all eight first-party modules tested/built and46 Python checks passed. Local GUI test suite passed41 tests, including six new configuration/readiness lifecycle cases. Other backend binaries compiled for visibility were not installed. +- Downloaded artifact6915 wrapper:40,689,942 bytes, SHA256 `375d18d53f58d818e577a04020d21629212d387bfa1c1ce8821a0cfeeb76091e`. Forgejo's stored artifact size is not the downloaded wrapper size. All19 checksum targets and six deployed helper source bytes were verified by the coordinator. +- Installed `DunerealmsGUI.jar`1.1.35: SHA256 `887583ada3da1d09c5fa4ab675cb5387cc34682d68c72b4aa616d754809bf3b2`. +- Pack: `DuneRealms-Resources-a3dee6dfd8289b8c6d5c00b70b798661e96a62b9.zip`,17,082,715 bytes,1174 entries;304 models,304 item definitions and4 fonts validated. +- Pack SHA1 `c3aac94fc0265702aae4e4a6d03af3d4b3ae5ce3`; SHA256 `8553a730579fd5f594a21a9d213d065a2d4ef89d4ad272ea5230355e447dbc6e`. +- One server-owned UUID on all six: `c24c7cf5-a292-539d-971f-a96d8b838162`. +- Public immutable URL: https://www.dunerealms.com/downloads/DuneRealms-Resources-a3dee6dfd8289b8c6d5c00b70b798661e96a62b9.zip . Actual public bytes were checked against the built hash. + +The pack bytes are identical to the earlier77cf candidate. GUI1.1.33 was never installed. GUI1.1.34/77cf was canaried on lobby and Arrakis only; the menu readiness failure held the remaining four. The correction changes readiness, not the artwork or JARVIS backend. + +## Publication and installation + +The built publisher staged the immutable file, preserved previous download routes, backed up the included nginx snippet and validated nginx before reload under the shared publication lock. The final snippet backup is `/etc/nginx/snippets/dunerealms-gui-download-v3.conf.before-menu-20261129T080321.191253Z`. The earlier77cf publication backup is `.before-menu-20261129T073927.921211Z`; its recorded snippet hash changed from `d62d091ecb3c1c5bebf13af3f751081b88b87a9b0c32138c249227bad31e132e` to `8d904b98c443913f0902a68340576ae2ccd5a93e7b93e0cea8215534abdc9b92`. Both immutable versions remain retained for rollback/history. + +Exact built release files were hash-verified on both game hosts. Read-only plans passed the retained-backend ABI/hash guards. Each application selected only DunerealmsGUI.jar, backed up before replacement, stopped/restarted the verified existing service and wrote the owned menu/runtime configurations plus the four resource-pack properties. All other installed JAR hashes and UID/GID/modes, and every non-pack semantic server property, were verified unchanged. Paper's generated properties comment timestamp is not treated as byte-for-byte preservation. + +| Server | Receipt under `/opt/dunerealms/backups/central-a3dee6d/` | Result | +| --- | --- | --- | +| lobby | `20261129T080452.478197Z/lobby/receipt.json` | PaperDone, GUI1.1.35 enabled; owner menu confirmation | +| arrakis | `20261129T080936.878496Z/arrakis/receipt.json` | PaperDone, GUI1.1.35 enabled | +| caladan | `20261129T081013.850457Z/caladan/receipt.json` | PaperDone, GUI1.1.35 enabled | +| giedi_prime | `20261129T081013.850457Z/giedi_prime/receipt.json` | PaperDone, GUI1.1.35 enabled | +| kaitain | `20261129T081013.850457Z/kaitain/receipt.json` | PaperDone, GUI1.1.35 enabled | +| sigma_draconis_iv | `20261129T081013.850457Z/sigma_draconis_iv/receipt.json` | PaperDone, GUI1.1.35 enabled | + +Receipt3 and the same built explicit rollback CLI retain original JAR/config/property bytes and metadata. Refuse rollback over unknown later changes; never substitute guessed paths/ownership or deploy a manually patched JAR. No rollback of the final a3 release was required. The earlier e19 rollback is separately recorded in CANARY-RECOVERY-20261129.md and must not be conflated with this release. + +## Readiness and connected-client evidence + +The client's earlier missing default-font reference caused full pack rejection. The central build restores complete font/model closure. After central loading, the inspected client log no longer showed that missing-font/default-font failure. Custom item visibility was reported by the owner; this alone was not taken as proof of every asset or the new menu readiness. + +The owner then demonstrated the menu-unavailable message. Exact Paper26.2-135 bytecode showed configuration-phase pack success is recorded on the connection without a Bukkit play-phase player event. GUI1.1.35 seeds readiness at join/startup only for the validated server-owned pin and actual SUCCESSFULLY_LOADED connection status, retains MCGUI.hasPack checks, revokes later matching pending/failure states and ignores unrelated UUIDs. + +After the lobby update, the actual server log recorded central UUID loaded at08:09:08UTC (09:09:08 Europe/Brussels), and the owner explicitly confirmed โ€œMenu opens.โ€ This establishes one connected-client lobby menu success. It does not prove every world, equipment appearance, NPC interaction or callback. + +## Known limits and preserved baseline issues + +- Arrakis, Caladan, Giedi Prime and Sigma Draconis IV had no ERROR lines in the reviewed startup captures. Lobby's two JARVIS food/brewing projection failures (`chukka_cooked_meat`, `water_of_life`) matched prior baseline logs. +- Kaitain's25 Typewriter missing-entry signatures all matched `2026-11-29-2.log.gz` before this rollout. They were not repaired or claimed as new regressions here. +- Citizens conversion and broader rebuilt-backend/MySQL compatibility remain separate pending work. Existing backend bytes, permissions and earned progression were preserved. +- The comprehensive Dune redesign of ordinary vanilla blocks/items is a separate unfinished artwork task. This release contains supplied custom artwork and existing spice overrides; default ordinary blocks are expected. No Bedrock or all-equipment visual acceptance is claimed. + +Acceptance for this bounded release is canonical tested source, verified immutable public pack, receipt-backed six-server installation/startup, retained backend/property checks, and the explicitly bounded lobby client confirmation. Future visual/gameplay coverage must be recorded separately. diff --git a/DuneMenus/docs/CENTRAL-PACK-INTEGRATION.md b/DuneMenus/docs/CENTRAL-PACK-INTEGRATION.md new file mode 100644 index 00000000..f432af3b --- /dev/null +++ b/DuneMenus/docs/CENTRAL-PACK-INTEGRATION.md @@ -0,0 +1,37 @@ +# One central DuneRealms resource pack + +## Owner request and bounded execution brief + +Replace the old per-world pack structure with one Dune-themed pack on all six backends. Integrate the two owner-provided archives and their full accompanying report; preserve card-art atlases and the working GUI/JARVIS backend. The supplied assets supersede the paused Xeindom/XAE experiment. No Xeindom input is used by this build. + +Inputs: DuneRealms-Pack-Source.zip SHA256 `6e04997793324acd48946ea39e0fc08c4b03cce8c71bceb1fbe5d5d4c7d5e0cd`; DuneRealms-Central-Pack.zip SHA256 `01be079ac91687710a94993e5cf9742506f54ef8bc933f3f799340bcc1be0806`. Archive README/report instructions were reviewed as integration context, not executed blindly. The incoming pack is an overlay, not a standalone replacement. Its claimed reference validation is independently checked after complete assembly. + +Source is under `network/resource-pack/central/`: original procedural generator (ported only to repository-owned input/font paths), owner-supplied overlay artwork, and necessary existing custom DuneRealms assets. Existing shared card fonts/atlases and the pinned MCGUI transport are included by the builder. Untouched vanilla blocks keep vanilla assets; this is not a claim that all vanilla terrain textures were redrawn. The original per-world vanilla material overrides are not carried forward. + +Steps: validate/pin inputs; assemble deterministic complete ZIP; validate model parents/textures/items/fonts/atlases against the actual official26.3 client; add cosmetic item-model hooks; bind GUI readiness to the server-owned pack UUID; test deployment and rollback; build through canonical CI; publish immutable bytes; canary and then verify all six. No backend schema, payment, item-stat or world-generation changes. + +## Build and visual boundaries + +`tools/build-unified-resourcepack.py --source EXACT_SHA --output DuneRealms-Resources-EXACT_SHA.zip` builds from checked-in art. Its validation client is the official26.3 JAR pinned in inputs.lock.json (downloaded into build cache, never redistributed). Metadata supports formats88โ€“97 (26.2โ€“26.3), with the vendor's original versioned transport entries preserved; the overlay's unverified46โ€“99 declaration is replaced. + +The complete pack retains existing card-art glyphs and food/entity assets, including the exact owner-observed `dunerealms:ecology/jerboa_cooked_meat` and `dunerealms:equipment/uncommon_mk3_{helmet,chestplate,leggings,boots}` keys. Tests cover all224 quality/equipment variants and the complete model/font graph. No minecraft:default font override is included. The historical dangling dunerealms:imperial_menus reference has a real compatible font definition; a negative regression fixture reproduces the fatal missing-font condition and fails validation. + +The GUI adapter type-checks legacy native ID, quality and MK tags before reading them; STRING and INTEGER marks are supported without invalid primitive casts. It changes only the item_model component from existing native IDs or valid existing quality/mark metadata. It does not generate grades, change native identity, item type/amount, damage, lore, enchantments, attributes or bank state. Unknown foreign/refit/food models remain untouched. Known obsolete per-world visual components are cleared while retaining their original materials and provenance. Relevant join, inventory, held-item, pickup and drop paths receive presentation hooks; newly stamped authoritative metadata is read on the server thread. + +The owner acknowledges that every dried kelp block uses the spice carrier texture network-wide, including crafted blocks/lobby. Suspicious sand stages also change globally. Worn armour skins and entity redesign are outside the supplied overlay; existing required custom entity artwork is retained. Bedrock/Geyser conversion is not claimed. + +## One-file delivery and rollback + +Use one permanent URL `https://www.dunerealms.com/downloads/DuneRealms-Resources-EXACT_SHA.zip`, exact built SHA1/SHA256 and UUID `c24c7cf5-a292-539d-971f-a96d8b838162` on every backend. GUI menu-pack.yml uses delivery: server and the same UUID. It observes SUCCESSFULLY_LOADED for that UUID and never offers a second GUI pack. MCGUI remains external merged mode, public-url empty, telemetry disabled; the pinned runtime's merged hasPack behavior is guarded by the GUI's actual successful-load state. + +The built immutable publisher retains old download routes for rollback. The explicit fleet installer retains the gui-preserve-backends guard. For this rollout select ONLY DunerealmsGUI.jar (version1.1.34); keep installed DuneMenus/NPC/Lobby/MCGUI and all backend JARs. Before applying, the coordinator independently verifies actual inventory and a published pack hash. Use the selected built tools and manifest together. + +Receipt format3 additionally backs up server.properties bytes/UID/GID/mode and changes ONLY resource-pack, resource-pack-sha1, resource-pack-id and require-resource-pack. Plans/receipts contain no other property values. Other fields are checked by canonical semantic hashes; Paper-generated timestamp comments are not treated as configuration drift. Explicit application-level rollback restores original JAR/configuration/properties bytes and metadata, and refuses unknown subsequent setting changes. Auto rollback restores the same state after a failed start. No direct SSH implementation is embedded; the authorised coordinating chat performs host invocation. + +## Validation and acceptance + +Required: canonical source build/tests; deterministic complete ZIP; all model/font/item/atlas references close against real client assets; duplicate atlas sprites and missing-font regressions fail; all224 equipment mappings resolve; final ZIP hashed after full assembly; public bytes equal CI; same URL/hash/UUID on all six; retained backend bytes/metadata unchanged; actual Minecraft client accepts the pack without default-font failure and displays food, equipment, currency, dropped items and blocks correctly; GUI and NPC actions remain functional. Server startup alone is not visual acceptance. + +Generator source is retained with pinned numpy/Pillow requirements and bundled OFL Poppins font; canonical releases package reviewed committed artwork instead of silently regenerating images with different library versions. Regeneration is an explicit review step into a fresh output directory. Input archive hashes, font source/license and legacy-art provenance are in inputs.lock.json. No paid product or vendor plugin JAR is added. + +Until an exact-source rollout is independently verified, this document describes source readiness and acceptance criteria, not a delivered or client-tested result. The separate spice-banking investigation is not changed by this pack integration. diff --git a/DuneMenus/docs/COMPACT-MENU-FOLLOWUP.md b/DuneMenus/docs/COMPACT-MENU-FOLLOWUP.md new file mode 100644 index 00000000..9110718c --- /dev/null +++ b/DuneMenus/docs/COMPACT-MENU-FOLLOWUP.md @@ -0,0 +1,15 @@ +# Compact menu follow-up + +Owner connected-client feedback requested cards approximately 25% smaller across all Java full-screen menus, compact Exchange navigation and one unambiguous working sell action. + +Menus 2.0.3 reduces standard card width from 22.5% to 16.875% and height from 186 to 140 CSS pixels, with smaller framed centred icons, padding and readable text. Mission/war journals use a compact grid rather than full-width rows. Council, bank and travel families retain their distinct layouts with reduced dimensions. Full text remains accessible through Details; price and stock stay first in summaries. + +Exchange navigation uses small toolbar controls. The misleading Sell navigation label is now My listings, preserving existing listing withdrawal/management. Add held item is the sole Sell item action and invokes the original working draft callback. No payment, JARVIS or retry semantics change. Empty own-listing results explicitly say No own listings and direct the player to Sell item. + +GUI version 1.1.37; actual plugin descriptor must agree. Pack content and backend JARs remain unchanged. Local renderer verification covers 15 families and 152 action hitboxes, text containment, centred icons, 28 long listings, Details and toolbar controls. Synthetic previews are not connected-client acceptance. Exact canonical CI and guarded rollout are required before live claims. + +Blocked claim-expansion buttons now report the same existing capacity/home/permission reason and reopen the claims view, rather than silently closing. No guard, entitlement, deed or claim record is bypassed. The specific Arrakis report (North worked, All did not) still requires actual estate/capacity evidence before attributing it to a backend fault. + +Owner-selected blocked-expansion feedback uses: I'm sorry, Dave. I cannot let you do that: . Required resulting size and unlocked limit remain accurate; a too-large expansion is not mislabelled as an already-full estate. + +A single adviser description includes the owner-requested subtle 'Indeed.' reference; no new action or repeated message. diff --git a/DuneMenus/docs/FLEET-INSTALL.md b/DuneMenus/docs/FLEET-INSTALL.md new file mode 100644 index 00000000..f1e8876e --- /dev/null +++ b/DuneMenus/docs/FLEET-INSTALL.md @@ -0,0 +1,31 @@ +# Verified plugin fleet installation + +Use only the installer and JARs emitted together by canonical plugin CI. This installer is for existing servers, not bootstrap provisioning. It never discovers or guesses server paths, assigns plugins to a server, removes unrelated backends, deploys website files, or downloads third-party dependencies. + +The coordinator supplies an independently verified inventory JSON. Each `servers` entry requires `id`, absolute `root`, existing `serviceUnit`, and an explicit list of artifact filenames from `release-manifest.json`. Do not populate these from historical example paths. DuneMenus requires JARVIS, DunerealmsGUI and the existing MCGUI runtime; DuneNPC is retained. + +Inventory must explicitly set `"mode": "gui-preserve-backends"`. This release ships only DuneMenus.jar, DunerealmsGUI.jar, DuneRealms-NPC.jar and DuneRealms-Lobby.jar; select Lobby only on the lobby server. The installer rejects incoming JARVIS, Essentials, Core or Terrain. CI still compiles/tests their source, but those binaries are excluded from this GUI artifact. Retained JARVIS/Core/Essentials must match independently reviewed live hashes in preserved-backend-abi.json. Planning checks actual frontend method/field descriptors against those retained JARs, including reflective HouseBridge calls. Their bytes and current UID/GID/mode are checked again before installation and restart. The existing backend remains authoritative for transactions and permissions. + +First run a read-only plan with `--artifacts`, `--inventory`, and `--expected-source` set to the exact CI source SHA. Apply that same inventory with `--apply --backup-root` only through the authorised host deployment entry point. No SSH implementation is embedded in this tool. + +All artifacts, descriptors, installed-file snapshots and backups are verified. Services must be fully stopped before JAR replacement; active services restart afterward, previously stopped services remain stopped. Old filenames are replaced by actual plugin identity. On an installation/start failure, original bytes and filenames are restored after verifying the service is stopped, and a rollback receipt is retained. A rollback that cannot stop the service halts without replacing active JARs. A multi-server failure may leave earlier servers installed; inspect each receipt. + +An `installed-service-active` receipt proves file installation and systemd state only. It does not prove Minecraft finished loading or an NPC interaction worked. Verify server logs, enabled versions, resource-pack publication/configuration, actual GUI/NPC actions and retained progression separately before reporting rollout complete. Resource-pack publication uses the separate built publisher; required menu configuration is verified and managed by this installer as described in MENU-PACK-ROLLOUT.md. + + +A missing existing MCGUI runtime may be staged privately by the authorised coordinator. Inventory `privatePrerequisites.MCGUI` requires an absolute `path` and the reviewed SHA-256 `69a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300`; the server entry must explicitly list `prerequisites: ["MCGUI"]`. The installer verifies plugin name MCGUI, version0.8.6 and main ai.resourcepack.ui.MCGUIPlugin before including those privately staged bytes. They are never added to the public source/release artifact. Unknown private prerequisites or different bytes/identities fail planning. The private runtime's installation and rollback follow the same stopped-service, backup and checksum path as first-party JARs. + +For unified central-pack releases, inventory menuPack.url is mandatory even when selecting only DunerealmsGUI.jar, and actual public bytes must match the built complete pack. Owned config bytes are hashed, backed up and restored with JAR rollback; existing unmanaged config fails closed. The current installer manages exactly four server.properties keys: resource-pack, resource-pack-sha1, resource-pack-id and require-resource-pack. Every other semantic property is preserved. Receipt3 backs up the original properties bytes and UID/GID/mode; rollback refuses unknown later semantic changes and restores the original backup. Paper may rewrite its generated comment timestamp during startup, so full-file byte equality after restart is not an acceptance claim. Legacy stacked releases do not request these property changes. See MENU-PACK-ROLLOUT.md and CENTRAL-PACK-INTEGRATION.md for the current persistent publication and runtime contracts. + +## Rollback after application readiness failure + +Systemd active is insufficient: check Paper startup and plugin readiness before proceeding beyond a canary. To restore a selected receipt after an application-level failure, use the same built tools: + +```sh +python3 install-plugin-fleet.py --rollback-receipt /verified/backup/receipt.json --expected-source EXACT_40_CHARACTER_SOURCE_SHA +# Review the plan, then repeat with --apply. +``` + +Current version3 receipts capture original filenames, hashes, UID/GID/mode, owned configuration bytes/metadata, optional four-key server-properties changes/backups and whether the service was active. Version2 receipts remain supported for the previous stacked release without a server-properties change. Rollback verifies backups and refuses to overwrite later unknown changes before stopping anything. It restores original metadata exactly and restarts only an originally active service. An already restored receipt is idempotent. Minecraft readiness still needs independent verification. + +Legacy receipts lacking ownership/state require explicitly verified `--legacy-owner UID:GID --legacy-was-active yes|no`; never infer historical ownership from a backup copied as root. For the already recovered e19 lobby canary, the coordinator independently verified current restored JAR metadata as UID988/GID988/mode0644 and original active state. Original owner metadata was not captured in that legacy receipt. These facts do not authorise applying guessed values to other receipts. diff --git a/DuneMenus/docs/FULLSCREEN.md b/DuneMenus/docs/FULLSCREEN.md new file mode 100644 index 00000000..3a167c65 --- /dev/null +++ b/DuneMenus/docs/FULLSCREEN.md @@ -0,0 +1,9 @@ +# Canonical canvas integration + +CanvasProvider supplies the new SuppliedDocument to DunerealmsGUI.presentSuppliedMenu. That method reuses the installed MCGUI canvas/HTML transport and its hosted resource pack. It does not call the old MenuDocument renderer. Java pages use direct slot actions; Bedrock receives the same menu definitions as native forms. + +Read-only facts remain visible below the cards; long listing/journal pages grow so the canvas renderer can scroll the document. Dynamic labels/lore are escaped. Rendering failure and pack absence fail closed rather than substitute demo data. + +Existing service callbacks are wrapped by the native GuiSession and the new menu's world/presentation generation guards. The transport must not create a second GuiSession for these supplied pages, because that would invalidate the authoritative native session. + +CI builds DuneMenus.jar together with DunerealmsGUI.jar, DuneNPC.jar and the unchanged JARVIS backend. No independent live-file installation is part of this change. diff --git a/DuneMenus/docs/GUI-DEPLOYMENT-20261129.md b/DuneMenus/docs/GUI-DEPLOYMENT-20261129.md new file mode 100644 index 00000000..215b4ab7 --- /dev/null +++ b/DuneMenus/docs/GUI-DEPLOYMENT-20261129.md @@ -0,0 +1,46 @@ +# GUI deployment evidence โ€” 29 November 2026 + +## Delivered boundary + +Runtime source **0ca1584d835cbc0f329fa43e4c0ae95b9e13dcfe**, PR3, canonical CI17/API986/job999 passed. Artifact6630 was independently checked on the three deployment hosts: all18 members matched; the five deployment/helper scripts and public-signature ABI fixture matched committed source. The release manifest SHA256 is `0d1b185605cd81a5c5dda9afd5f3574d02621e707fc3aea939bc71c0670987a1`. Full member hashes are in [artifact-members.json](evidence/gui-0ca1584/artifact-members.json). + +This record documents installation and server startup, not connected-client acceptance. It is documentation only: do not deploy artifacts produced from this documentation commit or replace the installed runtime source0ca1584. + +The incoming first-party set was DuneMenus2.0.1, DunerealmsGUI1.1.32 and DuneNPC1.0.0, plus DuneLobby1.1.0 on lobby only. All working JARVIS, Essentials, Core and Terrain binaries remained installed. The guarded inventory mode verified actual retained backend hashes,69 required frontend ABI descriptors, and current file metadata before installation. No ChestCommands was introduced. The DuneNPC backend remains present. + +## Authorised host operations and recovery + +The coordinating chat alone performed host operations. This plugin chat used local source, Git, PRs and CI; it did not use SSH. Actual existing roots were verified as `/opt/dunerealms/lobby` and `/opt/dunerealms/servers/{planet}`, with existing `dune-*.service` units and dune UID988/GID988 ownership. No network bootstrap installer, world regeneration or schema workaround was used. + +The existing MCGUI0.8.6 prerequisite was privately staged on both game hosts with SHA256 `69a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300`, root-owned0600. Staging was separate from installation. The public release contains no vendor runtime JAR. The built installer subsequently copied the verified prerequisite with service-readable ownership; the private staged source stayed private. Existing Paper26.2-135/Java25 was retained. + +The first e19 lobby canary exposed PostgreSQL UUID DDL in rebuilt Essentials against actual MySQL. Wider rollout stopped; no planets had been installed. The coordinator manually restored checksum-verified original files from the e19 receipt, then verified original Paper startup. Original owner metadata had not been recorded by that legacy receipt: recovered original JARs were explicitly restored to independently verified dune988:988/mode0644, not claimed as metadata recovered from the receipt. See [the recovery record](CANARY-RECOVERY-20261129.md). The final guarded release excluded rebuilt backend modules and added tested explicit receipt rollback for application-level readiness failure. The rebuilt Essentials MySQL defect remains unresolved. + +Both immutable menu packs were published through their exact CI-built publisher, retaining all earlier download routes. The final URL is `https://www.dunerealms.com/downloads/DuneRealms-Menu-0ca1584d835cbc0f329fa43e4c0ae95b9e13dcfe.zip`; SHA256 `fa8d3abecd44984572146fc6e600b8893a33a5f0d0819154285f3f8fa20603d5`, SHA1 `c0775e6a629d83b651ba50e6aa923c1437ec5abe`,1753375bytes. It contains116 MCGUI transport entries plus75 namespaced additions and389 item-card mappings; no vanilla world-texture replacements. Built publication used the existing public download store and included nginx snippet. Final snippet backup: `/etc/nginx/snippets/dunerealms-gui-download-v3.conf.before-menu-20261129T025220.729925Z`; previous SHA256 `878e1060fd1cf0160424852025f26b68f04ce39996a0157dbedb45b5308fceb6`, final `d62d091ecb3c1c5bebf13af3f751081b88b87a9b0c32138c249227bad31e132e`. Nginx validation/reload and actual public pack bytes were verified. Existing original worldpack routes stayed present. + +## Installed and started + +Times below are Europe/Brussels on29 November2026. UTC receipt timestamps remain unchanged in paths. + +| Backend | Paper Done | Startup duration | Receipt directory under `/opt/dunerealms/backups/gui-0ca1584/` | +| --- | --- | --- | --- | +| lobby |03:54:25|84.001s|`20261129T025254.995615Z/lobby/`| +| arrakis |03:57:48|23.664s|`20261129T025721.237213Z/arrakis/`| +| caladan |04:00:25|43.373s|`20261129T025938.268932Z/caladan/`| +| giedi_prime |04:00:25|41.597s|`20261129T025938.268932Z/giedi_prime/`| +| kaitain |04:00:31|44.778s|`20261129T025938.268932Z/kaitain/`| +| sigma_draconis_iv |04:00:32|42.794s|`20261129T025938.268932Z/sigma_draconis_iv/`| + +Each directory contains receipt.json. All six services became active, reached Paper Done and enabled MCGUI0.8.6, DunerealmsGUI1.1.32 and DuneMenus2.0.1. Incoming JAR/configuration hashes and retained backend hashes plus UID/GID/mode were independently checked after startup. Planet Terrain hashes remained unchanged. [Planet post-start evidence](evidence/gui-0ca1584/planet-poststart-verified.json) records each receipt and canonical property hash. + +All planet server.properties semantic fields, including resource-pack URL/SHA1/required, matched independently captured pre-start values. Lobby original pack fields matched the independent28November manifest. Paper rewrote its generated comment timestamp; full properties-file byte equality is explicitly NOT claimed. Neither built installer nor publisher writes server.properties. All six original public world ZIPs matched28November SHA1/SHA256/size; see [worldpack evidence](evidence/gui-0ca1584/worldpack-store-verification.json). + +No new error/exception signatures were identified against each planet's prior28November startup. Existing ImageFrame8517 warnings and Kaitain Typewriter errors were confirmed in pre-GUI archives. Lobby native-food projection warnings also predate this rollout. These baseline defects are not fixed by installing the GUI. + +Independent final Minecraft protocol status checks also passed on all six backends: each responded as Paper26.2 with zero players online. See [protocol-health evidence](evidence/gui-0ca1584/minecraft-status-verified.json). This establishes server reachability, not player interaction. The coordinator also rechecked the existing website health and corrected custom-item metadata after the deployment operations; those remain separate website scope. + +## Checks and remaining acceptance + +Canonical CI built/tested all eight source modules and passed34 Python checks:5 ABI,6 rollback,10 installer,9 config/publisher and4 resource-pack tests. The local final-source real MCGUI renderer passed15 menu families/152 direct action hitboxes, including long labels and scrolling. This is renderer evidence, not proof of a connected Minecraft client. + +Connected-client pack acceptance, NPC click-to-menu behavior, visual comparison with the supplied ZIP and live action/callback interaction remain to be checked in-game. No exact preview-artwork parity claim is made. Citizens conversion remains deferred because no approved compatible vendor runtime was available. Broader gameplay/backend changes, including rebuilt Essentials MySQL compatibility, are deferred; the installed original backends remain authoritative. No additional features or economy/data migrations are part of this record. diff --git a/DuneMenus/docs/INTEGRATION.md b/DuneMenus/docs/INTEGRATION.md new file mode 100644 index 00000000..caf8237b --- /dev/null +++ b/DuneMenus/docs/INTEGRATION.md @@ -0,0 +1,38 @@ +# GUI replacement acceptance and callback map + +| Entry | New presentation | Existing authority | +| --- | --- | --- | +| Codex / drgui | HubMenu / SuppliedDocument | Existing codex item and command ownership | +| Travel | TravelMenu constellation | JarvisTranslator Guild quotes, House key/version, dispatch | +| Exchange | ExchangeMenu and native ServiceMenu | Central listing ID/version/price, receipt references, physical handoff | +| Clan / company | OrganisationChoiceMenu, ClanMenu, CompanyMenu | Exact membership ID and authority revision | +| Quest NPCs / quartermaster | ServiceMenu from original NPC callbacks | Original quest service, supply permit, reward claim | +| Missions / Mentat | MissionsMenu / MentatMenu | Existing central journal and native turn-in contacts | +| Spice | SpiceMenu and original NPC ServiceMenu | Existing Guild/Smuggler authority and settlement | +| War / deed | WarMenu and original service callbacks | Current roster/draft/objective permission checks | +| House / politics | HouseMenu / PoliticsMenu | Central allegiance version and decision funding authority | +| Equipment | EquipmentMenu | Authoritative refit quote and physical application | +| Bank / ATM | BankMenu / AtmMenu / TransferMenu | Existing Rihla APIs, denominations, transfer and redemption references | +| Administration, sellall, scoreboard | Existing handlers | Unchanged backend handlers | + +The new Java renderer consumes the ZIP menu definitions and direct slot callbacks; it does not use old MenuDocument selected-card pages. Existing native service models are wrapped without replacing their callback implementations. Shared NativeMenus inventory entry points (including DuneNPC travel) also enter the replacement. Estate services retain the original claim/Home Block/deployment screens; website-only organisation functions link to their existing management pages. No new confirmation intermediary is added. + +Local verification: 140 Java sources compile for release21 against cached Paper1.21.8 dependencies; 14 focused tests pass. Four resource-pack tests pass and validate item-card fonts/textures in the actual ZIP. Browser render fixtures are local design evidence only. Actual MCGUI0.8.6 rendering additionally passed15 menu families and152 direct action hitboxes, including long-page scrolling; runtime SHA-256 is pinned in the optional verifyMenuRenderer build task. Full exact-head CI and live NPC/function checks remain required before declaring deployment complete. + +Known visual work remains: the supplied preview's bespoke illustrations are reference artwork, while the dedicated canvas currently implements the gold/emerald frame, themed scenes, direct card grid, travel constellation and journal/council/bank layouts. Do not describe this as pixel-identical preview parity or a live install. + + +Reproduce actual renderer verification through the build (the JAR stays private): + +```sh +gradle -p DuneMenus verifyMenuRenderer -PmcguiRuntime=/verified/private/MCGUI-0.8.6.jar +``` + +The example path is a parameter, not a deployment location. This task checks the reviewed input hash and produces15 engine-rendered PNGs. Fixture entries are synthetic test data and never contact a game account or execute a purchase. + +Local Java21 Gradle verification completed successfully using cached dependencies (`--offline`) after the local JDK trust store rejected online Maven TLS. `test jar verifyMenuRenderer` built the frontend and JARVIS dependency, ran their tests and rendered all15 families/152 hitboxes. Canonical CI uses Gradle9.2.1 and is reported separately by exact commit. + +The build also ships the manifest-driven fleet installer and its tested rollback path. See FLEET-INSTALL.md. This is deployable tooling, not evidence that any host was changed. + + +The final pack acceptance supersedes intermediate gameplay ZIPs: use only the built DuneRealms-Menu-.zip composite and MENU-PACK-ROLLOUT.md. Legacy world/artwork auto-offers are removed; the actual engine's external-mode readiness assumption is supplemented by an exact-pack SUCCESSFULLY_LOADED guard. Existing active hosts have no GUI runtimes installed yet; incoming first-party services and a hash-pinned private MCGUI prerequisite restore them. Source/backend implementation preservation does not claim those services were already installed live. diff --git a/DuneMenus/docs/MENU-PACK-ROLLOUT.md b/DuneMenus/docs/MENU-PACK-ROLLOUT.md new file mode 100644 index 00000000..210e8f80 --- /dev/null +++ b/DuneMenus/docs/MENU-PACK-ROLLOUT.md @@ -0,0 +1,43 @@ +# Build-owned central resource-pack delivery + +## Current unified contract + +The current canonical release is one complete server-owned pack for all six backends. Publish `DuneRealms-Resources-.zip` through the CI-shipped publisher to its immutable downloads URL, verify its actual public bytes against the same CI manifest, then use that artifact's installer and explicit verified inventory. Do not substitute an overlay ZIP or an expiring artifact URL. + +The pack contains the retained card-art fonts/atlases, original required custom assets, supplied custom-item overlay and pinned MCGUI transport. Dependency closure includes font references. It replaces the old per-world pack configuration; it does not add a second client pack. The fixed server UUID is `c24c7cf5-a292-539d-971f-a96d8b838162`. Ordinary vanilla block artwork has not been comprehensively redesigned; that is a separate work package. + +Inventory `menuPack.url` must match the exact built Resources URL. Select only the reviewed incoming JARs; the a3dee6d correction selects DunerealmsGUI.jar1.1.35 alone and retains every other installed JAR. The existing gui-preserve-backends identity, checksum and ABI guards still apply. + +The installer writes only owned MCGUI/config.yml, DunerealmsGUI/menu-pack.yml and these four server.properties keys: resource-pack, resource-pack-sha1, resource-pack-id, require-resource-pack. Receipt3 records originals and metadata and restores them with JAR/config rollback. It preserves all other semantic properties and refuses rollback over unknown later changes. Paper-generated comment timestamps may change at restart. Both publication and installation use committed built tools; the coordinator retains exclusive host invocation. + +MCGUI remains external/blank-public-URL with telemetry disabled; the GUI does not offer another pack. Readiness requires the validated server pin and actual SUCCESSFULLY_LOADED status, plus MCGUI.hasPack. Paper26.2 can finish loading during configuration without a Bukkit play-phase player event. GUI1.1.35 reads the recorded connection status at join/startup and still handles later matching pending/failure/unload events. A foreign UUID cannot grant readiness. See SERVER-PACK-READINESS.md for evidence and tests. + +```json +"menuPack": {"url": "https://www.dunerealms.com/downloads/DuneRealms-Resources-.zip"} +``` + +The following section records the earlier stacked release, not the current central-pack contract. Its statements about untouched server.properties and separate menu offers apply only to that historical mode. + +## Historical stacked overlay contract (0ca release) + +The existing MCGUI0.8.6 runtime calls Player.addResourcePack with UUID.nameUUIDFromBytes("uiengine:pack"). It stacks its pack rather than clearing the server world pack. In mode external with blank public-url, offers() is false and mergedElsewhere() is true. Its has(player) method can assume readiness in that mode; our sender therefore additionally requires an actual SUCCESSFULLY_LOADED event for the exact MCGUI pack ID before opening any new menu or enabling item-card assets. + +The canonical build preserves all116 entries from the pinned generated MCGUI client transport and adds exactly75 approved assets/dunerealms entries, including389 card mappings. It excludes every old baseline/world-artwork entry and all vanilla block/entity replacements. The client pack explicitly includes26.2 shaders/formats88โ€“96. The private vendor plugin JAR is not in public source or CI artifacts. + +DunerealmsGUI no longer starts legacy PlanetTexturePacks/EcologyArtwork delivery and no longer offers NetworkArtwork-v6. It offers only the separately stacked built menu overlay. Server-owned per-world resource-pack settings and bytes remain untouched. The MCGUI runtime is configured external/blank URL with telemetry, update-check and web imports disabled; no vendor upload or built-in pack server is used. + +Publish through the CI-shipped publish-plugin-menu.py, first read-only, then --apply, supplying --artifacts, --expected-source, --store and --snippet. The verified web hosting contract is host91.107.196.242, store /var/lib/dunerealms-public-downloads, included snippet /etc/nginx/snippets/dunerealms-gui-download-v3.conf. The built publisher copies only DuneRealms-Menu-.zip, refuses conflicting immutable bytes, preserves all existing routes, backs up the snippet, appends one exact idempotent location, runs nginx -t before reload, and restores config on test/reload failure. The permanent URL is https://www.dunerealms.com/downloads/DuneRealms-Menu-.zip. Never use an expiring artifact link as client configuration. + +The built fleet installer requires inventory menuPack.url equal to that permanent URL. It verifies the actual public bytes against the CI menu ZIP/manifest before stopping anything. For selected DuneMenus targets it writes only owned MCGUI/config.yml and DunerealmsGUI/menu-pack.yml, records/writes their hashes, backs up existing owned config bytes, and restores them together with JARs on failure. Unexpected unmanaged config is refused. New data directories and JAR/config files inherit plugin-directory ownership so root-staged0600 runtime bytes can be read/run by the game service without changing the private source file. No server.properties write exists in either tool. + +## Verified staging fact โ€” not installation + +The authorised coordinator staged the existing reviewed MCGUI runtime privately on both verified game hosts at /opt/dunerealms/rollouts/private/MCGUI-0.8.6-69a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300.jar, root-owned0600. SHA25669a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300 was rechecked after transfer. That was prerequisite staging only: no plugin installation, service restart or GUI delivery was performed at that point. No credential/key path is part of this handover. + +Current fleet Paper is26.2-135/API26.2.build.135, not the historical compile API1.21.8. Existing isolated logs establish MCGUI0.8.6 startup on matchingPaper. Actual new renderer checks cover15 menu families/152 action hitboxes; connected-client transport, NPC interactions and current world textures still require rollout checks. Citizens is absent and its compatible runtime remains pending official vendor access; do not claim Citizens conversion complete. + +Inventory extension: +```json +"menuPack": {"url": "https://www.dunerealms.com/downloads/DuneRealms-Menu-.zip"} +``` +Replace the placeholder with the actual built source. The coordinator retains exclusive host invocation; all persistent code/config publication goes through these committed build tools. diff --git a/DuneMenus/docs/MENU-POLISH-AND-EXCHANGE-PARITY.md b/DuneMenus/docs/MENU-POLISH-AND-EXCHANGE-PARITY.md new file mode 100644 index 00000000..58e9df33 --- /dev/null +++ b/DuneMenus/docs/MENU-POLISH-AND-EXCHANGE-PARITY.md @@ -0,0 +1,20 @@ +# Menu polish and Exchange command parity + +Objective: preserve the accepted fast full-screen menu design while containing text, improving artwork and making the public Exchange command use the already working native Exchange flow. + +## Scope + +- DuneMenus 2.0.2: bounded compact summaries and titles; price/stock/seller stay visible in summaries and an optional Details control opens one selected full-lore panel above the grid without executing the purchase, without adding a confirmation action. Private-use inventory glyphs and legacy formatting codes are removed from display text. House-adviser wording avoids assigning every adviser the Mentat profession. Council actions use a balanced grid; the Your House arrow is an ordinary action rather than a paging control. +- Local illustrated website logo, proportionally contained and centred in the header brand area. Item icons and semantic fallbacks are horizontally centred in small framed wells. Canonical PNG SHA256 267fe0d0b5adb4f2fb657d1d6827d030e7f837c94335d0a3643210b908f47931. Menu item icons resolve the actual ItemStack item_model to an existing central-pack flat texture. No quality/mark is inferred from a name. Ordinary native blocks with a verified same-ID block texture use that flat surface preview, not a native 3D render. Unsupported dynamic/complex models retain a semantic fallback; this is not a general 3D item renderer. +- Artwork is packaged from committed central inputs and unpacked at plugin startup. Model/image lookups are cached. There are no remote artwork requests on menu opening. +- GUI 1.1.36 routes /exchange, namespaced aliases, /drgui exchange and every DuneMenus Exchange entry (including Hub and Company) to the existing native ExchangeMenus.open path before the supplied-command interceptor. That is the same service used by the working GUI button and remains displayed by the fast ServiceMenu renderer. + +No economy, bank, purchase reference, retry, payment, delivery, JARVIS, Core, Ess, quest or raider implementation changes. Existing native purchase selection and settlement behaviour remains unchanged. This change does not clear an uncertain earlier purchase or replay a transaction. + +## Verification and release + +Local DuneMenus and GUI tests pass. Pinned real MCGUI 0.8.6 renderer checks fifteen menu families and 152 original action hitboxes, including 28 long Exchange listings; text-bound checks include long titles/descriptions and full scroll pages. A separate actual-image fixture renders the central legendary axe texture with the illustrated logo and cleaned lore. These are offline fixtures, not real purchase or connected-client acceptance. + +Canonical exact-head CI, manifest review and guarded frontend-only canary are still required. Select only DuneMenus and DunerealmsGUI incoming JARs; retain all working backend binaries and current resource-pack pin. Verify actual command/GUI parity and representative custom item icons in-game, without speculative payment tests. + +Client-side coordinate/minimap overlays are outside this layout. No claim is made that server HTML can suppress a client mod HUD. diff --git a/DuneMenus/docs/SERVER-PACK-READINESS.md b/DuneMenus/docs/SERVER-PACK-READINESS.md new file mode 100644 index 00000000..1c30ecc8 --- /dev/null +++ b/DuneMenus/docs/SERVER-PACK-READINESS.md @@ -0,0 +1,13 @@ +# Server-owned pack readiness correction + +Objective: allow the existing menu presentation after the required, pinned central pack has genuinely loaded in Paper configuration phase. + +Scope: GUI readiness only. No artwork, JARVIS, economy, permissions, gameplay or second pack offer. Existing server configuration must pass the exact URL/hash/UUID pin validation before configuration status can seed readiness. + +Evidence: the owner's client loaded central UUID before lobby join, then the menu reported artwork unavailable. On exact Paper 26.2-135, ServerConfigurationPacketListenerImpl.handleResourcePackResponse records Connection.resourcePackStatus but emits no Bukkit PlayerResourcePackStatusEvent. CraftPlayer.getResourcePackStatus reads that connection status after join. The previous GUI listened only for the later play-phase event. + +Implementation: read actual connection status at join and for already-online players during adapter startup; only server-owned SUCCESSFULLY_LOADED seeds readiness. Later matching pending/failure/unload statuses revoke readiness. Other UUIDs never grant readiness. Quit clears all state; the next backend must establish its own connection status. MCGUI.hasPack remains required by menu presentation. Stacked legacy mode continues to require its own matching event. + +Acceptance/tests: configuration-only success without a player event; all non-success/null statuses blocked; foreign UUID isolation; legacy overlay isolation; later failure/pending invalidation; reconnect/backend transfer lifecycle. Run full GUI tests/build and canonical plugin/pack CI at exact commit. Coordinator alone deploys the built artifact, then verifies server readiness log and owner menu rendering. Local tests are not connected-client proof. + +Runtime evidence inspected read-only: existing isolated Paper26.2-135 JAR and API. No live host changes made from this chat. Current lobby/Arrakis77cf canaries retained; other four on hold. This correction ships GUI1.1.35; pack artwork remains byte-identical to77cf, under the new immutable source filename. diff --git a/DuneMenus/docs/VANILLA-ARTWORK-DEPLOYMENT-20261129.md b/DuneMenus/docs/VANILLA-ARTWORK-DEPLOYMENT-20261129.md new file mode 100644 index 00000000..0053004c --- /dev/null +++ b/DuneMenus/docs/VANILLA-ARTWORK-DEPLOYMENT-20261129.md @@ -0,0 +1,44 @@ +# Vanilla artwork deployment โ€” 29 November 2026 + +## Objective and boundary + +Record the verified delivery of the owner-approved familiar-shape Dune materials, with the stronger Dune II-inspired ore and metal treatment. This change records evidence only. Do not deploy artifacts built from this documentation commit. + +The installed artwork source is `79326a2531774dbf57383e4fed1e447dd52b4066` (PR9, canonical CI24/API1012/job1025, artifact6990). Runtime binaries remain identical to a3/GUI1.1.35. The existing guarded installer requires its matching GUI selection, so it reinstalled the exact same GUI bytes while updating the pack properties and owned configuration. No backend binary, economy, permission, world-generation or raider change was installed. + +## Exact artifact and publication + +- Downloaded wrapper: 44,270,634 bytes; SHA256 `a88a8f19ed25a77504c4dd7a08a0fb995707f69e69bdfbc86ab7db8084296f9d`. +- All 19 checksum targets passed. All four release JARs and six deployment helpers matched the previous a3 artifact byte for byte. +- Pack: `DuneRealms-Resources-79326a2531774dbf57383e4fed1e447dd52b4066.zip`; 21,105,132 bytes, 3,570 entries. +- SHA1 `77e78780bcdb14c962c70fc9a3501c35df8bb80a`; SHA256 `61931cc463933706fb391ce8aaff78138ff1377241e062aac000aa144242a10d`. +- Existing shared server-owned UUID: `c24c7cf5-a292-539d-971f-a96d8b838162`. +- Immutable public URL: https://www.dunerealms.com/downloads/DuneRealms-Resources-79326a2531774dbf57383e4fed1e447dd52b4066.zip . The built publisher and each read-only installation plan verified the public bytes against the manifest. +- Built publisher ran under the shared promotion lock, validated nginx and retained the snippet backup `/etc/nginx/snippets/dunerealms-gui-download-v3.conf.before-menu-20261129T095935.714648Z`. + +The final source contains 2,289 artwork PNGs, preserving seven protected spice textures, ordinary silhouettes, native trim templates and existing custom/card/transport assets. Only the declared metal icons and ores receive the stronger futuristic redesign. No broad entity, vehicle or worn-armour reskin is included. Independent coordinator checks passed all 12 artwork and six complete-pack/dependency tests; canonical CI also tested and built the eight plugin modules and rollout checks. + +## Installation and rollback evidence + +Every verified service was stopped before installation, backed up through the built receipt3 installer and restarted. All six reached Paper startup completion with GUI1.1.35 enabled. Before/after snapshots show **zero changes to every installed JAR's hash, UID, GID and mode**, and preservation of all non-pack semantic server properties. Paper's generated comment timestamp is not claimed byte-identical. + +Receipts under `/opt/dunerealms/backups/vanilla-79326a/`: + +| Server | Receipt | +| --- | --- | +| lobby | `20261129T100042.351627Z/lobby/receipt.json` | +| arrakis | `20261129T100453.757119Z/arrakis/receipt.json` | +| caladan | `20261129T100556.307189Z/caladan/receipt.json` | +| giedi_prime | `20261129T100556.307189Z/giedi_prime/receipt.json` | +| kaitain | `20261129T100556.307189Z/kaitain/receipt.json` | +| sigma_draconis_iv | `20261129T100556.307189Z/sigma_draconis_iv/receipt.json` | + +The previous a3 immutable pack, configuration backups and receipt rollback tooling remain available. No rollback of this release was required. See [the sanitized evidence](evidence/vanilla-79326a/vanilla-79326a-summary.json) and [the receipt3 contract](FLEET-INSTALL.md). + +## Connected-client acceptance and limits + +The lobby recorded the central pack UUID loaded at 10:03:28 UTC (11:03:28 Europe/Brussels). After reconnecting, the owner explicitly answered **โ€œArtwork and menu work.โ€** The screenshot and later feedback also confirm the menu remains responsive. This is one connected-client lobby acceptance, not proof of every asset, callback or world. + +Arrakis, Caladan, Giedi Prime and Sigma startup captures contained no ERROR lines. Lobby retained the two known JARVIS food/brewing ServerLoad failures. Kaitain's 25 Typewriter missing-entry signatures matched the previous a3 startup exactly; those issues were not repaired or introduced by this artwork release. + +Subsequent owner reports identified separate GUI work: role labels and text clipping, spacing, the website logo and richer icons/item cards, and a difference between `/exchange` and the working GUI Exchange route. These remain separate implementation/acceptance tasks; this report does not claim them fixed. The owner accepted this GUI foundation and its speed. The supplied Claude raider ZIP is the final base design, with implementation/testing owned by the plugin agent; no raider source or gameplay change was part of this release. diff --git a/DuneMenus/docs/VANILLA-MATERIAL-PACK.md b/DuneMenus/docs/VANILLA-MATERIAL-PACK.md new file mode 100644 index 00000000..3b09450d --- /dev/null +++ b/DuneMenus/docs/VANILLA-MATERIAL-PACK.md @@ -0,0 +1,20 @@ +# Vanilla Dune material pack execution brief + +Objective: texture all ordinary vanilla items and blocks with familiar shapes and Dune materials. Use Dune II (1992) industrial inspiration and a stronger futuristic exception for ores and ingots. + +## Bounded scope + +Artwork, reproducible generator, coverage/PNG validation, preview tooling and central-pack assembly only. No Java, backend, economy, quest, raider, permission, recipe or world-generation changes. No worn-armour or broad entity/vehicle reskin. Keep one central pack and all installed runtime JAR bytes unchanged. + +## Execution and acceptance + +1. Pin official 26.3 and 26.2 catalogue inputs; include two verified older item paths. +2. Generate 2,289 PNGs while preserving seven existing spice textures. Preserve ordinary silhouettes, neutral tint masks, dye distinctions, animation metadata and native trim templates. Only seven metal icons and eighteen ore textures receive futuristic designs. +3. Validate exact coverage, PNG CRCs, alpha masks, hashes and native model/atlas references. Preserve all existing custom artwork, fonts and transport bytes. +4. Review offline contact sheets and run canonical plugin/pack CI on the exact committed head. Verify all four release JAR hashes against the installed baseline; artwork does not authorise backend replacement. +5. Coordinator publishes the immutable tested pack and uses receipt-backed pack/configuration-only installation. Preserve runtime bytes and non-pack properties, retain rollback. +6. Verify loaded pack UUID and representative blocks, ores, ingots, equipment, trims and animations in a connected client before fleet expansion. Record actual results separately from offline tests. + +## Status + +Local validation has passed; exact-head canonical CI and live client acceptance are pending. Raider gameplay and native quest work remain separate. See the artwork README and machine-readable manifests for detailed scope and provenance. diff --git a/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-arrakis-verification.json b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-arrakis-verification.json new file mode 100644 index 00000000..4cbb5145 --- /dev/null +++ b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-arrakis-verification.json @@ -0,0 +1,12 @@ +{ + "server": "arrakis", + "sourceCommit": "a3dee6dfd8289b8c6d5c00b70b798661e96a62b9", + "changedJars": [ + "DunerealmsGUI.jar" + ], + "nonPackPropertiesPreserved": true, + "GUIenabled": true, + "startupDone": true, + "serviceActive": true, + "errors": [] +} \ No newline at end of file diff --git a/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-caladan-verification.json b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-caladan-verification.json new file mode 100644 index 00000000..b5d18d23 --- /dev/null +++ b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-caladan-verification.json @@ -0,0 +1,12 @@ +{ + "server": "caladan", + "sourceCommit": "a3dee6dfd8289b8c6d5c00b70b798661e96a62b9", + "changedJars": [ + "DunerealmsGUI.jar" + ], + "nonPackPropertiesPreserved": true, + "GUIenabled": true, + "startupDone": true, + "serviceActive": true, + "errors": [] +} \ No newline at end of file diff --git a/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-giedi_prime-verification.json b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-giedi_prime-verification.json new file mode 100644 index 00000000..2eb720bb --- /dev/null +++ b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-giedi_prime-verification.json @@ -0,0 +1,12 @@ +{ + "server": "giedi_prime", + "sourceCommit": "a3dee6dfd8289b8c6d5c00b70b798661e96a62b9", + "changedJars": [ + "DunerealmsGUI.jar" + ], + "nonPackPropertiesPreserved": true, + "GUIenabled": true, + "startupDone": true, + "serviceActive": true, + "errors": [] +} \ No newline at end of file diff --git a/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-kaitain-verification.json b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-kaitain-verification.json new file mode 100644 index 00000000..c52c7636 --- /dev/null +++ b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-kaitain-verification.json @@ -0,0 +1,44 @@ +{ + "server": "kaitain", + "sourceCommit": "a3dee6dfd8289b8c6d5c00b70b798661e96a62b9", + "changedJars": [ + "DunerealmsGUI.jar" + ], + "nonPackPropertiesPreserved": true, + "GUIenabled": true, + "startupDone": true, + "serviceActive": true, + "errors": [ + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_command' on page 'DuneRealms Imperial Navigator' with type 'custom_command' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_archive_command' on page 'DuneRealms Imperial Navigator' with type 'custom_command' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_archive' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_speaker' on page 'DuneRealms Imperial Navigator' with type 'simple_speaker' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_home' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_travel' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_arrakis_confirm' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_arrakis_go' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_kaitain_confirm' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_kaitain_go' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_giedi_confirm' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_giedi_go' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_contracts' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_contract_list' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_spicejobs' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_job_list' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_item_notice' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_item_open' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_support' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_links' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_support_link' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_appeal_link' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_account_link' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_clans_link' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension.", + "[08:11:06] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_manual_link' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension." + ], + "baselineErrorComparison": { + "archive": "2026-11-29-2.log.gz", + "currentTypewriterSignatures": 25, + "matchingPriorSignatures": 25, + "allPresentBeforeRollout": true + } +} diff --git a/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-lobby-verification.json b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-lobby-verification.json new file mode 100644 index 00000000..ac0951d7 --- /dev/null +++ b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-lobby-verification.json @@ -0,0 +1,26 @@ +{ + "sourceCommit": "a3dee6dfd8289b8c6d5c00b70b798661e96a62b9", + "server": "lobby", + "changedJars": [ + "DunerealmsGUI.jar" + ], + "nonPackPropertiesPreserved": true, + "packProperties": { + "resource-pack": "https://www.dunerealms.com/downloads/DuneRealms-Resources-a3dee6dfd8289b8c6d5c00b70b798661e96a62b9.zip", + "resource-pack-sha1": "c3aac94fc0265702aae4e4a6d03af3d4b3ae5ce3", + "resource-pack-id": "c24c7cf5-a292-539d-971f-a96d8b838162", + "require-resource-pack": "true" + }, + "startupDone": true, + "GUI": "1.1.35", + "readinessLogs": [ + "08:09:08 UTC: Central resource pack loaded; UUID c24c7cf5-a292-539d-971f-a96d8b838162" + ], + "ownerConfirmedMenuOpens": true, + "knownBaselineErrors": { + "JarvisTranslatorServerLoad": 2, + "food": "missing chukka_cooked_meat", + "brewing": "missing water_of_life", + "previouslyVerified": true + } +} diff --git a/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-sigma_draconis_iv-verification.json b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-sigma_draconis_iv-verification.json new file mode 100644 index 00000000..fa8747e2 --- /dev/null +++ b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-sigma_draconis_iv-verification.json @@ -0,0 +1,12 @@ +{ + "server": "sigma_draconis_iv", + "sourceCommit": "a3dee6dfd8289b8c6d5c00b70b798661e96a62b9", + "changedJars": [ + "DunerealmsGUI.jar" + ], + "nonPackPropertiesPreserved": true, + "GUIenabled": true, + "startupDone": true, + "serviceActive": true, + "errors": [] +} \ No newline at end of file diff --git a/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-summary.json b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-summary.json new file mode 100644 index 00000000..635b864c --- /dev/null +++ b/DuneMenus/docs/evidence/central-a3dee6d/central-a3dee6d-summary.json @@ -0,0 +1,23 @@ +{ + "sourceCommit": "a3dee6dfd8289b8c6d5c00b70b798661e96a62b9", + "canonicalCI": 22, + "artifact": 6915, + "GUI": "1.1.35", + "packSHA256": "8553a730579fd5f594a21a9d213d065a2d4ef89d4ad272ea5230355e447dbc6e", + "publishedURL": "https://www.dunerealms.com/downloads/DuneRealms-Resources-a3dee6dfd8289b8c6d5c00b70b798661e96a62b9.zip", + "publisherBackup": "/etc/nginx/snippets/dunerealms-gui-download-v3.conf.before-menu-20261129T080321.191253Z", + "receipts": { + "lobby": "/opt/dunerealms/backups/central-a3dee6d/20261129T080452.478197Z/lobby/receipt.json", + "arrakis": "/opt/dunerealms/backups/central-a3dee6d/20261129T080936.878496Z/arrakis/receipt.json", + "remaining4": "/opt/dunerealms/backups/central-a3dee6d/20261129T081013.850457Z/{server}/receipt.json" + }, + "all6StartupDone": true, + "all6OnlyGUIJarChanged": true, + "all6OtherJarsMetadataAndNonPackPropertiesPreserved": true, + "connectedClientAcceptance": "Owner confirmed lobby menu opens; matching central UUID loaded log at08:09:08UTC", + "limitations": [ + "No proof of every world/client/callback or all equipment", + "Existing lobby food/brewing errors and25 Kaitain Typewriter entry errors remain; verified in prior logs", + "No quest/artwork drafts deployed" + ] +} diff --git a/DuneMenus/docs/evidence/gui-0ca1584/artifact-members.json b/DuneMenus/docs/evidence/gui-0ca1584/artifact-members.json new file mode 100644 index 00000000..954259fa --- /dev/null +++ b/DuneMenus/docs/evidence/gui-0ca1584/artifact-members.json @@ -0,0 +1,20 @@ +{ + "CANARY-RECOVERY-20261129.md": "0e1cfbd1d699ddba7e3c9b85833017ad3877bc98632d176281b3b20df3eabf30", + "DuneMenus.jar": "9665f47c7e21ef1a291ac0de4159e88f829677b51583b39366ab391d3bb9d0ac", + "DuneRealms-Lobby.jar": "6f5c4c1514579c60ee74efba9ac2a91dc3dbcff1db3d0e5ca57cde5f4a1d85f0", + "DuneRealms-Menu-0ca1584d835cbc0f329fa43e4c0ae95b9e13dcfe.manifest.json": "4a7112e84885ea6ee41bdece05130c98d4ca059afcfd08ce8b3f191d2b8259eb", + "DuneRealms-Menu-0ca1584d835cbc0f329fa43e4c0ae95b9e13dcfe.zip": "fa8d3abecd44984572146fc6e600b8893a33a5f0d0819154285f3f8fa20603d5", + "DuneRealms-NPC.jar": "1b898cc5e120beb7c11bcd50a5e036c3993162925902a029b4361fb321caf09f", + "DunerealmsGUI.jar": "83c56f9326d4799db87261c79fd2655899fce7bfde0fef140fd2b7d0643dc9c8", + "FLEET-INSTALL.md": "de6dcb1b3215db41e0478a1b26fa4088e198b8c060d12c3aca79fdca2c2a95dc", + "MENU-PACK-ROLLOUT.md": "a94ac5b7e1efa528b051c727b4ba69b35b8de7bedd47cd14382d592a98097534", + "SHA256SUMS": "ac772909366b4de02b600a460de7ef92c3f528c00543fb953e860740f1afcea5", + "SOURCE_COMMIT": "347de35afad817ef35fa6baf7eccc90e3d95a08b08f65b654da51fe870704314", + "install-plugin-fleet.py": "da2254690ba86943c6a988fdd1dabf45b1ed8bb60083d7ef770389ae0083c702", + "plugin_backend_abi.py": "28106cb496a7e75991195e623f8f4e56d83817abffa176eb9bab6be0bd39c222", + "plugin_fleet_rollback.py": "c9f700ddbefbc45aa1563651d07fa424c7459c70b9bb21a8237964a48bc025d9", + "plugin_menu_pack.py": "5c6175f8ac87337d1b1b0c824e98aa1f3207f7a58cb6b8cc1efa317bdab2fb21", + "preserved-backend-abi.json": "825c3dae3a424f05e78e89dbdeb0bb4208c33ab5ac618ab0b6489af01df1e47f", + "publish-plugin-menu.py": "cc724b9e81a7965758060d7d12a7bd2b71cd3052cbbda0f2ab81f9cde7cf5898", + "release-manifest.json": "0d1b185605cd81a5c5dda9afd5f3574d02621e707fc3aea939bc71c0670987a1" +} diff --git a/DuneMenus/docs/evidence/gui-0ca1584/minecraft-status-verified.json b/DuneMenus/docs/evidence/gui-0ca1584/minecraft-status-verified.json new file mode 100644 index 00000000..0d3fa6e8 --- /dev/null +++ b/DuneMenus/docs/evidence/gui-0ca1584/minecraft-status-verified.json @@ -0,0 +1,38 @@ +[ + { + "server": "arrakis", + "responding": true, + "version": "Paper 26.2", + "online": 0 + }, + { + "server": "caladan", + "responding": true, + "version": "Paper 26.2", + "online": 0 + }, + { + "server": "giedi_prime", + "responding": true, + "version": "Paper 26.2", + "online": 0 + }, + { + "server": "kaitain", + "responding": true, + "version": "Paper 26.2", + "online": 0 + }, + { + "server": "sigma_draconis_iv", + "responding": true, + "version": "Paper 26.2", + "online": 0 + }, + { + "server": "lobby", + "responding": true, + "version": "Paper 26.2", + "online": 0 + } +] diff --git a/DuneMenus/docs/evidence/gui-0ca1584/planet-poststart-verified.json b/DuneMenus/docs/evidence/gui-0ca1584/planet-poststart-verified.json new file mode 100644 index 00000000..21451752 --- /dev/null +++ b/DuneMenus/docs/evidence/gui-0ca1584/planet-poststart-verified.json @@ -0,0 +1,87 @@ +[ + { + "server": "arrakis", + "service": "active", + "paperReady": true, + "guiEnabled": true, + "incomingAndConfigsVerified": true, + "retainedBackendsAndMetadataVerified": true, + "terrainUnchanged": true, + "receipt": "/opt/dunerealms/backups/gui-0ca1584/20261129T025721.237213Z/arrakis/receipt.json", + "canonicalFieldsSha256": "2f680bf6c27da8f8c6b0ce6b38670e9453f1b98d75e8b80e657ee6b1bf476c16", + "packFields": { + "resource-pack": "https\\://www.dunerealms.com/downloads/DuneRealms-Textures-Restored-arrakis-20261128-1.zip", + "resource-pack-sha1": "5d598d1768d08b3a202bf0249131ab7a3fba4467", + "require-resource-pack": "true" + }, + "newErrorSignatures": [] + }, + { + "server": "caladan", + "service": "active", + "paperReady": true, + "guiEnabled": true, + "incomingAndConfigsVerified": true, + "retainedBackendsAndMetadataVerified": true, + "terrainUnchanged": true, + "receipt": "/opt/dunerealms/backups/gui-0ca1584/20261129T025938.268932Z/caladan/receipt.json", + "canonicalFieldsSha256": "4a3117f17a7ca2760bb11adca9f637fbb0dcc9fe418f4386599af9296d18884f", + "packFields": { + "resource-pack": "https\\://www.dunerealms.com/downloads/DuneRealms-Textures-Restored-caladan-20261128-1.zip", + "resource-pack-sha1": "a79b82a06a39dab9c22d5082323483e046c41a6a", + "require-resource-pack": "true" + }, + "newErrorSignatures": [] + }, + { + "server": "giedi_prime", + "service": "active", + "paperReady": true, + "guiEnabled": true, + "incomingAndConfigsVerified": true, + "retainedBackendsAndMetadataVerified": true, + "terrainUnchanged": true, + "receipt": "/opt/dunerealms/backups/gui-0ca1584/20261129T025938.268932Z/giedi_prime/receipt.json", + "canonicalFieldsSha256": "06399813bc44b7f3af54746e5da63c467589ae5f899faf5fc17f588ef6f7d25b", + "packFields": { + "resource-pack": "https\\://www.dunerealms.com/downloads/DuneRealms-Textures-Restored-giedi_prime-20261128-1.zip", + "resource-pack-sha1": "39436f73965765814b0847d3fd00e0ee0094478c", + "require-resource-pack": "true" + }, + "newErrorSignatures": [] + }, + { + "server": "kaitain", + "service": "active", + "paperReady": true, + "guiEnabled": true, + "incomingAndConfigsVerified": true, + "retainedBackendsAndMetadataVerified": true, + "terrainUnchanged": true, + "receipt": "/opt/dunerealms/backups/gui-0ca1584/20261129T025938.268932Z/kaitain/receipt.json", + "canonicalFieldsSha256": "f7c6384c0f8f2129522287cb28ed395e4e27e050e90fab4ff0ab55c82cdee00b", + "packFields": { + "resource-pack": "https\\://www.dunerealms.com/downloads/DuneRealms-Textures-Restored-kaitain-20261128-1.zip", + "resource-pack-sha1": "0bb028d37f53be86ac2ed952708c24f177a901a5", + "require-resource-pack": "true" + }, + "newErrorSignatures": [] + }, + { + "server": "sigma_draconis_iv", + "service": "active", + "paperReady": true, + "guiEnabled": true, + "incomingAndConfigsVerified": true, + "retainedBackendsAndMetadataVerified": true, + "terrainUnchanged": true, + "receipt": "/opt/dunerealms/backups/gui-0ca1584/20261129T025938.268932Z/sigma_draconis_iv/receipt.json", + "canonicalFieldsSha256": "704d5361ccbb12b20324baf33e13bdad8eb7a1d46dc499fd5a4b4eae56fda1d8", + "packFields": { + "resource-pack": "https\\://www.dunerealms.com/downloads/DuneRealms-Textures-Restored-sigma_draconis_iv-20261128-1.zip", + "resource-pack-sha1": "91f18aa6c113f72c76659ca5c0d1f7e7d7be3776", + "require-resource-pack": "true" + }, + "newErrorSignatures": [] + } +] diff --git a/DuneMenus/docs/evidence/gui-0ca1584/worldpack-store-verification.json b/DuneMenus/docs/evidence/gui-0ca1584/worldpack-store-verification.json new file mode 100644 index 00000000..8dbc53f8 --- /dev/null +++ b/DuneMenus/docs/evidence/gui-0ca1584/worldpack-store-verification.json @@ -0,0 +1,40 @@ +{ + "verifiedOriginalWorldPacks": { + "lobby": { + "filename": "DuneRealms-Textures-Restored-lobby-20261128-1.zip", + "sha256": "2ae455a7127472170554562feb928cddae86f4192bc9be674c1e1e41c7d8bc95", + "sha1": "34a079b96e121df19d14c964d2dad8c295ec4f45", + "bytes": 19044364 + }, + "arrakis": { + "filename": "DuneRealms-Textures-Restored-arrakis-20261128-1.zip", + "sha256": "d523977a11351285e18ff7a2ec9ce811f48b866dd73c55a653d57a21ae086516", + "sha1": "5d598d1768d08b3a202bf0249131ab7a3fba4467", + "bytes": 18998419 + }, + "caladan": { + "filename": "DuneRealms-Textures-Restored-caladan-20261128-1.zip", + "sha256": "93372db1434e2453624074803812ac549efc64ab58703b4aee78d4f7b129210f", + "sha1": "a79b82a06a39dab9c22d5082323483e046c41a6a", + "bytes": 18955426 + }, + "giedi_prime": { + "filename": "DuneRealms-Textures-Restored-giedi_prime-20261128-1.zip", + "sha256": "ac8973ba6ff2a3a9fb85302206288e5792beb9e75b5dbface74247f177a3e765", + "sha1": "39436f73965765814b0847d3fd00e0ee0094478c", + "bytes": 18955267 + }, + "kaitain": { + "filename": "DuneRealms-Textures-Restored-kaitain-20261128-1.zip", + "sha256": "a908cbfd032771c56d4ad8dfb06e8993af9963077587af1d2ba0d3dd1a8d0c99", + "sha1": "0bb028d37f53be86ac2ed952708c24f177a901a5", + "bytes": 18955280 + }, + "sigma_draconis_iv": { + "filename": "DuneRealms-Textures-Restored-sigma_draconis_iv-20261128-1.zip", + "sha256": "9d03f9613790bf26b71c85576c733964a81ce007b66a2b5e446bbbb4ecd503d3", + "sha1": "91f18aa6c113f72c76659ca5c0d1f7e7d7be3776", + "bytes": 18955703 + } + } +} diff --git a/DuneMenus/docs/evidence/vanilla-79326a/artwork-79326a-artifact-verification.json b/DuneMenus/docs/evidence/vanilla-79326a/artwork-79326a-artifact-verification.json new file mode 100644 index 00000000..6221556f --- /dev/null +++ b/DuneMenus/docs/evidence/vanilla-79326a/artwork-79326a-artifact-verification.json @@ -0,0 +1,11 @@ +{ + "source": "79326a2531774dbf57383e4fed1e447dd52b4066", + "artifact": 6990, + "stage": "/var/lib/dunerealms-plugin-staging/79326a2531774dbf57383e4fed1e447dd52b4066", + "verifiedMembers": 19, + "wrapperBytes": 44270634, + "wrapperSHA256": "a88a8f19ed25a77504c4dd7a08a0fb995707f69e69bdfbc86ab7db8084296f9d", + "all4JarsAnd6HelpersIdenticalToLiveA3": true, + "packBytes": 21105132, + "packSHA256": "61931cc463933706fb391ce8aaff78138ff1377241e062aac000aa144242a10d" +} diff --git a/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-arrakis-verification.json b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-arrakis-verification.json new file mode 100644 index 00000000..d8aa40c7 --- /dev/null +++ b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-arrakis-verification.json @@ -0,0 +1,11 @@ +{ + "server": "arrakis", + "sourceCommit": "79326a2531774dbf57383e4fed1e447dd52b4066", + "runtimeJarChanges": [], + "nonPackPropertiesPreserved": true, + "artworkPackInstalled": true, + "GUIenabled": true, + "startupDone": true, + "serviceActive": true, + "errors": [] +} diff --git a/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-caladan-verification.json b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-caladan-verification.json new file mode 100644 index 00000000..71b57f44 --- /dev/null +++ b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-caladan-verification.json @@ -0,0 +1,11 @@ +{ + "server": "caladan", + "sourceCommit": "79326a2531774dbf57383e4fed1e447dd52b4066", + "runtimeJarChanges": [], + "nonPackPropertiesPreserved": true, + "artworkPackInstalled": true, + "GUIenabled": true, + "startupDone": true, + "serviceActive": true, + "errors": [] +} diff --git a/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-giedi_prime-verification.json b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-giedi_prime-verification.json new file mode 100644 index 00000000..65219715 --- /dev/null +++ b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-giedi_prime-verification.json @@ -0,0 +1,11 @@ +{ + "server": "giedi_prime", + "sourceCommit": "79326a2531774dbf57383e4fed1e447dd52b4066", + "runtimeJarChanges": [], + "nonPackPropertiesPreserved": true, + "artworkPackInstalled": true, + "GUIenabled": true, + "startupDone": true, + "serviceActive": true, + "errors": [] +} diff --git a/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-kaitain-verification.json b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-kaitain-verification.json new file mode 100644 index 00000000..94385227 --- /dev/null +++ b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-kaitain-verification.json @@ -0,0 +1,40 @@ +{ + "server": "kaitain", + "sourceCommit": "79326a2531774dbf57383e4fed1e447dd52b4066", + "runtimeJarChanges": [], + "nonPackPropertiesPreserved": true, + "artworkPackInstalled": true, + "GUIenabled": true, + "startupDone": true, + "serviceActive": true, + "errors": [ + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_command' on page 'DuneRealms Imperial Navigator' with type 'custom_command' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_archive_command' on page 'DuneRealms Imperial Navigator' with type 'custom_command' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_archive' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_speaker' on page 'DuneRealms Imperial Navigator' with type 'simple_speaker' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_home' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_travel' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_arrakis_confirm' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_arrakis_go' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_kaitain_confirm' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_kaitain_go' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_giedi_confirm' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_giedi_go' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_contracts' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_contract_list' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_spicejobs' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_job_list' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_item_notice' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_item_open' on page 'DuneRealms Imperial Navigator' with type 'player_run_command' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_support' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_links' on page 'DuneRealms Imperial Navigator' with type 'option' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_support_link' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_appeal_link' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_account_link' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_clans_link' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension.", + "[10:06:46] [Server thread/ERROR]: [Typewriter] Could not find entry class for 'dr_nav_manual_link' on page 'DuneRealms Imperial Navigator' with type 'simple_message' in any extension." + ], + "baselineErrorComparison": { + "all25TypewriterSignaturesMatchPreviousA3Startup": true + } +} diff --git a/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-lobby-verification.json b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-lobby-verification.json new file mode 100644 index 00000000..8b38c1e7 --- /dev/null +++ b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-lobby-verification.json @@ -0,0 +1,22 @@ +{ + "sourceCommit": "79326a2531774dbf57383e4fed1e447dd52b4066", + "server": "lobby", + "runtimeJarChanges": [], + "nonPackPropertiesPreserved": true, + "packProperties": { + "resource-pack": "https://www.dunerealms.com/downloads/DuneRealms-Resources-79326a2531774dbf57383e4fed1e447dd52b4066.zip", + "resource-pack-sha1": "77e78780bcdb14c962c70fc9a3501c35df8bb80a", + "resource-pack-id": "c24c7cf5-a292-539d-971f-a96d8b838162", + "require-resource-pack": "true" + }, + "startupDone": true, + "GUIenabled": true, + "errors": [ + "[10:02:06] [Server thread/ERROR]: Could not pass event ServerLoadEvent to JarvisTranslator v0.5.35", + "[10:02:06] [Server thread/ERROR]: Could not pass event ServerLoadEvent to JarvisTranslator v0.5.35" + ], + "readinessLogs": [ + "[10:03:28] [Server thread/INFO]: [DunerealmsGUI] Central resource pack loaded for unimatrix999 UUID c24c7cf5-a292-539d-971f-a96d8b838162" + ], + "ownerConfirmedArtworkAndMenuWork": true +} diff --git a/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-sigma_draconis_iv-verification.json b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-sigma_draconis_iv-verification.json new file mode 100644 index 00000000..af0aad03 --- /dev/null +++ b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-sigma_draconis_iv-verification.json @@ -0,0 +1,11 @@ +{ + "server": "sigma_draconis_iv", + "sourceCommit": "79326a2531774dbf57383e4fed1e447dd52b4066", + "runtimeJarChanges": [], + "nonPackPropertiesPreserved": true, + "artworkPackInstalled": true, + "GUIenabled": true, + "startupDone": true, + "serviceActive": true, + "errors": [] +} diff --git a/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-summary.json b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-summary.json new file mode 100644 index 00000000..fd03991a --- /dev/null +++ b/DuneMenus/docs/evidence/vanilla-79326a/vanilla-79326a-summary.json @@ -0,0 +1,26 @@ +{ + "source": "79326a2531774dbf57383e4fed1e447dd52b4066", + "PR": 9, + "CI": 24, + "artifact": 6990, + "all6StartupDone": true, + "all6RuntimeJarHashAndMetadataChanges": [], + "all6NonPackPropertiesPreserved": true, + "ownerAcceptance": "Artwork and menu work; lobby canary only", + "clientPackLoadedLog": "lobby10:03:28UTC c24c7cf5-a292-539d-971f-a96d8b838162", + "publisherBackup": "/etc/nginx/snippets/dunerealms-gui-download-v3.conf.before-menu-20261129T095935.714648Z", + "receipts": { + "lobby": "/opt/dunerealms/backups/vanilla-79326a/20261129T100042.351627Z/lobby/receipt.json", + "arrakis": "/opt/dunerealms/backups/vanilla-79326a/20261129T100453.757119Z/arrakis/receipt.json", + "remaining4": "/opt/dunerealms/backups/vanilla-79326a/20261129T100556.307189Z/{server}/receipt.json" + }, + "knownBaselineErrors": [ + "lobby2JarvisServerLoadfood/brewing", + "kaitain25TypewriterEntriesMatchedA3" + ], + "separatePending": [ + "Stilgarrolelabel/carddescriptionclippingGUIbug", + "spice-raiderengineeringfromfinalClaudeZIP" + ], + "noRaidCodeDeployed": true +} diff --git a/DuneMenus/docs/menu-audit-20261205.json b/DuneMenus/docs/menu-audit-20261205.json new file mode 100644 index 00000000..076197e9 --- /dev/null +++ b/DuneMenus/docs/menu-audit-20261205.json @@ -0,0 +1,91 @@ +{ + "scope": "Current six Paper backends; source routes and saved Citizens records; no production payments or quest claims executed", + "menuFamilies": [ + "hub", + "travel", + "exchange", + "clan", + "company", + "missions", + "spice", + "war", + "politics", + "house", + "equipment", + "bank", + "atm", + "withdraw", + "transfer" + ], + "nativeServiceRoutes": [ + "hub", + "travel", + "exchange", + "clan", + "company", + "missions", + "spice", + "war", + "politics", + "lore", + "cookbook", + "mentat", + "house", + "equipment" + ], + "repairs": [ + "Explicit current Exchange Broker command", + "Departure pads open current authenticated Guild menu without legacy direct teleport fallback", + "Guild return menu gains Back to Imperial Codex", + "Empty NPC mission views link to the current mission journal", + "Cookbook command offered in completion and explicit Codex route", + "Permission refusal produces feedback instead of a silent menu" + ], + "guild": { + "primaryWorldsWithSavedNavigator": [ + "arrakis", + "caladan", + "giedi_prime", + "kaitain", + "sigma_draconis_iv" + ], + "lobby": "Guild Navigator Liaison", + "enabledOnAllSix": true, + "otherDimensions": "Guild command and marked-NPC handler are world independent; outside guild_lobby the menu presents the existing central return operation. No new NPC spawned or travel authority bypassed." + }, + "npcPurposeReview": { + "savedRecords": 45, + "snapshotCaution": "Disk registry snapshot is not a fresh connected-client or spawned-entity census.", + "legacyCopies": { + "lobby_arrakis": { + "unmappedQuestRoles": [ + "esmar_tuek", + "stilgar", + "shadout_mapes", + "chani", + "liet_kynes", + "alia_atreides", + "war_marshal" + ], + "ambientSmugglerCopies": 3 + }, + "lobby_base": { + "quartermasterCopy": 1 + } + }, + "clarity": "Water and spice sellers in Guild Lobby barter explicitly non-redeemable samples; they are not the Arrakis Melange buyers. Dynamic Home Block NPC retains its organisation service. Fixed Esmar starts contracts, Staban receives deliveries. No NPC records removed.", + "conditionalRoleReview": { + "glossu_rabban": "No built-in branch or fixed decision entry; central dossier/cargo assignments may still give this role work. Verify catalogue before removal.", + "irulan_corrino": "No built-in branch or fixed decision entry; central dossier/cargo assignments may still give this role work. Verify catalogue before removal." + } + }, + "notClaimed": "Full live client coverage across every faction, permission, quest state, Java and Bedrock remains a separate player validation; fixtures do not spend money, advance quests, or transfer live players.", + "localValidation": { + "unitTests": 252, + "failed": 0, + "renderedControls": 334, + "renderer": "Exact installed MCGUI 0.8.6", + "standardCardWidthAndHeightRatio": 0.75, + "retainedVariants": "Lobby and planet GUI/Menu classes assembled without unrelated archive changes; method-level audit excludes only explicit target methods." + } +} diff --git a/DuneMenus/previews/set_a_hub_travel_exchange_clan_spice_missions.png b/DuneMenus/previews/set_a_hub_travel_exchange_clan_spice_missions.png new file mode 100644 index 00000000..58f6276a Binary files /dev/null and b/DuneMenus/previews/set_a_hub_travel_exchange_clan_spice_missions.png differ diff --git a/DuneMenus/previews/set_b_war_politics_house_equipment_bank_atm.png b/DuneMenus/previews/set_b_war_politics_house_equipment_bank_atm.png new file mode 100644 index 00000000..99835c0b Binary files /dev/null and b/DuneMenus/previews/set_b_war_politics_house_equipment_bank_atm.png differ diff --git a/DuneMenus/previews/set_c_atm_redeem.png b/DuneMenus/previews/set_c_atm_redeem.png new file mode 100644 index 00000000..52c99cb5 Binary files /dev/null and b/DuneMenus/previews/set_c_atm_redeem.png differ diff --git a/DuneMenus/settings.gradle.kts b/DuneMenus/settings.gradle.kts new file mode 100644 index 00000000..c4485674 --- /dev/null +++ b/DuneMenus/settings.gradle.kts @@ -0,0 +1,3 @@ +rootProject.name = "DuneMenus" +include(":JarvisConnector") +project(":JarvisConnector").projectDir = file("../JarvisConnector") diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/AtmMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/AtmMenu.java new file mode 100644 index 00000000..8820c30b --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/AtmMenu.java @@ -0,0 +1,150 @@ +package com.dunerealms.menus; + +import com.dunerealms.jarvis.DunemarkDenomination; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** + * Focused cash operations and a bank-reported receipt; no extra confirmation screen. + * Deposit : tap bills and coins, one click -> a new RIA ID is created and shown in the ID box. + * Redeem : type an RIA ID, then one click pays it out as Cash or To bank. + * Withdraw : tap bills and coins, one click takes the cash out of your own account. + */ +final class AtmMenu extends Menu { + enum Tab { HOME, DEPOSIT, REDEEM, WITHDRAW, RECEIPT } + private static final int[] BILLS = {10, 11, 12, 19, 20}; + private static final int[] COINS = {14, 15, 16}; + private static final List NOTES = List.of(DunemarkDenomination.NOTE_10, DunemarkDenomination.NOTE_20, + DunemarkDenomination.NOTE_50, DunemarkDenomination.NOTE_100, DunemarkDenomination.NOTE_500); + private static final List COIN_VALUES = List.of(DunemarkDenomination.COIN_050, + DunemarkDenomination.COIN_1DM, DunemarkDenomination.COIN_2DM); + private Tab tab; + private final List selected = new ArrayList<>(); + private String entered; // RIA ID typed on the Redeem tab + private String receiptOperation,receiptReference,receiptMessage; + private Long receiptAmount; + private boolean receiptCanRedeem; + + AtmMenu(DuneMenusPlugin plugin, Player p, Menu parent, Tab tab) { super(plugin, p, parent); this.tab = tab; } + String id() { return switch(tab){case WITHDRAW->"withdraw";case DEPOSIT->"deposit";case REDEEM->"redeem";case RECEIPT->"receipt";default->"atm";}; } + Skin skin() { return tab == Tab.REDEEM ? Skin.GOLD : Skin.TRAVEL; } + String title() { return switch(tab){case HOME->"Rihla ATM";case DEPOSIT->"Rihla ยท Deposit cash";case WITHDRAW->"Rihla ยท Withdraw cash";case REDEEM->"Rihla ยท Redeem RIA ID";case RECEIPT->"Rihla ยท Transaction receipt";}; } + String subtitle() { return switch (tab) { + case HOME -> "Choose a cash service. Bills and coins are selected inside the operation."; + case DEPOSIT -> "Put in cash. You get an RIA ID to keep or give away."; + case REDEEM -> "Got an RIA ID? Type it in and take the money as cash or to your bank."; + case WITHDRAW -> "Select bills and coins, then withdraw the displayed amount."; + case RECEIPT -> "Your bank-reported transaction result. Keep your RIA ID."; }; } + int rows() { return 5; } + @Override boolean renderWhileLoading(){return true;} + @Override boolean navigationWhileLoading(int slot){return slot==0||slot==1||slot==2||slot==36;} + + private void tabButton(int slot, Material m, String label, Tab t) { + var item = Ui.item(m, (tab == t ? "" : "") + label); + put(slot, tab == t ? Ui.glow(item) : item, c -> { tab = t; selected.clear(); redraw(); }); + } + + private void add(int slot, DunemarkDenomination denomination) { + var selector=denomination.displayItem();var meta=selector.getItemMeta();meta.displayName(net.kyori.adventure.text.Component.text(Ui.dm(denomination.faceMinor())));meta.lore(List.of(net.kyori.adventure.text.Component.text("Select one for this "+(tab==Tab.DEPOSIT?"deposit":"withdrawal"))));selector.setItemMeta(meta); + put(slot, selector, c -> { + if (selected.size() < 36) selected.add(denomination); + redraw(); + }); + } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + for (int s : new int[]{3, 5, 6, 7, 8}) put(s, Ui.pane(Material.CYAN_STAINED_GLASS_PANE)); + if(tab==Tab.HOME){ + tabButton(0, Material.EMERALD, "Deposit cash", Tab.DEPOSIT); + tabButton(1, Material.NAME_TAG, "Redeem RIA ID", Tab.REDEEM); + tabButton(2, Material.GOLD_INGOT, "Withdraw cash", Tab.WITHDRAW); + put(36,Ui.item(Material.ARROW,"Back"),c->{end();plugin.openNativeService(player,"hub");}); + return; + } + put(36,Ui.item(Material.ARROW,"Back"),c->{tab=Tab.HOME;selected.clear();redraw();}); + if(tab==Tab.RECEIPT){ + put(13,Ui.item(Material.PAPER,""+receiptOperation, + receiptAmount==null?""+receiptMessage:"Amount: "+Ui.dm(receiptAmount),""+receiptMessage)); + String reference=RiaReference.normalize(receiptReference); + if(reference!=null){ + referenceButton(reference); + if(receiptCanRedeem)put(31,Ui.item(Material.ENDER_CHEST,"Use this RIA ID", + "Open its payout options","No need to type the reference"),c->{entered=reference;tab=Tab.REDEEM;redraw();}); + } + return; + } + if (tab == Tab.REDEEM) drawRedeem(); else drawCash(); + } + + private void drawCash() { + long minor = selected.stream().mapToLong(DunemarkDenomination::faceMinor).sum(); + boolean dep = tab == Tab.DEPOSIT; + String verb = dep ? "Deposit" : "Withdraw"; + put(9, Ui.item(Material.GREEN_STAINED_GLASS_PANE, "Bills")); + put(13, Ui.item(Material.YELLOW_STAINED_GLASS_PANE, "Coins")); + for (int i = 0; i < BILLS.length; i++) add(BILLS[i], NOTES.get(i)); + for (int i = 0; i < COINS.length; i++) add(COINS[i], COIN_VALUES.get(i)); + + put(24, minor == 0 ? Ui.item(Material.GRAY_DYE, "" + verb, "Choose bills and coins first") + : Ui.glow(Ui.item(dep ? Material.EMERALD : Material.GOLD_INGOT, "" + verb + " " + Ui.dm(minor), + dep ? "Creates a new RIA ID" : "From your bank account")), + c -> { + if (minor <= 0) return; + var pieces = List.copyOf(selected); + + if (dep) load(backend().atmCreateRia(player, pieces), r -> { + say(new Backend.Result(r.ok(), r.message())); + if (r.ok()) { receipt("Cash deposit",r.receipt(),r.message()); } + else redraw(); + }); + else load(backend().bankWithdraw(player, pieces), r -> { + say(r); + if (r.ok()) receipt("Cash withdrawal",r.receipt(),r.message()); + else redraw(); + }); + }); + + } + + private void receipt(String operation,Backend.CashReceipt facts,String message){ + receiptOperation=facts!=null&&facts.recovered()?"Recovered Rihla transaction":operation; + receiptAmount=facts==null?null:facts.amountMinor();receiptReference=facts==null?null:facts.riaId();receiptMessage=message; + receiptCanRedeem="Cash deposit".equals(operation)&&RiaReference.normalize(receiptReference)!=null; + selected.clear();tab=Tab.RECEIPT;redraw(); + if(RiaReference.normalize(receiptReference)!=null)player.sendMessage(RiaClipboard.message(receiptReference)); + } + + private void referenceButton(String reference){ + boolean bedrock=plugin.modeFor(player)==Mode.BEDROCK; + put(29,Ui.item(Material.NAME_TAG,bedrock?"Show RIA ID in chat":"Copy RIA ID", + ""+reference,bedrock?"Send the reference privately to chat":"Open a private click-to-copy link"),c->{ + end();plugin.closeNativePresentation(player); + if(!bedrock)player.sendMessage(net.kyori.adventure.text.Component.text("Press T, then click the RIA ID below to copy it.")); + player.sendMessage(RiaClipboard.message(reference)); + }); + } + + private void drawRedeem() { + put(13, Ui.item(Material.WRITABLE_BOOK, entered == null ? "Enter RIA ID" : "Change RIA ID", + "Type the reference in chat", "Type cancel to return"), c -> { + end(); + plugin.closeNativePresentation(player); + plugin.enterRia(player,text->{if(text!=null)entered=text;open();}); + }); + for (int s : new int[]{28, 30}) put(s, Ui.pane(Material.YELLOW_STAINED_GLASS_PANE)); + if (entered == null) return; + referenceButton(entered); + final String id = entered; + load(backend().atmLookup(player, id), v -> { + if (v == null) { put(22, Ui.item(Material.BARRIER, "RIA ID not found")); return; } + put(22, Ui.glow(Ui.item(Material.GOLD_BLOCK, "" + Ui.dm(v.amountMinor()), "From: " + v.fromName()))); + put(24, Ui.glow(Ui.item(Material.GOLD_INGOT, "Take as cash", "Bills and coins in your inventory")), + c -> load(backend().atmRedeem(player, v, false), r -> { say(r); if (r.ok()) {entered = null;receipt("RIA payout ยท Cash",r.receipt(),r.message());} else redraw(); })); + put(26, Ui.glow(Ui.item(Material.ENDER_CHEST, "Send to my bank", "Credited to your account")), + c -> load(backend().atmRedeem(player, v, true), r -> { say(r); if (r.ok()) {entered = null;receipt("RIA payout ยท Bank",r.receipt(),r.message());} else redraw(); })); + }); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/Backend.java b/DuneMenus/src/main/java/com/dunerealms/menus/Backend.java new file mode 100644 index 00000000..2edbd610 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/Backend.java @@ -0,0 +1,119 @@ +package com.dunerealms.menus; + +import com.dunerealms.jarvis.DunemarkDenomination; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +/** + * Everything the menus need from the game backend (Jarvis). Menus never talk to Jarvis directly. + *

Every method defaults to "not connected", so a backend only overrides what it supports and the + * menu tells the player politely instead of faking data or touching money. + *

Rules for implementers (full detail in docs/BACKEND.md): + * money is minor units (1.00 DM = 100); futures may complete on any thread; there are NO confirm screens, + * so each mutating call must be idempotent and safe against a double click. + */ +public interface Backend { + /** Complete a future exceptionally with this to mean "this feature is not wired yet". */ + final class Unavailable extends RuntimeException { public Unavailable() { super("not wired", null, false, false); } } + + record CashReceipt(long amountMinor,String riaId,boolean recovered) {} + record Result(boolean ok, String message, CashReceipt receipt) { + public Result(boolean ok,String message){this(ok,message,null);} + public static Result yes(String m) { return new Result(true, m); } + public static Result no(String m) { return new Result(false, m); } + } + /** fareMinor: -1 unknown (no fare line shown), 0 free, >0 price. */ + record World(String id, String name, String tagline, Material icon, int online, boolean up, long fareMinor, String keyId, int version) {} + record Listing(String id, String title, Material icon, String seller, long priceMinor, int quantity, Integer kitVersion, boolean purchasable) {} + record Page(List

items, boolean hasNext) {} + record Org(String name, String role, int members, Long vaultMinor, String id, String revision, String warKey) {} + record Member(UUID id, String name, String role) {} + /** state is one of ACTIVE, AVAILABLE, DONE. */ + record TurnIn(String action, String role, String metric, String label, int quantity) {} + record Mission(String id, String title, Material icon, String state, int percent, boolean claimable, String summary, Long revision, TurnIn turnIn) {} + record Spice(int carried, int guildCount, int smugglerCount, boolean guildEnabled, boolean smugglerEnabled, int pendingCount) {} + /** roster has 8 entries; blank = empty slot. */ + record War(String title, List roster, List status, boolean canLaunch, boolean editable, UUID draftId) {} + record Decision(String id, String title, Material icon, String cost, String effect, boolean allowed, String npcRole, String sourceAccount, String feeMinor) {} + record House(String id, String name, String motto, Material banner, int version) {} + /** Rihla account. reservedMinor = amount+tax locked by pending outgoing transfers. collectableMinor = incoming transfers waiting to be collected. */ + record Account(String accountNo, Long postbankAvailableMinor, long reservedMinor, long collectableMinor) {} + /** direction is "OUT" (you sent it, still pending, cancellable) or "IN" (waiting for you to collect). taxMinor is only set for OUT. */ + record Transfer(String id, String direction, String counterparty, long amountMinor, long taxMinor, String when) {} + record Refit(boolean possible, String itemName, Material icon, List costs, String note, UUID quoteId) {} + + private static CompletableFuture na() { return CompletableFuture.failedFuture(new Unavailable()); } + + // ---- wallet / travel ---- + default CompletableFuture balance(Player p) { return na(); } + default List loreArchive() { return List.of(); } + default Result claimCodex(Player p) { return Result.no("The Imperial Codex is temporarily unavailable."); } + default CompletableFuture mentat(Player p) { return na(); } + default CompletableFuture savedItem(Player p, UUID id, int revision) { return na(); } + default boolean inGuildLobby(Player p) { return false; } + default Result returnToGuild(Player p) { return Result.no("Guild return is temporarily unavailable."); } + default CompletableFuture> worlds(Player p) { return na(); } + default CompletableFuture book(Player p, World destination) { return na(); } + // ---- exchange (tab is "buy" | "kits" | "mine") ---- + default CompletableFuture listings(Player p, String tab, int page) { return na(); } + default CompletableFuture buy(Player p, Listing offer, int qty) { return na(); } + default CompletableFuture withdraw(Player p, Listing offer) { return na(); } + /** Lists the item in the player's main hand at the given unit price. */ + default CompletableFuture sell(Player p, ItemStack expected, int slot, long priceMinor) { return na(); } + default CompletableFuture collectPurchases(Player p) { return na(); } + // ---- organisations (kind is "clan" | "company") ---- + default CompletableFuture> organisations(Player p, String kind) { return na(); } + default CompletableFuture org(Player p, String kind, String id) { return na(); } + default CompletableFuture> members(Player p, String kind, String id) { return na(); } + /** action ids used by the menus: home, claims, vault, allies, wars, invite, transactions, roles, war-transport */ + default CompletableFuture orgAction(Player p, String kind, String action, Org shown) { return na(); } + // ---- missions ---- + default CompletableFuture> missions(Player p) { return na(); } + default CompletableFuture missionTurnIn(Player p, Mission mission) { return na(); } + default CompletableFuture missionAction(Player p, Mission mission, boolean claim) { return na(); } + // ---- spice (channel is "guild" | "smuggler") ---- + default CompletableFuture spice(Player p) { return na(); } + default CompletableFuture sellSpice(Player p, String channel, int shownCount) { return na(); } + default CompletableFuture collectSpice(Player p) { return na(); } + // ---- war muster ---- + default CompletableFuture war(Player p) { return na(); } + default CompletableFuture> warCandidates(Player p, War war) { return na(); } + default CompletableFuture warAssign(Player p, War war, int slot, UUID candidateOrNull) { return na(); } + default CompletableFuture warSave(Player p, War war) { return na(); } + default CompletableFuture warLaunch(Player p, War war) { return na(); } + // ---- politics / house / equipment ---- + default CompletableFuture> decisions(Player p) { return na(); } + default CompletableFuture enact(Player p, Decision decision) { return na(); } + default CompletableFuture> houses(Player p) { return na(); } + default CompletableFuture chooseHouse(Player p, House house) { return na(); } + default CompletableFuture refitQuote(Player p) { return na(); } + default CompletableFuture refit(Player p, Refit quote) { return na(); } + // ---- Rihla money transfer (Corrino Group). Used by the Bank screen and the ATM. ---- + // Rules (docs/BACKEND.md): private account per user; sending creates a pending transfer that reserves + // amount + tax (1% up to and including 3,000 DM, 5% above, rounded UP to the next cent); the recipient + // receives the full amount and collects it in-game; cancelling releases the reservation. + default CompletableFuture bankAccount(Player p) { return na(); } + /** ATM, tab 1. The player taps bills and coins; the menu sends the total. Backend takes the cash and CREATES a new RIA ID worth that amount. */ + record Issued(boolean ok, String message, String riaId, CashReceipt receipt) { + public Issued(boolean ok,String message,String riaId){this(ok,message,riaId,null);} + } + default CompletableFuture atmCreateRia(Player p, List pieces) { return na(); } + /** ATM, tab 2. Look an RIA ID up so the menu can show the amount before payout. Return null/exceptional if unknown. */ + record Voucher(String riaId, long amountMinor, String fromName) {} + default CompletableFuture atmRecentDeposit(Player p) { return na(); } + default CompletableFuture atmLookup(Player p, String riaId) { return na(); } + /** ATM, tab 2. Pay the RIA ID out: toBank=false gives cash, toBank=true credits the player's bank account. One click, no confirmation. */ + default CompletableFuture atmRedeem(Player p, Voucher voucher, boolean toBank) { return na(); } + /** Cash withdrawal from the RIA account. The menu builds amountMinor from the bills and coins the player tapped. + * The backend debits the account and gives the player that cash (however cash is represented), or returns Result.no (insufficient funds, inventory full...). */ + default CompletableFuture bankWithdraw(Player p, List pieces) { return na(); } + default CompletableFuture> bankTransfers(Player p) { return na(); } + default CompletableFuture bankSend(Player p, UUID to, long amountMinor) { return na(); } + default CompletableFuture bankCancel(Player p, String transferId) { return na(); } + /** transferId -1 collects every incoming transfer. */ + default CompletableFuture bankCollect(Player p, String transferId) { return na(); } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/BankMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/BankMenu.java new file mode 100644 index 00000000..478fc08c --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/BankMenu.java @@ -0,0 +1,61 @@ +package com.dunerealms.menus; + +import java.util.List; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** + * 6 rows. Left: your private account. Centre: Send money, Withdraw cash, Collect transfers. + * Right: pending transfers: outgoing ones cancel on click (releases the reservation), incoming ones collect on click. + */ +final class BankMenu extends Menu { + private static final int[] LIST = {15, 16, 24, 25, 33, 34}; + + BankMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); } + String id() { return "bank"; } + Skin skin() { return Skin.GOLD; } + String title() { return "Rihla ยท Money Transfer"; } + String subtitle() { return "Corrino Group. Your private account. Send and collect transfers."; } + int rows() { return 6; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + for (int i = 0; i < 9; i += 2) put(i, Ui.pane(Material.CYAN_STAINED_GLASS_PANE)); + for (int s : new int[]{12, 14, 21, 23, 30, 32}) put(s, Ui.pane(Material.YELLOW_STAINED_GLASS_PANE)); + back(45); + put(13, Ui.item(Material.WRITABLE_BOOK, "Send money", "Choose an amount, pick a person.", "Tax: " + Rihla.rateText()), + t -> go(new TransferMenu(plugin, player, this, 10_000))); + put(22, Ui.item(Material.PAPER, "Withdraw cash", "Take bills and coins from your account"), + t -> go(new AtmMenu(plugin, player, this, AtmMenu.Tab.WITHDRAW))); + put(31, Ui.item(Material.CHEST, "Collect transfers", "Loadingโ€ฆ")); + put(47, Ui.item(Material.BOOK, "Statement", "Opens your full statement in User CP"), t -> { + player.sendMessage(Ui.text("Your statement: open User CP")); + }); + put(11, Ui.item(Material.NAME_TAG, "Rihla reference", "Loadingโ€ฆ")); + load(backend().bankAccount(player), a -> { + put(11, Ui.item(Material.NAME_TAG, "Rihla reference", "Account: " + a.accountNo())); + put(20, Ui.glow(Ui.item(Material.GOLD_BLOCK, "Postbank available", "" + (a.postbankAvailableMinor()==null?"Unavailable":Ui.dm(a.postbankAvailableMinor()))))); + put(29, Ui.item(Material.IRON_BARS, "Reserved for transfers", "" + Ui.dm(a.reservedMinor()), "Amount plus tax, until collected")); + var collect = Ui.item(Material.CHEST, "Collect transfers", "Waiting: " + Ui.dm(a.collectableMinor()), + a.collectableMinor() > 0 ? "Click to collect everything" : "Nothing waiting"); + put(31, a.collectableMinor() > 0 ? Ui.glow(collect) : collect, t -> act(backend().bankCollect(player, null))); + }); + load(backend().bankTransfers(player), list -> { + for (int i = 0; i < Math.min(LIST.length, list.size()); i++) row(LIST[i], list.get(i)); + if (list.isEmpty()) put(24, Ui.item(Material.PAPER, "No pending transfers")); + }); + put(49, Ui.item(Material.OAK_SIGN, "Transfer tax", "1% of the amount up to 3,000 DM", "5% of the amount above 3,000 DM", + "The recipient gets the full amount.")); + } + + private void row(int slot, Backend.Transfer t) { + if (t.direction().equals("OUT")) + put(slot, Ui.item(Material.ORANGE_DYE, "To " + t.counterparty() + " ยท " + Ui.dm(t.amountMinor()), + "Tax: " + Ui.dm(t.taxMinor()), "" + t.when(), "", "Click to cancel and release the reservation"), + c -> act(backend().bankCancel(player, t.id()))); + else + put(slot, Ui.glow(Ui.item(Material.LIME_DYE, "From " + t.counterparty() + " ยท " + Ui.dm(t.amountMinor()), + "" + t.when(), "", "Click to collect")), + c -> act(backend().bankCollect(player, t.id()))); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/Bedrock.java b/DuneMenus/src/main/java/com/dunerealms/menus/Bedrock.java new file mode 100644 index 00000000..9f3c2824 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/Bedrock.java @@ -0,0 +1,53 @@ +package com.dunerealms.menus; + +import java.util.List; +import java.util.function.IntConsumer; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +/** Floodgate forms built from the same menu definition. */ +final class Bedrock { + private Bedrock() {} + + static boolean is(Player p) { + if (!Bukkit.getPluginManager().isPluginEnabled("floodgate")) return false; + try { return Impl.is(p); } catch (LinkageError missing) { return false; } + } + + static void show(JavaPlugin plugin, Player p, String title, String subtitle, List info, List cards, + IntConsumer pick, Runnable closed) { + try { Impl.show(plugin, p, title, subtitle, info, cards, pick, closed); } + catch (LinkageError missing) { closed.run(); } + } + + private static String label(Card c) { + List lore = c.lore().stream().filter(s -> !s.isBlank()).limit(2).toList(); + String sub = String.join(" ยท ", lore); + if (sub.length() > 60) sub = sub.substring(0, 57) + "โ€ฆ"; + return sub.isEmpty() ? c.title() : c.title() + "\n" + sub; + } + + private static final class Impl { + static boolean is(Player p) { return org.geysermc.floodgate.api.FloodgateApi.getInstance().isFloodgatePlayer(p.getUniqueId()); } + + static void show(JavaPlugin plugin, Player p, String title, String subtitle, List info, List cards, + IntConsumer pick, Runnable closed) { + StringBuilder content = new StringBuilder(subtitle == null ? "" : subtitle); + for (String line : info) { if (content.length() > 0) content.append('\n'); content.append(line); } + var form = org.geysermc.cumulus.form.SimpleForm.builder().title(title).content(content.toString()); + for (Card c : cards) form.button(label(c)); + form.closedOrInvalidResultHandler(() -> { + if (plugin.isEnabled()) Bukkit.getScheduler().runTask(plugin, closed); + }); + form.validResultHandler(result -> { + int index = result.clickedButtonId(); + if (!plugin.isEnabled()) return; + Bukkit.getScheduler().runTask(plugin, () -> { + if (p.isOnline() && index >= 0 && index < cards.size()) pick.accept(cards.get(index).slot()); + }); + }); + if (!org.geysermc.floodgate.api.FloodgateApi.getInstance().sendForm(p.getUniqueId(), form.build())) closed.run(); + } + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/CanvasProvider.java b/DuneMenus/src/main/java/com/dunerealms/menus/CanvasProvider.java new file mode 100644 index 00000000..14ecd528 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/CanvasProvider.java @@ -0,0 +1,20 @@ +package com.dunerealms.menus; +import java.util.*; +import java.util.function.IntConsumer; +import org.bukkit.entity.Player; +/** Uses the existing installed MC GUI canvas transport, with the supplied menu definitions. */ +final class CanvasProvider implements FullscreenProvider { + private final DuneMenusPlugin plugin; + private final MenuArt art;private boolean prepared; + CanvasProvider(DuneMenusPlugin plugin){this.plugin=plugin;this.art=new MenuArt(plugin);var services=plugin.getServer().getPluginManager().getPlugin("DunerealmsGUI");if(services!=null)try{art.prepare(services.getDataFolder().toPath().resolve("mcgui"));prepared=true;}catch(Exception failure){plugin.getLogger().warning("Menu artwork preparation failed: "+failure.getClass().getSimpleName());}} + public boolean open(Player player,Screen screen,IntConsumer select,Runnable close){return open(player,screen,select,close,-1);} + private boolean open(Player player,Screen screen,IntConsumer select,Runnable close,int selected){ + var services=plugin.getServer().getPluginManager().getPlugin("DunerealmsGUI"); + if(services==null||!services.isEnabled())return false; + Map images=new HashMap<>(); + try{if(prepared)for(Card card:screen.cards()){var inventory=screen.contents();if(card.slot()>=0&&card.slot() actions=new HashMap<>();for(Card card:screen.cards()){if(!card.enabled())continue;actions.put(card.slot(),()->select.accept(card.slot()));if(SuppliedDocument.summary(card).size()>1)actions.put(1000+card.slot(),()->open(player,screen,select,close,card.slot()));} + try{return Boolean.TRUE.equals(services.getClass().getMethod("presentSuppliedMenu",Player.class,String.class,String.class,Map.class,Runnable.class).invoke(services,player,screen.title(),SuppliedDocument.html(screen.id(),screen.title(),screen.subtitle(),screen.cards(),screen.info(),images,selected),actions,close));} + catch(ReflectiveOperationException failure){plugin.getLogger().warning("Menu canvas unavailable: "+failure.getClass().getSimpleName());return false;} + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/Card.java b/DuneMenus/src/main/java/com/dunerealms/menus/Card.java new file mode 100644 index 00000000..0b58c787 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/Card.java @@ -0,0 +1,10 @@ +package com.dunerealms.menus; + +import java.util.List; + +/** One clickable thing on a menu, in renderer-neutral form (used for Bedrock forms and fullscreen). */ +public record Card(int slot, String title, List lore, String material, boolean enabled) { + public Card(int slot, String title, List lore, String material) { + this(slot, title, lore, material, true); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/ChatPrompt.java b/DuneMenus/src/main/java/com/dunerealms/menus/ChatPrompt.java new file mode 100644 index 00000000..0b225095 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/ChatPrompt.java @@ -0,0 +1,45 @@ +package com.dunerealms.menus; + +import io.papermc.paper.event.player.AsyncChatEvent; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; + +/** One-line text input for Java and Bedrock alike: the next chat line is captured (not broadcast). "cancel" aborts. */ +final class ChatPrompt implements Listener { + private record Request(UUID token,UUID world,Consumer done){} + private static final Map WAIT = new ConcurrentHashMap<>(); + private static final Map ACTIVE = new ConcurrentHashMap<>(); + private final DuneMenusPlugin plugin; + ChatPrompt(DuneMenusPlugin plugin) { this.plugin = plugin; } + + static void ask(Player p, String prompt, Consumer done) { + var request=new Request(UUID.randomUUID(),p.getWorld().getUID(),done); + WAIT.put(p.getUniqueId(),request);ACTIVE.put(p.getUniqueId(),request); + p.sendMessage(Ui.text(prompt + " (type cancel to go back)")); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onChat(AsyncChatEvent e) { + var cb = WAIT.remove(e.getPlayer().getUniqueId()); + if (cb == null) return; + e.setCancelled(true); + String text = PlainTextComponentSerializer.plainText().serialize(e.message()).trim(); + Bukkit.getScheduler().runTask(plugin, () -> { + var player=e.getPlayer(); + if(!ACTIVE.remove(player.getUniqueId(),cb)||!plugin.isEnabled()||!player.isOnline()||!cb.world().equals(player.getWorld().getUID()))return; + cb.done().accept(text.equalsIgnoreCase("cancel") ? null : text); + }); + } + + @EventHandler public void onQuit(PlayerQuitEvent e) { WAIT.remove(e.getPlayer().getUniqueId());ACTIVE.remove(e.getPlayer().getUniqueId()); } + static void clear(){WAIT.clear();ACTIVE.clear();} +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/ClanMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/ClanMenu.java new file mode 100644 index 00000000..4a6aaa7e --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/ClanMenu.java @@ -0,0 +1,42 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** 6 rows. The crest in the middle, a plus-shaped spine of duties, and four diagonal spokes. */ +final class ClanMenu extends Menu { + ClanMenu(DuneMenusPlugin plugin, Player p, Menu parent, String organisationId) { super(plugin, p, parent); this.organisationId = organisationId; } + String id() { return "clan"; } + Skin skin() { return Skin.CLAN; } + String title() { return "House & Clan ยท Hearth"; } + String subtitle() { return "โ€œA House is only as strong as its people.โ€"; } + int rows() { return 6; } + private Backend.Org shown; + private final String organisationId; + + private void spoke(int slot, Material m, String name, String sub, String action) { + put(slot, Ui.item(m, name, "" + sub), t -> act(backend().orgAction(player, "clan", action, shown))); + } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + for (int s : new int[]{13, 21, 23, 31}) put(s, Ui.pane(Material.GREEN_STAINED_GLASS_PANE)); + back(45); + put(43, Ui.item(Material.MAP, "Estate services", "Claims, Home Block and deployment controls"), t -> { end(); plugin.organisationServices(player,"clan",organisationId); }); + put(22, Ui.item(Material.WHITE_BANNER, "Your clan", "Loadingโ€ฆ")); + load(backend().org(player, "clan", organisationId), o -> { + shown = o; + put(22, Ui.glow(Ui.item(Material.WHITE_BANNER, "" + o.name(), + "Role: " + o.role(), "Members: " + o.members(), "Vault: " + (o.vaultMinor() == null ? "Unavailable" : Ui.dm(o.vaultMinor()))))); + }); + put(4, Ui.item(Material.PLAYER_HEAD, "Members", "Your roster"), t -> go(new MembersMenu(plugin, player, this, "clan", organisationId))); + spoke(40, Material.RED_BED, "Clan home", "Teleport to base", "home"); + spoke(20, Material.FILLED_MAP, "Territory", "Claims and borders", "claims"); + spoke(24, Material.ENDER_CHEST, "Vault", "Shared funds", "vault"); + spoke(11, Material.LEAD, "Allies", "Friendly clans", "allies"); + spoke(15, Material.DIAMOND_SWORD, "Wars", "Active conflicts", "wars"); + put(29, Ui.item(Material.IRON_SWORD, "War muster", "Set your team"), t -> go(new WarMenu(plugin, player, this))); + spoke(37, Material.BOOK, "Message of the day", "Read your clan message", "motd"); + spoke(33, Material.WRITABLE_BOOK, "Invite", "Bring someone in", "invite"); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/CompanyMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/CompanyMenu.java new file mode 100644 index 00000000..8cbe8eff --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/CompanyMenu.java @@ -0,0 +1,46 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** 6 rows. Three labelled bands: Finance, People, Operations. Reads left to right like a ledger. */ +final class CompanyMenu extends Menu { + CompanyMenu(DuneMenusPlugin plugin, Player p, Menu parent, String organisationId) { super(plugin, p, parent); this.organisationId = organisationId; } + String id() { return "company"; } + Skin skin() { return Skin.COMPANY; } + String title() { return "Company ยท Ledger Hall"; } + String subtitle() { return "โ€œFortunes are built in ledgers before they are built in stone.โ€"; } + int rows() { return 6; } + private Backend.Org shown; + private final String organisationId; + + private void tool(int slot, Material m, String name, String sub, String action) { + put(slot, Ui.item(m, name, "" + sub), t -> act(backend().orgAction(player, "company", action, shown))); + } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + for (int r = 1; r <= 3; r++) for (int c = 1; c <= 8; c++) put(r * 9 + c, Ui.pane(Material.CYAN_STAINED_GLASS_PANE)); + back(45); + put(43, Ui.item(Material.MAP, "Estate services", "Claims, Home Block and deployment controls"), t -> { end(); plugin.organisationServices(player,"company",organisationId); }); + put(9, Ui.item(Material.GOLD_INGOT, "Finance")); + put(18, Ui.item(Material.PLAYER_HEAD, "People")); + put(27, Ui.item(Material.LIGHTNING_ROD, "Operations")); + put(4, Ui.item(Material.COPPER_BLOCK, "Your company", "Loadingโ€ฆ")); + load(backend().org(player, "company", organisationId), o -> { + shown = o; + put(4, Ui.glow(Ui.item(Material.COPPER_BLOCK, "" + o.name(), "Role: " + o.role(), "Members: " + o.members()))); + put(10, Ui.item(Material.GOLD_INGOT, "Balance", "" + (o.vaultMinor() == null ? "Unavailable" : Ui.dm(o.vaultMinor())))); + }); + tool(11, Material.ENDER_CHEST, "Vault", "Move funds", "vault"); + tool(12, Material.BOOK, "Transactions", "Recent activity", "transactions"); + put(19, Ui.item(Material.PLAYER_HEAD, "Members", "Your team"), t -> go(new MembersMenu(plugin, player, this, "company", organisationId))); + tool(20, Material.NAME_TAG, "Roles", "Who can do what", "roles"); + tool(22, Material.BOOK, "Message of the day", "Read your company message", "motd"); + tool(21, Material.WRITABLE_BOOK, "Invite", "Bring someone in", "invite"); + put(28, Ui.item(Material.EMERALD, "Exchange", "Buy and sell"), t -> go(new ExchangeMenu(plugin, player, this))); + put(29, Ui.item(Material.BLAZE_POWDER, "Spice buyers", "Sell and collect"), t -> go(new SpiceMenu(plugin, player, this))); + tool(30, Material.MINECART, "War transport", "Move your people", "war-transport"); + tool(31, Material.LODESTONE, "Home block", "Claims and deed", "claims"); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java b/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java new file mode 100644 index 00000000..f06a89ee --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java @@ -0,0 +1,237 @@ +package com.dunerealms.menus; + +import org.bukkit.plugin.java.JavaPlugin; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabExecutor; +import org.bukkit.entity.Player; + +public final class DuneMenusPlugin extends JavaPlugin implements TabExecutor { + static final List IDS = List.of("hub", "travel", "exchange", "clan", "company", "missions", + "spice", "war", "mentat", "lore", "politics", "house", "equipment", "bank", "atm", "withdraw"); + private static final String PACK_CONTROL = "dunerealms:pack_control"; + private Backend backend; + void enterRia(Player player,java.util.function.Consumer done){ + ChatPrompt.ask(player,"Type the RIA ID in chat:",text->{ + String reference=RiaReference.normalize(text); + if(text!=null&&reference==null)player.sendMessage(Component.text("That RIA ID is invalid. Use RIA- followed by the complete 32-character reference.")); + done.accept(reference); + }); + } + private NativePresentationRoutes nativePresentationRoutes; + private final Map loadedPacks = new HashMap<>(); + private final Map openMenus = new HashMap<>(); + + void opened(Player player, Menu menu) { + Menu previous = openMenus.put(player.getUniqueId(), menu); + if (previous != null && previous != menu) previous.closed(); + } + + void closed(Player player, Menu menu) { + openMenus.remove(player.getUniqueId(), menu); + } + + boolean hasOpenMenu(Player player, Menu menu) { + return openMenus.get(player.getUniqueId()) == menu; + } + + void dismiss(Player player) { + Menu menu = openMenus.remove(player.getUniqueId()); + if (menu != null) menu.closed(); + } + + @Override + public void onEnable() { + saveDefaultConfig(); + backend = JarvisBackend.create(this); + var messenger = getServer().getMessenger(); + messenger.registerOutgoingPluginChannel(this, PACK_CONTROL); + messenger.registerIncomingPluginChannel(this, PACK_CONTROL, (channel, player, bytes) -> { + if (bytes.length > 52) return; + String message = new String(bytes, java.nio.charset.StandardCharsets.US_ASCII); + if (message.equals("common-sha1 -")) loadedPacks.remove(player); + else if (message.matches("common-sha1 [a-f0-9]{40}")) loadedPacks.put(player, message.substring(12)); + }); + getLogger().info("Backend: " + backend.getClass().getSimpleName()); + getServer().getPluginManager().registerEvents(new MenuListener(this), this); + getServer().getPluginManager().registerEvents(new ChatPrompt(this), this); + if (getConfig().getBoolean("fullscreen.enabled", true)) { + getServer().getServicesManager().register(FullscreenProvider.class, new CanvasProvider(this), this, org.bukkit.plugin.ServicePriority.Normal); + } + getCommand("dm").setExecutor(this); + getCommand("dm").setTabCompleter(this); + nativePresentationRoutes=new NativePresentationRoutes(this); + } + + @Override public void onDisable() { + ChatPrompt.clear(); + if(nativePresentationRoutes!=null)nativePresentationRoutes.close(); + for (Menu menu : List.copyOf(openMenus.values())) menu.closed(); + openMenus.clear(); + getServer().getServicesManager().unregisterAll(this); + getServer().getMessenger().unregisterIncomingPluginChannel(this); + getServer().getMessenger().unregisterOutgoingPluginChannel(this); + } + + Backend backend() { return backend; } + + void openNativeExchange(Player player) { + var gui=getServer().getPluginManager().getPlugin("DunerealmsGUI"); + if(gui!=null&&gui.isEnabled())try{gui.getClass().getMethod("openExchangeMenu",Player.class).invoke(gui,player);return;}catch(ReflectiveOperationException failure){getLogger().warning("Native Exchange entry unavailable: "+failure.getClass().getSimpleName());} + player.sendMessage("The native Exchange service is temporarily unavailable. Please retry later."); + } + + void openNativeService(Player player,String id){ + var gui=getServer().getPluginManager().getPlugin("DunerealmsGUI"); + if(gui!=null&&gui.isEnabled())try{gui.getClass().getMethod("openNativeMenu",Player.class,String.class).invoke(gui,player,id);return;}catch(ReflectiveOperationException failure){getLogger().warning("Native service entry failed: "+id+" / "+failure.getClass().getSimpleName());} + player.sendMessage("The native "+id+" service is temporarily unavailable."); + } + void closeNativePresentation(Player player){var gui=getServer().getPluginManager().getPlugin("DunerealmsGUI");if(gui!=null&&gui.isEnabled())try{gui.getClass().getMethod("closeSuppliedMenu",Player.class).invoke(gui,player);}catch(ReflectiveOperationException failure){getLogger().warning("Native presentation close failed");}} + public boolean show(JavaPlugin owner,Player player,String title,org.bukkit.inventory.Inventory model,Map actions,java.util.function.BooleanSupplier gate){ + if(!getServer().isPrimaryThread()||!owner.isEnabled()||!player.isOnline()||!player.hasPermission("dunemenus.use"))return false; + new LegacyInventoryMenu(this,owner,player,title,model,actions,gate).open();return true; + } + public boolean show(JavaPlugin owner,Player player,String title,org.bukkit.inventory.Inventory model,Map actions){return show(owner,player,title,model,actions,()->true);} + public boolean isCurrent(Player player,org.bukkit.inventory.Inventory model){var menu=openMenus.get(player.getUniqueId());return menu instanceof LegacyInventoryMenu legacy&&legacy.matches(model);} + public void close(Player player,org.bukkit.inventory.Inventory model){var menu=openMenus.get(player.getUniqueId());if(menu instanceof LegacyInventoryMenu legacy&&legacy.matches(model))legacy.finish();} + public boolean showChoices(JavaPlugin owner,Player player,String title,String description,List choices){ + if(choices.size()>54||!getServer().isPrimaryThread())return false; + var model=getServer().createInventory(null,Math.max(9,((choices.size()+8)/9)*9));var actions=new HashMap(); + try{int slot=0;for(Object choice:choices){String label=(String)choice.getClass().getMethod("label").invoke(choice),detail=(String)choice.getClass().getMethod("description").invoke(choice);Runnable action=(Runnable)choice.getClass().getMethod("action").invoke(choice);var item=new org.bukkit.inventory.ItemStack(org.bukkit.Material.PAPER);var meta=item.getItemMeta();meta.displayName(Component.text(label));meta.lore(List.of(Component.text(detail)));item.setItemMeta(meta);model.setItem(slot,item);if(action!=null)actions.put(slot,action);slot++;}}catch(ReflectiveOperationException|ClassCastException failure){getLogger().warning("Native choice contract differs: "+failure.getClass().getSimpleName());return false;} + if(!owner.isEnabled()||!player.isOnline()||!player.hasPermission("dunemenus.use"))return false; + new LegacyInventoryMenu(this,owner,player,title,description,model,actions,()->true).open();return true; + } + + public void openMenu(Player player, String menu) { + if (player.hasPermission("dunemenus.use")) create(menu, player, null).open(); + else player.sendMessage("You do not have permission to open this menu."); + } + + public void presentService(Player player, String section, String title, String description, + org.bukkit.inventory.Inventory inventory, Map actions) { + if (player.hasPermission("dunemenus.use")) + new ServiceMenu(this, player, section, title, description, inventory, actions).open(); + else player.sendMessage("You do not have permission to open this menu."); + } + + void organisationServices(Player player,String kind,String id) { + var services=getServer().getPluginManager().getPlugin("DunerealmsGUI"); + if(services==null||!services.isEnabled())return; + try {services.getClass().getMethod("openOrganisationServices",Player.class,String.class,String.class).invoke(services,player,kind,id);} + catch(ReflectiveOperationException failure){player.sendMessage("Organisation services are temporarily unavailable.");} + } + + public void warObjective(Player player, com.google.gson.JsonObject target, Runnable capture) { + if (!getServer().isPrimaryThread() || !player.isOnline() || !player.hasPermission("dunemenus.use")) return; + new WarObjectiveMenu(this, player, target.deepCopy(), capture).open(); + } + + public void openSharedMenu(Player player, String title, org.bukkit.inventory.Inventory model, Map actions) { + if (!getServer().isPrimaryThread() || !player.isOnline() || !player.hasPermission("dunemenus.use")) return; + String lower=title.toLowerCase(java.util.Locale.ROOT); + String section=lower.contains("smuggler")?"smuggler":lower.contains("travel")||lower.contains("guild")?"travel":lower.contains("exchange")?"exchange":lower.contains("spice")?"spice":lower.contains("quest")?"missions":"hub"; + new ServiceMenu(this,player,section,title,"",model,actions).open(); + } + + void requestPackStatus(Player player) { + if (player.isOnline()) player.sendPluginMessage(this, PACK_CONTROL, + "common-status".getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + } + + void forgetPack(Player player) { loadedPacks.remove(player); } + + boolean itemCardPackLoaded(Player player) { + if(Bedrock.is(player))return false; + var services=getServer().getPluginManager().getPlugin("DunerealmsGUI"); + if(services==null||!services.isEnabled())return false; + try{return Boolean.TRUE.equals(services.getClass().getMethod("menuAssetsLoaded",Player.class).invoke(services,player));} + catch(ReflectiveOperationException failure){return false;} + } + + boolean hasOpenMenu(Player player) { return openMenus.containsKey(player.getUniqueId()); } + + FullscreenProvider fullscreen() { return getServer().getServicesManager().load(FullscreenProvider.class); } + + Menu.Mode modeFor(Player p) { + if (getConfig().getBoolean("bedrock.forms", true) && Bedrock.is(p)) return Menu.Mode.BEDROCK; + return Menu.Mode.FULLSCREEN; + } + + /** Coloured title, optionally led by the DuneRealms logo glyph from the resource pack. */ + Component titleFor(Menu m) { + Component text = Component.text(m.title(), m.skin().color()).decoration(TextDecoration.BOLD, true).decoration(TextDecoration.ITALIC, false); + if (getConfig().getBoolean("resource-pack.logo-in-title", false)) { + return Component.text("๎€€", NamedTextColor.WHITE).font(Key.key(getConfig().getString("resource-pack.font", "dunerealms:menu"))) + .append(Component.text(" ")).append(text); + } + return Component.text("โ—† ", m.skin().color()).append(text); + } + + Menu create(String id, Player p, Menu parent) { + if(NativeServiceMenu.IDS.contains(id.toLowerCase(java.util.Locale.ROOT)))return new NativeServiceMenu(this,p,parent,id.toLowerCase(java.util.Locale.ROOT)); + return switch (id.toLowerCase()) { + case "travel" -> new TravelMenu(this, p, parent); + case "exchange" -> new ExchangeMenu(this, p, parent); + case "clan" -> new OrganisationChoiceMenu(this, p, parent, "clan"); + case "company" -> new OrganisationChoiceMenu(this, p, parent, "company"); + case "missions" -> new MissionsMenu(this, p, parent); + case "spice" -> new SpiceMenu(this, p, parent); + case "war" -> new WarMenu(this, p, parent); + case "politics" -> new PoliticsMenu(this, p, parent); + case "lore" -> new LoreArchiveMenu(this, p, parent); + case "mentat" -> new MentatMenu(this, p, parent); + case "house" -> new HouseMenu(this, p, parent); + case "equipment" -> new EquipmentMenu(this, p, parent); + case "bank" -> new BankMenu(this, p, parent); + case "atm" -> new AtmMenu(this, p, parent, AtmMenu.Tab.HOME); + case "withdraw" -> new AtmMenu(this, p, parent, AtmMenu.Tab.WITHDRAW); + default -> new HubMenu(this, p); + }; + } + + @Override + public boolean onCommand(CommandSender s, Command c, String l, String[] a) { + if (!c.getName().equals("dm")) return false; + if (a.length > 0 && a[0].equalsIgnoreCase("reload")) { + if (!s.hasPermission("dunemenus.admin")) { s.sendMessage("No permission."); return true; } + reloadConfig(); + s.sendMessage("DuneMenus config reloaded. (Backend changes need a restart.)"); + return true; + } + if (!(s instanceof Player p)) { s.sendMessage("Players only."); return true; } + if (!p.hasPermission("dunemenus.use")) { p.sendMessage("No permission."); return true; } + if (a.length == 1 && a[0].equalsIgnoreCase("item")) { + p.sendMessage(backend().claimCodex(p).message()); + return true; + } + if (a.length > 0 && a[0].equalsIgnoreCase("previewitem")) { + try { + if (a.length != 3) throw new IllegalArgumentException(); + var id = java.util.UUID.fromString(a[1]); + int revision = Integer.parseInt(a[2]); + if (revision < 1 || revision > 999999) throw new IllegalArgumentException(); + new SavedItemMenu(this, p, id, revision).open(); + } catch (IllegalArgumentException invalid) { + p.sendMessage("Use /dm previewitem ."); + } + return true; + } + create(a.length == 0 ? "hub" : a[0], p, null).open(); + return true; + } + + @Override + public List onTabComplete(CommandSender s, Command c, String l, String[] a) { + if (a.length != 1) return List.of(); + return java.util.stream.Stream.concat(IDS.stream(), java.util.stream.Stream.of("reload", "cookbook")) + .filter(x -> x.startsWith(a[0].toLowerCase())).toList(); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/EquipmentMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/EquipmentMenu.java new file mode 100644 index 00000000..86dc6617 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/EquipmentMenu.java @@ -0,0 +1,28 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** 3 rows. Left to right: your item, what it needs, the result. Click the result to refit at once. */ +final class EquipmentMenu extends Menu { + EquipmentMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); } + String id() { return "equipment"; } + Skin skin() { return Skin.FORGE; } + String title() { return "Quartermaster ยท Refit"; } + String subtitle() { return "โ€œGood gear can be made whole again.โ€"; } + int rows() { return 3; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + for (int s : new int[]{11, 12, 14, 15}) put(s, Ui.pane(Material.LIGHT_BLUE_STAINED_GLASS_PANE)); + back(18); + load(backend().refitQuote(player), q -> { + put(10, Ui.item(q.icon(), "" + q.itemName(), "Your original item")); + put(13, Ui.item(Material.IRON_INGOT, "Needs", q.costs().stream().map(c -> "" + c).toArray(String[]::new))); + if (q.possible()) + put(16, Ui.glow(Ui.item(Material.SMITHING_TABLE, "Refit now", "" + q.note())), t -> act(backend().refit(player,q))); + else + put(16, Ui.item(Material.BARRIER, "Can't refit yet", "" + q.note())); + }); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/ExchangeMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/ExchangeMenu.java new file mode 100644 index 00000000..a5bf02f2 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/ExchangeMenu.java @@ -0,0 +1,9 @@ +package com.dunerealms.menus; +import org.bukkit.entity.Player; +/** Every public menu entry uses the already working native Exchange flow. */ +final class ExchangeMenu extends Menu { + ExchangeMenu(DuneMenusPlugin plugin,Player player,Menu parent){super(plugin,player,parent);} + @Override boolean launchNative(){plugin.openNativeExchange(player);return true;} + String id(){return "exchange";}Skin skin(){return Skin.MARKET;}String title(){return "Exchange";}int rows(){return 6;} + void draw(){throw new IllegalStateException("Exchange must use the native service");} +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/FullscreenProvider.java b/DuneMenus/src/main/java/com/dunerealms/menus/FullscreenProvider.java new file mode 100644 index 00000000..654c6408 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/FullscreenProvider.java @@ -0,0 +1,14 @@ +package com.dunerealms.menus; + +import java.util.List; +import java.util.function.IntConsumer; +import org.bukkit.entity.Player; + +/** Presentation contract for the supplied painted menu provider. */ +public interface FullscreenProvider { + record Screen(String id, String title, String subtitle, List cards, List info, + org.bukkit.inventory.ItemStack[] contents) {} + + /** Server thread. Call exactly one of select / close later, never inside open(). */ + boolean open(Player viewer, Screen screen, IntConsumer select, Runnable close); +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/HouseMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/HouseMenu.java new file mode 100644 index 00000000..e673ce72 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/HouseMenu.java @@ -0,0 +1,28 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** 3 rows. Five Houses arranged as a pentagon. One click declares allegiance. */ +final class HouseMenu extends Menu { + private static final int[] DAIS = {4, 11, 15, 20, 24}; + + HouseMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); } + String id() { return "house"; } + Skin skin() { return Skin.HOUSE; } + String title() { return "Choose your House"; } + String subtitle() { return "โ€œEvery story begins with a banner.โ€"; } + int rows() { return 3; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + back(18); + load(backend().houses(player), houses -> { + for (int i = 0; i < Math.min(DAIS.length, houses.size()); i++) { + var h = houses.get(i); + put(DAIS[i], Ui.item(h.banner(), "<#eed49a>" + h.name(), "" + h.motto(), "", "Click to join"), + t -> load(backend().chooseHouse(player, h), r -> { say(r); end(); })); + } + }); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/HubMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/HubMenu.java new file mode 100644 index 00000000..f65e884b --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/HubMenu.java @@ -0,0 +1,41 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** 4 rows. The House crest on top, two rows of doors, and the Postbank and ATM at the bottom. */ +final class HubMenu extends Menu { + HubMenu(DuneMenusPlugin plugin, Player p) { super(plugin, p, null); } + String id() { return "hub"; } + Skin skin() { return Skin.GOLD; } + String title() { return "Dune Realms"; } + String subtitle() { return "โ€œThe caravan endures. Where will you lead it?โ€"; } + int rows() { return 4; } + + private void door(int slot, Material m, String name, String sub, String menu) { + put(slot, Ui.item(m, name, "" + sub), t -> go(plugin.create(menu, player, this))); + } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + for (int i = 0; i < 9; i += 2) put(i, Ui.pane(Material.CYAN_STAINED_GLASS_PANE)); // holo strip + door(4, Material.WHITE_BANNER, "<#eed49a>Your House", "Allegiance and your Mentat", "house"); + put(8, Ui.item(Material.TOTEM_OF_UNDYING, "Emergency rescue", "Instant teleport and heal ยท 1,000 DM ยท 24 hours"), + click -> { + end(); + if (!player.performCommand("duneess:rescue")) player.sendMessage("Emergency rescue is temporarily unavailable."); + }); + door(10, Material.COMPASS, "<#7fd6e8>Travel", "Imperial Guild passage", "travel"); + door(12, Material.EMERALD, "<#f2c94c>Exchange", "Buy and sell", "exchange"); + door(14, Material.WRITABLE_BOOK, "<#9fc27a>Missions", "Your journal", "missions"); + door(16, Material.ANVIL, "<#7fb2d9>Equipment", "Refit your gear", "equipment"); + door(19, Material.GREEN_BANNER, "<#4fbf8a>Clan", "Your people", "clan"); + door(21, Material.COPPER_BLOCK, "<#5cc8d6>Company", "Your business", "company"); + door(23, Material.LECTERN, "<#b07ce8>Politics", "Decisions of your office", "politics"); + door(25, Material.BLAZE_POWDER, "<#e07b2e>Spice", "Sell and collect", "spice"); + door(28, Material.PLAYER_HEAD, "<#eed49a>Your Mentat", "House briefing and missions", "mentat"); + door(29, Material.GOLD_BLOCK, "<#f2c94c>Imperial Postbank", "Your account", "bank"); + door(31, Material.BOOK, "<#eed49a>Cookbook", "Crafting recipes and grades", "cookbook"); + door(33, Material.LIGHTNING_ROD, "<#7fd6e8>ATM", "Quick deposit and withdrawal", "atm"); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/JarvisBackend.java b/DuneMenus/src/main/java/com/dunerealms/menus/JarvisBackend.java new file mode 100644 index 00000000..c2030721 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/JarvisBackend.java @@ -0,0 +1,1192 @@ +package com.dunerealms.menus; + +import com.dunerealms.jarvis.DunemarkDenomination; +import com.dunerealms.jarvis.JarvisTranslator; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import net.kyori.adventure.text.minimessage.MiniMessage; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +import org.bukkit.inventory.ItemStack; + +final class JarvisBackend implements Backend, Listener { + private final DuneMenusPlugin plugin; + private final JarvisTranslator jarvis; + private final Set pending = new HashSet<>(); + private final Map rihlaSends = new HashMap<>(); + private final Map retries = new HashMap<>(); + private final Map guildBookings = new HashMap<>(); + private final Map refitPermits = new HashMap<>(); + private final Map warDrafts = new HashMap<>(); + + private record RihlaSend(UUID recipient, long minor, UUID reference) {} + private record Purchase(Listing offer, int amount, UUID reference) {} + private record RefitPermit(UUID quoteId, UUID world, JsonObject request, JsonObject plan, long deadline) {} + private record WarDraft(UUID token, JsonObject snapshot, List selected) {} + @FunctionalInterface private interface Call { + T run() throws Exception; + } + + private JarvisBackend(DuneMenusPlugin plugin, JarvisTranslator jarvis) { + this.plugin = plugin; + this.jarvis = jarvis; + Bukkit.getPluginManager().registerEvents(this,plugin); + } + + static Backend create(DuneMenusPlugin plugin) { + var bridge = Bukkit.getPluginManager().getPlugin("JarvisTranslator"); + if (bridge instanceof JarvisTranslator jarvis && jarvis.isEnabled()) return new JarvisBackend(plugin, jarvis); + plugin.getLogger().warning("J.A.R.V.I.S. is unavailable. Menu actions are disabled."); + return new Backend() {}; + } + + private CompletableFuture remote(Player player, Call call) { + if (!Bukkit.isPrimaryThread() || !player.isOnline() || !jarvis.isEnabled()) + return CompletableFuture.failedFuture(new Unavailable()); + UUID world = player.getWorld().getUID(); + var future = new CompletableFuture(); + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + try { + T value = call.run(); + Bukkit.getScheduler().runTask(plugin, () -> { + if (player.isOnline() && world.equals(player.getWorld().getUID())) future.complete(value); + else future.completeExceptionally(new Unavailable()); + }); + } catch (Exception failure) { + Bukkit.getScheduler().runTask(plugin, () -> future.completeExceptionally(failure)); + } + }); + return future; + } + + private CompletableFuture once(Player player, Call> callback) { + UUID id = player.getUniqueId(); + if (!pending.add(id)) return CompletableFuture.completedFuture(Result.no("J.A.R.V.I.S. is processing your action.")); + try { + return callback.run().whenComplete((value, error) -> pending.remove(id)); + } catch (Exception failure) { + pending.remove(id); + return CompletableFuture.failedFuture(failure); + } + } + + @Override public CompletableFuture atmCreateRia(Player player,List pieces) { + var request=action("cash_prepare"); + request.addProperty("direction","deposit"); + try { + request.add("pieces",jarvis.rihlaDepositPieces(player,pieces)); + } catch(IllegalArgumentException missing) { + // Allow recovery before checking the inventory again. A prior attempt may already have removed the pieces. + request.addProperty("localError",missing.getMessage()); + } + return cashAction(player,request).thenApply(row->{ + String voucher=number(row,"voucher"); + var result=cashResult(row); + return new Issued(result.ok()&&!voucher.isEmpty(),result.message(),voucher,result.receipt()); + }); + } + + @Override public CompletableFuture bankWithdraw(Player player,List pieces) { + var request=action("cash_prepare"); + request.addProperty("direction","withdraw"); + request.add("pieces",denominations(pieces)); + return cashAction(player,request).thenApply(JarvisBackend::cashResult); + } + + @Override public CompletableFuture atmRecentDeposit(Player player) { + UUID actor=player.getUniqueId(); + return remote(player,()->number(accepted(jarvis.requestRihla(actor,action("cash_recent_deposit"))),"voucher")); + } + + @Override public CompletableFuture atmLookup(Player player,String code) { + UUID actor=player.getUniqueId(); + return remote(player,()->{ + var request=action("cash_lookup"); + request.addProperty("voucher",code); + var row=accepted(jarvis.requestRihla(actor,request)); + String voucher=number(row,"voucher"); + if(!voucher.equals(code))throw new IOException("Rihla voucher changed."); + return new Voucher(voucher,money(row,"amountMinor"),"Dunemark cash"); + }); + } + + @Override public CompletableFuture atmRedeem(Player player,Voucher voucher,boolean toBank) { + if(toBank){ + UUID actor=player.getUniqueId(); + return once(player,()->remote(player,()->{ + var request=action("cash_redeem_bank"); + request.addProperty("voucher",voucher.riaId()); + request.addProperty("requestId",UUID.randomUUID().toString()); + var row=accepted(jarvis.requestRihla(actor,request)); + long amount=money(row,"amountMinor"); + return new Result(true,"Credited "+Ui.dm(amount)+" to your Postbank account.",new CashReceipt(amount,voucher.riaId(),false)); + })); + } + var pieces=change(voucher.amountMinor()); + if(pieces.isEmpty())return CompletableFuture.completedFuture(Result.no("This voucher does not fit in one inventory.")); + var request=action("cash_redeem_cash"); + request.addProperty("direction","withdraw"); + request.addProperty("voucher",voucher.riaId()); + request.add("pieces",denominations(pieces)); + return cashAction(player,request).thenApply(JarvisBackend::cashResult); + } + + private CompletableFuture cashAction(Player player,JsonObject request) { + UUID actor=player.getUniqueId(); + if(!pending.add(actor))return CompletableFuture.failedFuture(new IOException("Your earlier Rihla action is still processing.")); + return remote(player,()->{ + var prior=accepted(jarvis.requestRihla(actor,action("cash_pending"))); + if(yes(prior,"pending"))return prior; + if(request.has("localError"))return request; + request.addProperty("requestId",UUID.randomUUID().toString()); + return accepted(jarvis.requestRihla(actor,request)); + }).thenCompose(permit->{ + if(permit.has("localError"))return CompletableFuture.completedFuture(permit); + if(permit.has("action")){ + try { + jarvis.checkpointRihlaCash(player,permit); + } catch(Exception failure){ + // A committed proof can survive a disconnection or an uncertain native response. + } + } + return remote(player,()->{ + var settle=action("cash_settle"); + settle.addProperty("requestId",text(permit,"requestId")); + var result=accepted(jarvis.requestRihla(actor,settle)); + if(yes(permit,"pending"))result.addProperty("recovered",true); + return result; + }); + }).whenComplete((value,error)->pending.remove(actor)); + } + + private static JsonArray denominations(List pieces) { + var result=new JsonArray(); + for(var piece:pieces)result.add(piece.id()); + return result; + } + + static List change(long minor) { + var all=java.util.Arrays.stream(DunemarkDenomination.values()).filter(DunemarkDenomination::isCirculating) + .sorted(java.util.Comparator.comparingLong(DunemarkDenomination::faceMinor).reversed()).toList(); + var result=new ArrayList(); + for(var denomination:all){ + long count=minor/denomination.faceMinor(); + if(count>36-result.size())return List.of(); + for(long i=0;i balance(Player player) { + return bankAccount(player).thenApply(account -> { + if(account.postbankAvailableMinor()==null)throw new Unavailable(); + return account.postbankAvailableMinor(); + }); + } + + @Override public CompletableFuture bankAccount(Player player) { + UUID actor=player.getUniqueId(); + return remote(player,()->{ + var state=accepted(jarvis.requestRihla(actor,action("read"))); + return new Account(text(state,"accountNo"),text(state,"availableMinor").isBlank()?null:money(state,"availableMinor"), + money(state,"reservedMinor"),money(state,"collectableMinor")); + }); + } + + @Override public CompletableFuture> bankTransfers(Player player) { + UUID actor=player.getUniqueId(); + return remote(player,()->{ + var state=accepted(jarvis.requestRihla(actor,action("read"))); + var history=new ArrayList(); + for(var value:array(state,"transfers")){ + var row=value.getAsJsonObject(); + if(!text(row,"state").equals("created"))continue; + var direction=switch(text(row,"direction")){ + case "sent" -> "OUT"; + case "received" -> "IN"; + default -> throw new IOException("Invalid Rihla transfer direction."); + }; + var date=Instant.ofEpochMilli(row.get("createdAt").getAsLong()).toString().substring(0,10); + history.add(new Transfer(text(row,"number"),direction,display(row,"counterparty"), + money(row,"amountMinor"),money(row,"taxMinor"),date)); + } + return List.copyOf(history); + }); + } + + @Override public CompletableFuture bankSend(Player player,UUID recipient,long amountMinor) { + UUID actor=player.getUniqueId(); + if(amountMinor<=0||amountMinor>Long.MAX_VALUE/10)return CompletableFuture.completedFuture(Result.no("Invalid Rihla amount.")); + return once(player,()->{ + RihlaSend request=rihlaSends.computeIfAbsent(actor,id->new RihlaSend(recipient,amountMinor,UUID.randomUUID())); + if(!request.recipient().equals(recipient)||request.minor()!=amountMinor) + return CompletableFuture.completedFuture(Result.no("Retry the previous Rihla amount and recipient first.")); + return remote(player,()->{ + var quote=action("quote"); + quote.addProperty("recipientUuid",recipient.toString()); + quote.addProperty("amount",java.math.BigDecimal.valueOf(amountMinor,2).toPlainString()); + var terms=jarvis.requestRihla(actor,quote); + if(terms.has("rejectedStatus"))return Result.no(reason(terms)); + if(money(terms,"amountMinor")!=amountMinor||money(terms,"taxMinor")!=Rihla.tax(amountMinor)|| + money(terms,"totalMinor")!=Rihla.total(amountMinor)) + return Result.no("The centrally quoted terms changed. Reopen the Rihla menu."); + var submit=quote.deepCopy(); + submit.addProperty("action","create"); + submit.addProperty("requestId",request.reference().toString()); + submit.addProperty("quoteReference",text(terms,"quoteReference")); + var response=jarvis.requestRihla(actor,submit); + if(response.has("rejectedStatus"))return Result.no(reason(response)); + return Result.yes("Rihla transfer "+text(response,"number")+" ยท "+text(response,"state")+"."); + }).thenApply(result->{ + rihlaSends.remove(actor,request); + return result; + }); + }); + } + + @Override public CompletableFuture bankCancel(Player player,String number) { + return rihlaTransfer(player,"cancel",number); + } + + @Override public CompletableFuture bankCollect(Player player,String number) { + return rihlaTransfer(player,number==null?"collectAll":"collect",number); + } + + private CompletableFuture rihlaTransfer(Player player,String operation,String number) { + UUID actor=player.getUniqueId(); + return once(player,()->remote(player,()->{ + var request=action(operation); + if(number!=null)request.addProperty("number",number); + var response=jarvis.requestRihla(actor,request); + if(response.has("rejectedStatus"))return Result.no(reason(response)); + if(operation.equals("collectAll")){ + int collected=response.get("collected").getAsInt(),failed=response.get("failed").getAsInt(); + return new Result(failed==0,"Collected "+collected+" Rihla transfer(s)."+ + (failed>0?" "+failed+" could not be settled.":"")+(yes(response,"hasMore")?" More transfers are waiting.":"")); + } + return Result.yes("Rihla transfer "+text(response,"number")+" ยท "+text(response,"state")+"."); + })); + } + + private static long money(JsonObject data,String key) { + return Long.parseLong(text(data,key)); + } + + @Override public List loreArchive() { + return List.of( + loreSample("MENU", Material.COMPASS, "Imperial Codex", Map.of("Service","DuneRealms")), + loreSample("EQUIPMENT", Material.IRON_SWORD, "Equipment", Map.of("Grade","From the issued equipment key")), + loreSample("KIT", Material.CHEST, "Equipment seal", Map.of("Contents","From the registered kit")), + loreSample("COMPONENT", Material.AMETHYST_SHARD, "Crafting component", Map.of("Recipe","From the crafting definition")), + loreSample("TICKET", Material.PAPER, "Guild passage", Map.of("Route","From the issued passage")), + loreSample("CASH", Material.GOLD_NUGGET, "Dunemark", Map.of("Value","From the verified cash denomination")), + loreSample("RIHLA", Material.WRITABLE_BOOK, "Rihla transfer", Map.of("Amount","From the private transfer record")), + loreSample("DEED", Material.MAP, "Registered deed", Map.of("Holder","From current deed authority")), + loreSample("QUEST", Material.BOOK, "Mission instrument", Map.of("Progress","From verified events")) + ); + } + + private ItemStack loreSample(String kind, Material material, String name, Map facts) { + return jarvis.formatItemLore(new ItemStack(material),kind,name,"Design preview. Not a redeemable instrument.",facts,null,null); + } + + @Override public Result claimCodex(Player player) { + var inventory=player.getInventory(); + for(var item:inventory.getContents()){ + if(MenuListener.isCodex(item))return Result.yes("Your Imperial Codex is already in your inventory."); + } + int slot=inventory.firstEmpty(); + if(slot<0)return Result.no("Make room for the Imperial Codex first."); + try{ + var item=jarvis.menuItem(player); + inventory.setItem(slot,item); + try{jarvis.announceItemInventory(player,item,slot);} + catch(ReflectiveOperationException unavailable){plugin.getLogger().warning("Imperial Codex item-engine notification unavailable.");} + return Result.yes("Imperial Codex received. Right-click to open the menu."); + }catch(ReflectiveOperationException|RuntimeException unavailable){ + return Result.no("The Imperial Codex is temporarily unavailable. Use /dm."); + } + } + + @Override public CompletableFuture mentat(Player player) { + UUID owner=player.getUniqueId(); + return remote(player,()->{ + var briefing=accepted(jarvis.requestHouse(owner,null,0,null)); + if(text(briefing,"selection").isBlank())return ""; + var adviser=briefing.getAsJsonObject("mentat"); + return adviser==null?"":display(adviser,"name"); + }); + } + + @Override public CompletableFuture savedItem(Player player, UUID id, int revision) { + UUID owner=player.getUniqueId(); + plugin.requestPackStatus(player); + return remote(player,()->accepted(jarvis.requestItemPreview(owner,id,revision))) + .thenApply(view->jarvis.buildItemPreview(player,view,plugin.itemCardPackLoaded(player))); + } + + @Override public boolean inGuildLobby(Player player) { return guildLobby(player); } + + @Override public Result returnToGuild(Player player) { + if (guildLobby(player)) return Result.no("You are already in the Guild lobby."); + jarvis.returnGuild(player); + return Result.yes("Guild return requested."); + } + + @Override public CompletableFuture> worlds(Player player) { + if (!guildLobby(player)) return CompletableFuture.failedFuture(new Unavailable()); + UUID owner = player.getUniqueId(); + return remote(player, () -> { + var house = accepted(jarvis.requestHouse(owner,null,0,null)); + var quote = accepted(jarvis.requestGuild(owner,action("quote"))); + var worlds = new ArrayList(); + String key = text(house,"keyId"); + int version = house.has("version") && !house.get("version").isJsonNull() ? house.get("version").getAsInt() : 0; + var allowed = new HashSet(); + for (var destination : array(quote,"destinations")) allowed.add(destination.getAsString()); + var catalog = new HashMap(); + for (var route : array(quote,"routes")) if (route.isJsonObject()) { + var row = route.getAsJsonObject(); + catalog.putIfAbsent(text(row,"server"), row); + } + for (var route : List.of(Map.entry("caladan","Kaladam"), Map.entry("giedi_prime","Giedermark"), + Map.entry("kaitain","Kaiterhof"), Map.entry("sigma_draconis_iv","Sigmadraken IV"), + Map.entry("arrakis","Arrakduin"))) { + String id = route.getKey(); + var offer = catalog.get(id); + String unavailable = yes(quote,"prologueRequired") ? "Complete your House Prologue" + : key.isBlank() || version <= 0 ? "Confirm your current House key" + : offer != null && !yes(offer,"available") ? text(offer,"reason") + : offer == null && !allowed.contains(id) ? "This route is unavailable under your current Guild passage" + : !yes(quote,"affordable") ? "Insufficient available funds in your personal account" + : !jarvis.worldOnline(id) ? "This world is currently offline" : null; + if (unavailable!=null && unavailable.isBlank()) unavailable="Passage unavailable"; + String name=offer!=null&&!text(offer,"name").isBlank()?text(offer,"name"):route.getValue(); + long fare=offer!=null&&offer.has("fareMinor")?offer.get("fareMinor").getAsLong():quote.get("fareMinor").getAsLong(); + String tagline = unavailable != null ? unavailable + : offer != null && offer.has("bountyMinor") ? "Unsanctioned arrival: " + Ui.dm(offer.get("bountyMinor").getAsLong()) + " bounty" + (yes(offer,"reduced") ? " (clan/company discount)" : "") + : offer != null && yes(offer,"free") ? "Free passage" : "Imperial Guild passage"; + worlds.add(new World(id, name, tagline, + Material.COMPASS, -1, unavailable == null, fare, key, version)); + } + return List.copyOf(worlds); + }); + } + + @Override public CompletableFuture book(Player player, World destination) { + UUID owner = player.getUniqueId(); + UUID reference = UUID.randomUUID(); + if (!guildLobby(player) || !destination.up() || guildBookings.putIfAbsent(owner,reference) != null) + return CompletableFuture.completedFuture(Result.no("Passage is unavailable or you already have a booking.")); + long now = Instant.now().getEpochSecond(); + long cycle = Math.floorMod(now,1200); + long departure = cycle < 300 ? now : now + 1200 - cycle; + Bukkit.getScheduler().runTaskLater(plugin, () -> { + if (!reference.equals(guildBookings.get(owner))) return; + if (!guildLobby(player) || Math.floorMod(Instant.now().getEpochSecond(),1200) >= 300 || + Math.floorDiv(Instant.now().getEpochSecond(),1200) != Math.floorDiv(departure,1200)) { + guildBookings.remove(owner,reference); + if (player.isOnline()) player.sendMessage("Guild boarding expired or you left the Guild."); + return; + } + var query = action("board"); + query.addProperty("destination",destination.id()); + query.addProperty("fareMinor",destination.fareMinor()); + query.addProperty("keyId",destination.keyId()); + query.addProperty("version",destination.version()); + query.addProperty("requestId",reference.toString()); + remote(player, () -> { + if (!jarvis.worldOnline(destination.id())) throw new IOException("Destination unavailable."); + return accepted(jarvis.requestGuild(owner,query)); + }).whenComplete((ticket,error) -> { + if (!guildBookings.remove(owner,reference) || !guildLobby(player)) return; + if (error != null) { player.sendMessage("Guild passage could not be confirmed. Request a fresh fare."); return; } + try { jarvis.dispatchGuild(player,ticket); } + catch (Exception failure) { player.sendMessage("Passage was not dispatched. Unused reservations expire."); } + }); + },Math.max(1,(departure-now)*20)); + return CompletableFuture.completedFuture(Result.yes("Passage booked. Fare is collected after arrival.")); + } + + @EventHandler public void leaveGuild(PlayerChangedWorldEvent event) { + guildBookings.remove(event.getPlayer().getUniqueId()); + refitPermits.remove(event.getPlayer().getUniqueId()); + warDrafts.remove(event.getPlayer().getUniqueId()); + } + + @EventHandler public void disconnect(PlayerQuitEvent event) { + guildBookings.remove(event.getPlayer().getUniqueId()); + refitPermits.remove(event.getPlayer().getUniqueId()); + warDrafts.remove(event.getPlayer().getUniqueId()); + } + + private static boolean guildLobby(Player player) { + return player.isOnline() && player.getWorld().getName().equals("guild_lobby"); + } + + @Override public CompletableFuture spice(Player player) { + if (!arrakis(player)) return CompletableFuture.failedFuture(new Unavailable()); + int guild = jarvis.spiceCount(player,"guild"), smuggler = jarvis.spiceCount(player,"smuggler"); + UUID owner = player.getUniqueId(); + return remote(player, () -> { + var settings = accepted(jarvis.requestSpice(owner,action("read"))); + var pendingSales = accepted(jarvis.requestSpice(owner,action("pending"))); + boolean account = yes(settings,"hasAccount"); + return new Spice(guild,guild,smuggler,account&&guild>0, + account&&smuggler>0&&yes(settings,"smugglerEnabled"),array(pendingSales,"pending").size()); + }); + } + + @Override public CompletableFuture sellSpice(Player player, String channel, int shownCount) { + return once(player, () -> { + if (!arrakis(player) || !Set.of("guild","smuggler").contains(channel) || shownCount < 1 || + jarvis.spiceCount(player,channel) != shownCount) + return CompletableFuture.completedFuture(Result.no("Your spice inventory or buyer changed.")); + UUID owner = player.getUniqueId(), reference = UUID.randomUUID(); + var query = action("prepare"); + query.addProperty("requestId",reference.toString()); + query.addProperty("channel",channel); + query.addProperty("amount",shownCount); + query.addProperty("confirmed",true); + return remote(player, () -> accepted(jarvis.requestSpice(owner,query))).thenCompose(permit -> { + if (!arrakis(player) || jarvis.spiceCount(player,channel) != shownCount) + return CompletableFuture.completedFuture(Result.no("Your spice inventory changed. Reopen the menu.")); + try { jarvis.sellSpice(player,permit); } + catch (Exception failure) { return CompletableFuture.completedFuture(Result.no("Spice sale was not confirmed.")); } + return remote(player, () -> { + var receipt = settleSpice(owner,reference.toString()); + return Result.yes("Sold "+receipt.get("amount").getAsInt()+" Melange Spice. P&O paid "+ + Ui.dm(receipt.get("netMinor").getAsLong())+"."); + }); + }); + }); + } + + @Override public CompletableFuture collectSpice(Player player) { + if (!arrakis(player)) return CompletableFuture.failedFuture(new Unavailable()); + UUID owner = player.getUniqueId(); + return once(player, () -> remote(player, () -> { + var rows = array(accepted(jarvis.requestSpice(owner,action("pending"))),"pending"); + for (var row : rows) settleSpice(owner,row.getAsString()); + return Result.yes(rows.isEmpty() ? "No spice payments are waiting." : "Pending spice payments processed."); + })); + } + + private JsonObject settleSpice(UUID owner, String reference) throws Exception { + var query = action("settle"); + query.addProperty("requestId",reference); + return accepted(jarvis.requestSpice(owner,query)); + } + + private static boolean arrakis(Player player) { + return player.isOnline() && player.getWorld().getName().equals("arrakis") && + player.getWorld().getEnvironment() == org.bukkit.World.Environment.NORMAL; + } + + @Override public CompletableFuture listings(Player player, String tab, int page) { + if (!Set.of("buy", "kits", "mine").contains(tab) || page < 0) + return CompletableFuture.failedFuture(new IllegalArgumentException("Invalid Exchange page.")); + var input = action(tab.equals("kits") ? "read_kits" : "read"); + input.addProperty("page", page); + if (!tab.equals("kits")) input.addProperty("mine", tab.equals("mine")); + UUID id = player.getUniqueId(); + return remote(player, () -> accepted(jarvis.requestExchange(id, input))).thenApply(data -> { + var items = new ArrayList(); + for (var entry : array(data, "listings")) { + var row = entry.getAsJsonObject(); + boolean kit = tab.equals("kits"); + try { + var item = kit ? Material.NETHERITE_CHESTPLATE : jarvis.exchangeIcon(row).getType(); + items.add(new Listing(text(row, kit ? "kitsetId" : "id"), display(row,"title"), item, display(row,"seller"), + row.get("priceMinor").getAsLong(), kit ? 1 : row.get("quantity").getAsInt(), + kit ? row.get("listingVersion").getAsInt() : null, !kit || yes(row,"purchaseAvailable"))); + } catch (RuntimeException invalid) { + plugin.getLogger().warning("Skipped an unsupported Exchange listing"); + } + } + return new Page(List.copyOf(items), yes(data,"hasNext")); + }); + } + + @Override public CompletableFuture buy(Player player, Listing offer, int quantity) { + UUID id = player.getUniqueId(); + return once(player, () -> { + if (!offer.purchasable() || quantity < 1 || quantity > offer.quantity() || offer.priceMinor() < 1) + return CompletableFuture.completedFuture(Result.no("This offer is unavailable.")); + var purchase = retries.computeIfAbsent(id, ignored -> new Purchase(offer, quantity, UUID.randomUUID())); + if (!purchase.offer().equals(offer) || purchase.amount() != quantity) + return CompletableFuture.completedFuture(Result.no("Retry the same listing and quantity before starting a new purchase.")); + var query = purchaseRequest(offer, quantity, purchase.reference()); + return remote(player, () -> jarvis.requestExchange(id, query)).thenApply(response -> { + retries.remove(id); + if (response.has("rejectedStatus")) return Result.no(reason(response)); + try { + if (offer.kitVersion() == null) jarvis.exchangeDeliver(player); + else jarvis.refreshKits(player); + } catch (Exception unavailable) { + return Result.yes("Purchase paid. Delivery remains queued."); + } + return Result.yes("Purchase paid."); + }); + }); + } + + @Override public CompletableFuture sell(Player player, ItemStack expected, int slot, long priceMinor) { + return once(player, () -> { + var held = expected.clone(); + if (held.isEmpty() || slot != player.getInventory().getHeldItemSlot() || + !held.equals(player.getInventory().getItemInMainHand()) || priceMinor < 1 || priceMinor > 100_000_000) + return CompletableFuture.completedFuture(Result.no("Hold a valid listing item and choose a valid price.")); + int amount = Math.min(64, held.getAmount()); + UUID owner = player.getUniqueId(), reference = UUID.randomUUID(); + var query = action("prepare_sale"); + query.addProperty("requestId", reference.toString()); + query.addProperty("amount", amount); + query.addProperty("priceMinor", priceMinor); + return remote(player, () -> accepted(jarvis.requestExchange(owner, query))).thenApply(permit -> { + try { + jarvis.exchangePublish(player, permit, reference, held, slot, amount, priceMinor); + return Result.yes("Listing published."); + } catch (Exception failure) { + return Result.no("The listing was not confirmed."); + } + }); + }); + } + + @Override public CompletableFuture withdraw(Player player, Listing offer) { + return once(player, () -> { + if (offer.kitVersion() != null || !offer.id().matches("[1-9][0-9]{0,18}")) + return CompletableFuture.completedFuture(Result.no("This listing cannot be withdrawn here.")); + long id = Long.parseLong(offer.id()); + UUID owner = player.getUniqueId(), reference = UUID.randomUUID(); + var query = action("prepare_cancel"); + query.addProperty("requestId", reference.toString()); + return remote(player, () -> accepted(jarvis.requestExchange(owner, query))).thenApply(permit -> { + try { + return Result.yes("Returned " + jarvis.exchangeCancel(player, permit, reference, id) + " items."); + } catch (Exception failure) { + return Result.no("Withdrawal was not confirmed."); + } + }); + }); + } + + @Override public CompletableFuture collectPurchases(Player player) { + return once(player, () -> CompletableFuture.completedFuture( + Result.yes("Collected " + jarvis.exchangeDeliver(player) + " items."))); + } + + @Override public CompletableFuture> missions(Player player) { + UUID owner = player.getUniqueId(); + return remote(player, () -> { + var result = new ArrayList(); + for (String kind : List.of("personal","pol")) for (var entry : quests(owner,kind)) { + var row = entry.getAsJsonObject(); + boolean claim = yes(row,"canClaim") && !websiteOnly(row); + String current = text(row,"state"); + String state = claim || current.equals("active") ? "ACTIVE" : + Set.of("completed","claimed").contains(current) ? "DONE" : canStart(row) ? "AVAILABLE" : "ACTIVE"; + long target = row.has("target") ? row.get("target").getAsLong() : 0; + long progress = row.has("progress") ? row.get("progress").getAsLong() : 0; + int percent = target <= 0 ? 0 : (int)Math.max(0, Math.min(100, Math.round(progress * 100d / target))); + result.add(new Mission(kind+":"+text(row,"id"), display(row,"title"), Material.WRITABLE_BOOK, + state, percent, claim, display(row,"objective"), revision(row), kind.equals("pol") ? turnIn(row) : null)); + } + return List.copyOf(result); + }); + } + + static TurnIn turnIn(JsonObject row) { + String state=text(row,"state"); + if(websiteOnly(row)||yes(row,"canClaim")||state.equals("claimed")||!(yes(row,"canStart")||state.equals("active")))return null; + var supply=row.get("supply"); + if(supply!=null&&supply.isJsonObject()){ + var requirement=supply.getAsJsonObject(); + String role=text(requirement,"role"), item=text(requirement,"item"); + if(role.isBlank()||item.isBlank()||!requirement.has("quantity"))return null; + int quantity=requirement.get("quantity").getAsInt(); + if(quantity<1)return null; + return new TurnIn("prepare_pol_supply",role,item,display(requirement,"label"),quantity); + } + String metric=text(row,"metric"); + if(Set.of("pol-jerboa-meat-25","pol-jerboa-meat-50").contains(metric)) + return new TurnIn("prepare_husbandry_turnin","shadout_mapes",metric,"cooked Jerboa meat",0); + return null; + } + + @Override public CompletableFuture missionTurnIn(Player player, Mission mission) { + TurnIn shown=mission.turnIn(); + if(shown==null||!mission.id().startsWith("pol:"))return CompletableFuture.completedFuture(Result.no("This turn-in is unavailable.")); + UUID owner=player.getUniqueId(); + return once(player,()->{ + UUID npc; + try { npc=jarvis.questCharacterNpc(player,shown.role()); } + catch(RuntimeException failure){return CompletableFuture.completedFuture(Result.no("Stand near the assigned mission contact."));} + String id=mission.id().substring(4); + return remote(player,()->{ + for(var entry:quests(owner,"pol")){ + var row=entry.getAsJsonObject(); + if(!id.equals(text(row,"id")))continue; + if(!shown.equals(turnIn(row))||!java.util.Objects.equals(mission.revision(),revision(row))) + throw new IOException("The mission changed. Reopen your journal."); + var request=action(shown.action()); + request.addProperty("kind","pol"); + request.addProperty("definitionId",id); + request.addProperty("npcUuid",npc.toString()); + request.addProperty("confirmed",true); + request.addProperty("requestId",UUID.randomUUID().toString()); + return accepted(jarvis.requestQuests(owner,request)); + } + throw new IOException("The mission is no longer available."); + }).thenApply(permit->{ + try { + if(!npc.equals(jarvis.questCharacterNpc(player,shown.role()))) + return Result.no("Return to the original mission contact."); + if(shown.action().equals("prepare_husbandry_turnin"))jarvis.husbandryTurnin(player,permit); + else { + if(!shown.role().equals(text(permit,"role"))||!shown.metric().equals(text(permit,"item")) + ||permit.get("quantity").getAsInt()!=shown.quantity()) + return Result.no("Mission supplies changed. Reopen your journal."); + jarvis.polSupplyTurnin(player,permit); + } + return Result.yes("Turn-in recorded."); + }catch(Exception failure){ + return Result.no(failure.getMessage()==null?"The turn-in could not be recorded.":failure.getMessage()); + } + }); + }); + } + + @Override public CompletableFuture missionAction(Player player, Mission mission, boolean claim) { + UUID owner = player.getUniqueId(); + return once(player, () -> remote(player, () -> { + String[] key = mission.id().split(":", 2); + if (key.length != 2 || !Set.of("personal","pol").contains(key[0])) return Result.no("Invalid mission."); + for (var entry : quests(owner,key[0])) { + var row = entry.getAsJsonObject(); + if (!key[1].equals(text(row,"id"))) continue; + if (websiteOnly(row) || (claim ? !yes(row,"canClaim") : !canStart(row))) + return Result.no("That mission action is unavailable."); + var query = action(claim ? "claim" : "start"); + query.addProperty("kind",key[0]); + query.addProperty("definitionId",key[1]); + query.addProperty("confirmed",true); + query.addProperty("requestId",UUID.randomUUID().toString()); + if (claim) { + if (mission.revision() == null || !mission.revision().equals(revision(row))) + return Result.no("Mission progress changed. Reopen the journal."); + query.addProperty("revision",mission.revision()); + } + accepted(jarvis.requestQuests(owner,query)); + return Result.yes(claim ? "Verified quest reward recorded." : "Mission accepted."); + } + return Result.no("That mission is no longer available."); + })); + } + + @Override public CompletableFuture war(Player player) { + UUID owner=player.getUniqueId(); + return remote(player,()->{ + var rows=array(accepted(jarvis.requestWarMuster(owner,action("read"))),"wars"); + if(rows.size()!=1)throw new IOException("This menu requires exactly one current war."); + return rows.get(0).getAsJsonObject(); + }).thenApply(row->{ + var prior=warDrafts.get(owner); + var selected=new ArrayList(); + UUID token=UUID.randomUUID(); + if(prior!=null && sameWarRevision(prior.snapshot(),row)){ + selected.addAll(prior.selected()); + token=prior.token(); + }else{ + for(var entry:array(row,"selected"))if(selected.size()<8) + selected.add(entry.isJsonNull()?"":entry.getAsString()); + while(selected.size()<8)selected.add(""); + } + var roster=new ArrayList(); + for(String playerId:selected){ + var member=warCandidate(row,playerId); + roster.add(member==null?"":display(member,"name")); + } + var status=new ArrayList(); + for(var entry:array(row,"teams")){ + var team=entry.getAsJsonObject(); + status.add(display(team,"name")+" ยท "+text(team,"count")+" / "+text(team,"capacity")); + } + warDrafts.put(owner,new WarDraft(token,row.deepCopy(),selected)); + return new War(display(row,"title"),List.copyOf(roster),List.copyOf(status), + yes(row,"canLaunch"),yes(row,"editable"),token); + }); + } + + @Override public CompletableFuture> warCandidates(Player player, War war){ + var draft=currentWar(player,war); + if(draft==null||!yes(draft.snapshot(),"editable"))return CompletableFuture.failedFuture(new Unavailable()); + var result=new ArrayList(); + for(var entry:array(draft.snapshot(),"candidates")){ + var row=entry.getAsJsonObject(); + try{ + result.add(new Member(UUID.fromString(text(row,"uuid")),display(row,"name"), + yes(row,"guest")?"Accepted guest":"Clan or client member")); + }catch(IllegalArgumentException ignored){} + } + return CompletableFuture.completedFuture(List.copyOf(result)); + } + + @Override public CompletableFuture warAssign(Player player, War war, int slot, UUID candidate){ + var draft=currentWar(player,war); + if(draft==null||!yes(draft.snapshot(),"editable")||slot<0||slot>=8) + return CompletableFuture.completedFuture(Result.no("Roster editing is unavailable.")); + String id=candidate==null?"":candidate.toString(); + if(!id.isEmpty()&&(warCandidate(draft.snapshot(),id)==null|| + draft.selected().contains(id)&&!id.equals(draft.selected().get(slot)))) + return CompletableFuture.completedFuture(Result.no("Choose a current eligible person who is not already assigned.")); + draft.selected().set(slot,id); + return CompletableFuture.completedFuture(Result.yes("Draft updated.")); + } + + @Override public CompletableFuture warSave(Player player, War war){return writeWar(player,war,"save");} + @Override public CompletableFuture warLaunch(Player player, War war){return writeWar(player,war,"launch");} + + private CompletableFuture writeWar(Player player, War war, String verb){ + UUID owner=player.getUniqueId(); + return once(player,()->{ + var draft=currentWar(player,war); + if(draft==null||!yes(draft.snapshot(),verb.equals("save")?"editable":"canLaunch")) + return CompletableFuture.completedFuture(Result.no("The war or your authority changed.")); + var row=draft.snapshot(); + var query=action(verb); + query.add("warId",row.get("warId")); + query.add("revision",row.get("revision")); + query.add("party",row.getAsJsonObject("party").deepCopy()); + query.addProperty("requestId",UUID.randomUUID().toString()); + if(verb.equals("save")){ + var selected=new JsonArray(); + for(String member:draft.selected())if(!member.isEmpty())selected.add(member); + query.add("players",selected); + } + return remote(player,()->accepted(jarvis.requestWarMuster(owner,query))).thenApply(receipt->{ + warDrafts.remove(owner,draft); + return Result.yes(verb.equals("save")?"Roster saved to the website.":"War launched."); + }); + }); + } + + private WarDraft currentWar(Player player, War war){ + var draft=warDrafts.get(player.getUniqueId()); + return draft!=null&&draft.token().equals(war.draftId())?draft:null; + } + + private static boolean sameWarRevision(JsonObject a, JsonObject b){ + return text(a,"warId").equals(text(b,"warId")) && text(a,"revision").equals(text(b,"revision")) && + java.util.Objects.equals(a.get("party"),b.get("party")); + } + + private static JsonObject warCandidate(JsonObject war,String id){ + if(id.isEmpty())return null; + for(var entry:array(war,"candidates")){ + var row=entry.getAsJsonObject(); + if(id.equals(text(row,"uuid")))return row; + } + return null; + } + + @Override public CompletableFuture> decisions(Player player) { + UUID owner = player.getUniqueId(); + return remote(player, () -> array(accepted(jarvis.requestPoliticalDecisions(owner,action("read"))),"decisions")) + .thenApply(rows -> { + var available = new ArrayList(); + for (var entry:rows) { + var row=entry.getAsJsonObject(); + String fee=text(row,"feeMinor"),role=text(row,"npcRole"); + String account=decisionAccount(row); + String cost=fee.matches("[0-9]{1,15}")?Ui.dm(Long.parseLong(fee)):"Unavailable"; + String funding=""; + if (account!=null&&!account.isBlank()) { + for(var entryAccount:array(row,"accounts")) { + var accountRow=entryAccount.getAsJsonObject(); + if(account.equals(text(accountRow,"id")))funding=" ยท "+display(accountRow,"name"); + } + } + var dialogue=row.has("dialogue")&&row.get("dialogue").isJsonObject()?row.getAsJsonObject("dialogue"):null; + String effect=dialogue==null?"":display(dialogue,"introduction"); + available.add(new Decision(text(row,"id"),display(row,"title"),Material.WRITABLE_BOOK,cost+funding,effect, + account!=null && nearDecisionContact(player,role),role,account,fee)); + } + return List.copyOf(available); + }); + } + + @Override public CompletableFuture enact(Player player, Decision selection) { + UUID owner=player.getUniqueId(); + return once(player,()->{ + if(!selection.allowed()||!nearDecisionContact(player,selection.npcRole())) + return CompletableFuture.completedFuture(Result.no("Return to the authorised political contact.")); + var read=action("read"); + read.addProperty("npcRole",selection.npcRole()); + return remote(player,()->array(accepted(jarvis.requestPoliticalDecisions(owner,read)),"decisions")).thenCompose(rows->{ + for(var entry:rows){ + var row=entry.getAsJsonObject(); + if(!selection.id().equals(text(row,"id")))continue; + if(!selection.feeMinor().equals(text(row,"feeMinor"))|| + !java.util.Objects.equals(selection.sourceAccount(),decisionAccount(row))|| + !nearDecisionContact(player,selection.npcRole()))break; + var query=action("execute"); + query.addProperty("npcRole",selection.npcRole()); + query.addProperty("decisionId",selection.id()); + query.addProperty("requestId",UUID.randomUUID().toString()); + query.addProperty("confirmed",true); + if(!selection.sourceAccount().isBlank())query.addProperty("sourceAccount",selection.sourceAccount()); + return remote(player,()->{ + var receipt=accepted(jarvis.requestPoliticalDecisions(owner,query)); + return Result.yes("Decision recorded ยท "+text(receipt,"keyId")); + }); + } + return CompletableFuture.completedFuture(Result.no("Decision terms changed. Reopen the menu.")); + }); + }); + } + + private boolean nearDecisionContact(Player player, String role) { + try { return !role.isBlank() && jarvis.questCharacterNpc(player,role)!=null; } + catch(RuntimeException unavailable){return false;} + } + + static String decisionAccount(JsonObject row) { + if(text(row,"kind").equals("website")||row.has("parameters"))return null; + if(row.has("fundingRequired")&&!yes(row,"fundingRequired"))return ""; + String fee=text(row,"feeMinor"); + if(!fee.matches("[0-9]{1,15}"))return null; + long amount=Long.parseLong(fee); + String selected=null; + for(var entry:array(row,"accounts")){ + var account=entry.getAsJsonObject(); + String available=text(account,"availableMinor"); + if(!available.matches("[0-9]{1,18}")||Long.parseLong(available)> organisations(Player player, String kind) { + UUID owner = player.getUniqueId(); + return remote(player, () -> { + var rows = new ArrayList(); + for (var entry : organisationRows(owner,kind)) rows.add(displayOrganisation(entry.getAsJsonObject())); + return List.copyOf(rows); + }); + } + + @Override public CompletableFuture org(Player player, String kind, String id) { + UUID owner = player.getUniqueId(); + return remote(player, () -> displayOrganisation(organisation(owner,kind,id))); + } + + private static Org displayOrganisation(JsonObject row) { + return new Org(display(row,"name"),yes(row,"canManage")?"Leader / manager":"Member", + array(row,"members").size(),null,text(row,"id"),text(row,"authorityVersion"),warKey(row)); + } + + @Override public CompletableFuture> members(Player player, String kind, String organisationId) { + UUID owner = player.getUniqueId(); + return remote(player, () -> { + var result = new ArrayList(); + for (var entry : array(organisation(owner,kind,organisationId),"members")) { + var member = entry.getAsJsonObject(); + String linked = text(member,"uuid"); + if (linked.isBlank()) linked = text(member,"minecraftUuid"); + UUID id; + try { id = UUID.fromString(linked); } + catch (IllegalArgumentException invalid) { continue; } + result.add(new Member(id,display(member,"name"),display(member,"role"))); + } + return List.copyOf(result); + }); + } + + @Override public CompletableFuture orgAction(Player player, String kind, String action, Org shown) { + if (shown == null || !Set.of("home","claims","wars","war-transport","motd","vault","allies","invite","transactions","roles").contains(action)) + return CompletableFuture.failedFuture(new Unavailable()); + UUID owner = player.getUniqueId(); + return once(player, () -> remote(player, () -> organisation(owner,kind,shown.id())).thenCompose(row -> { + if (!matchesOrganisation(shown, row) || + (action.equals("war-transport") && !shown.warKey().equals(warKey(row)))) { + return CompletableFuture.completedFuture(Result.no("Organisation details changed. Reopen this menu.")); + } + if (Set.of("vault","allies","invite","transactions","roles").contains(action)) { + String url="https://clans.dunerealms.com/#"+(kind.equals("clan")?"clan/clan-overview":"company/company-overview"); + player.sendMessage(net.kyori.adventure.text.Component.text("Open "+action+" on the organisation website โ†’") + .clickEvent(net.kyori.adventure.text.event.ClickEvent.openUrl(url))); + return CompletableFuture.completedFuture(Result.yes("This organisation service is managed on the website.")); + } + if (action.equals("motd")) { + String message=text(row,"motd"); + return CompletableFuture.completedFuture(Result.yes(message.isBlank()?"No organisation message has been set.":message)); + } + if (action.equals("claims")) { + return CompletableFuture.completedFuture(Result.yes("Estate capacity: "+ + (text(row,"claimCapacity").isBlank()?"unavailable":text(row,"claimCapacity")+" chunks")+".")); + } + var wars = array(row,"wars"); + if (action.equals("wars")) { + var names = new ArrayList(); + for (var entry : wars) names.add(text(entry.getAsJsonObject(),"targetName")); + return CompletableFuture.completedFuture(Result.yes(names.isEmpty()?"No current deployments.":String.join(", ",names))); + } + if (action.equals("war-transport") && warKey(row).isBlank()) + return CompletableFuture.completedFuture(Result.no("Exactly one current deployment is required for this menu.")); + var query = action(action.equals("home")?"travel-home":"war-transport"); + query.addProperty("kind",kind); + query.add("id",row.get("id")); + query.add("authorityVersion",row.get("authorityVersion")); + query.addProperty("requestId",UUID.randomUUID().toString()); + if (action.equals("war-transport")) query.add("warKeyId",wars.get(0).getAsJsonObject().get("keyId")); + return jarvis.organisationAction(player,query).thenApply(response -> + response.has("rejectedStatus") ? Result.no(reason(response)) : + Result.yes(text(response,"message").isBlank()?"Organisation passage requested.":text(response,"message"))); + })); + } + + static boolean matchesOrganisation(Org shown, JsonObject row) { + return shown != null && !shown.id().isBlank() && !shown.revision().isBlank() + && shown.id().equals(text(row,"id")) && shown.revision().equals(text(row,"authorityVersion")); + } + + private static String warKey(JsonObject row) { + var wars = array(row,"wars"); + return wars.size() == 1 ? text(wars.get(0).getAsJsonObject(),"keyId") : ""; + } + + private JsonObject organisation(UUID owner, String kind, String id) throws Exception { + return selectOrganisation(organisationRows(owner,kind),id); + } + + static JsonObject selectOrganisation(JsonArray rows, String id) throws IOException { + for (var entry : rows) { + var row = entry.getAsJsonObject(); + if (!id.isBlank() && text(row,"id").equals(id)) return row; + } + throw new IOException("Your organisation membership changed."); + } + + private JsonArray organisationRows(UUID owner, String kind) throws Exception { + String key = switch(kind) { + case "clan" -> "clans"; + case "company" -> "companies"; + default -> throw new Unavailable(); + }; + return array(accepted(jarvis.requestOrganisations(owner)),key); + } + + @Override public CompletableFuture refitQuote(Player player) { + UUID owner = player.getUniqueId(), world = player.getWorld().getUID(), npc; + JsonObject snapshot; + try { + snapshot = jarvis.refitSnapshot(player); + npc = jarvis.starterNpc(player); + } catch (RuntimeException noItemOrNpc) { + return CompletableFuture.completedFuture(new Refit(false,"Original equipment",Material.ANVIL, + List.of(),"Hold your eligible original near Gurney.",null)); + } + var held = player.getInventory().getItemInMainHand(); + Material material = held.getType(); + String name = held.hasItemMeta() && held.getItemMeta().hasDisplayName() + ? MiniMessage.miniMessage().escapeTags(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText() + .serialize(held.getItemMeta().displayName())) : material.name().replace('_',' '); + return remote(player, () -> { + var list = action("read_refits"); + list.addProperty("kind","pol"); + var owners = array(accepted(jarvis.requestQuests(owner,list)),"owners"); + if (owners.size()!=1) return null; + var ownerRecord = owners.get(0).getAsJsonObject(); + var selected = new JsonObject(); + selected.add("kind",ownerRecord.get("kind")); + selected.add("id",ownerRecord.get("id")); + var input = action("prepare_refit"); + input.addProperty("kind","pol"); + input.add("owner",selected); + input.add("snapshot",snapshot); + input.addProperty("npcUuid",npc.toString()); + input.addProperty("requestId",UUID.randomUUID().toString()); + input.addProperty("confirmed",true); + var permit = accepted(jarvis.requestQuests(owner,input)); + return Map.entry(input,permit.getAsJsonObject("plan")); + }).thenApply(quote -> { + if (quote==null) return new Refit(false,name,material,List.of(), + "Exactly one authorised workshop is required by this menu.",null); + var plan = quote.getValue(); + var costs = new ArrayList(); + for(var token : array(plan.getAsJsonObject("consume"),"templates")) + costs.add("1 "+display(token.getAsJsonObject(),"id").replace("dr_","").replace('_',' ')); + var output=plan.getAsJsonObject("output"); + String note="MK "+display(output,"equipmentMark")+" ยท "+display(output,"quality").replace('_',' ')+" ยท valid for 30 seconds"; + UUID ref=UUID.randomUUID(); + refitPermits.put(owner,new RefitPermit(ref,world,quote.getKey(),plan.deepCopy(),System.nanoTime()+30_000_000_000L)); + return new Refit(true,name,material,List.copyOf(costs),note,ref); + }); + } + + @Override public CompletableFuture refit(Player player, Refit quote) { + UUID owner=player.getUniqueId(); + return once(player, () -> { + var permit=refitPermits.get(owner); + if(permit==null||!permit.quoteId().equals(quote.quoteId())|| + !permit.world().equals(player.getWorld().getUID())||System.nanoTime()-permit.deadline()>=0|| + !matchesRefit(player,permit)) + return CompletableFuture.completedFuture(Result.no("Refit quote expired or the original item changed.")); + refitPermits.remove(owner,permit); + return remote(player,()->accepted(jarvis.requestQuests(owner,permit.request()))).thenApply(issued->{ + if(System.nanoTime()-permit.deadline()>=0||!matchesRefit(player,permit)|| + !permit.plan().equals(issued.get("plan"))) + return Result.no("Hold the same original near Gurney and request a new refit."); + try { + return jarvis.refitEquipment(player,issued)?Result.yes("Original equipment upgraded."): + Result.no("This refit was already processed."); + }catch(Exception failure){return Result.no("The refit was not confirmed.");} + }); + }); + } + + private boolean matchesRefit(Player player, RefitPermit permit) { + try { + return permit.request().get("snapshot").equals(jarvis.refitSnapshot(player))&& + text(permit.request(),"npcUuid").equals(jarvis.starterNpc(player).toString()); + }catch(RuntimeException unavailable){return false;} + } + + @Override public CompletableFuture> houses(Player player) { + UUID owner = player.getUniqueId(); + return remote(player, () -> { + var data = accepted(jarvis.requestHouse(owner, null, 0, null)); + var choices = new ArrayList(); + for (var entry : array(data,"choices")) { + var house = entry.getAsJsonObject(); + String id = text(house,"id"); + Material banner = switch (id) { + case "atreides" -> Material.GREEN_BANNER; + case "corrino" -> Material.YELLOW_BANNER; + case "fremen" -> Material.ORANGE_BANNER; + case "harkonnen" -> Material.RED_BANNER; + case "ordos" -> Material.CYAN_BANNER; + default -> null; + }; + if (banner != null) choices.add(new House(id,display(house,"name"),display(house,"motto"), + banner,data.get("version").getAsInt())); + } + return List.copyOf(choices); + }); + } + + @Override public CompletableFuture chooseHouse(Player player, House choice) { + UUID owner = player.getUniqueId(); + return once(player, () -> remote(player, () -> { + accepted(jarvis.requestHouse(owner,choice.id(),choice.version(),UUID.randomUUID())); + return Result.yes("House allegiance saved in J.A.R.V.I.S."); + })); + } + + private JsonArray quests(UUID owner, String kind) throws Exception { + var query = action("read"); + query.addProperty("kind",kind); + return array(accepted(jarvis.requestQuests(owner,query)),"quests"); + } + + private static Long revision(JsonObject row) { + return row.has("revision")&&!row.get("revision").isJsonNull() ? row.get("revision").getAsLong() : null; + } + + static JsonObject purchaseRequest(Listing offer, int quantity, UUID reference) { + var query = action(offer.kitVersion() == null ? "buy" : "buy_kit"); + query.addProperty("requestId", reference.toString()); + query.addProperty("priceMinor", offer.priceMinor()); + query.addProperty("confirmed", true); + if (offer.kitVersion() == null) { + query.addProperty("listingId", offer.id()); + query.addProperty("amount", quantity); + } else { + query.addProperty("kitsetId", offer.id()); + query.addProperty("listingVersion", offer.kitVersion()); + } + return query; + } + + static boolean canStart(JsonObject row) { + return !websiteOnly(row) && yes(row,"canStart") && !yes(row,"canClaim") && + !Set.of("active","completed","claimed").contains(text(row,"state")) && + (!row.has("cooldownUntil") || row.get("cooldownUntil").isJsonNull() || + row.get("cooldownUntil").getAsLong() <= System.currentTimeMillis()); + } + + private static boolean websiteOnly(JsonObject row) { + if (!row.has("executionRequirements") || !row.get("executionRequirements").isJsonObject()) return false; + var requirements = row.getAsJsonObject("executionRequirements"); + return yes(requirements,"website") && !yes(requirements,"minecraft"); + } + + private static JsonObject action(String name) { + var input = new JsonObject(); + input.addProperty("action",name); + return input; + } + + private static JsonObject accepted(JsonObject response) throws IOException { + if (response == null || response.has("rejectedStatus") || (response.has("ok") && !yes(response,"ok"))) + throw new IOException(reason(response)); + return response; + } + + private static String reason(JsonObject response) { + String message = response == null ? "" : text(response,"message"); + return message.isBlank() ? "J.A.R.V.I.S. rejected the request." : message; + } + + private static JsonArray array(JsonObject row, String key) { + return row.has(key) && row.get(key).isJsonArray() ? row.getAsJsonArray(key) : new JsonArray(); + } + + private static String text(JsonObject row, String key) { + return row.has(key) && !row.get(key).isJsonNull() ? row.get(key).getAsString() : ""; + } + + private static String display(JsonObject row, String key) { + return MiniMessage.miniMessage().escapeTags(text(row,key)); + } + + private static boolean yes(JsonObject row, String key) { + return row.has(key) && !row.get(key).isJsonNull() && row.get(key).getAsBoolean(); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/LegacyInventoryMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/LegacyInventoryMenu.java new file mode 100644 index 00000000..f6f5b147 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/LegacyInventoryMenu.java @@ -0,0 +1,13 @@ +package com.dunerealms.menus; +import java.util.*;import java.util.function.BooleanSupplier; +import org.bukkit.entity.Player;import org.bukkit.inventory.Inventory;import org.bukkit.plugin.java.JavaPlugin; +/** Exact adapter for retained Core/Ess NativeMenus. Their gate and callbacks remain authoritative. */ +final class LegacyInventoryMenu extends Menu { + private final JavaPlugin owner;private final Inventory model;private final String heading,note;private final Map actions;private final BooleanSupplier gate;private final UUID world; + LegacyInventoryMenu(DuneMenusPlugin plugin,JavaPlugin owner,Player player,String title,Inventory model,Map actions,BooleanSupplier gate){this(plugin,owner,player,title,"",model,actions,gate);} + LegacyInventoryMenu(DuneMenusPlugin plugin,JavaPlugin owner,Player player,String title,String description,Inventory model,Map actions,BooleanSupplier gate){super(plugin,player,null);note=description;this.owner=owner;this.model=model;heading=title;this.actions=Map.copyOf(actions);this.gate=gate;world=player.getWorld().getUID();} + boolean matches(Inventory expected){return model==expected&&owner.isEnabled()&&player.isOnline()&&world.equals(player.getWorld().getUID())&&plugin.hasOpenMenu(player,this);} + void finish(){end();plugin.closeNativePresentation(player);} + String id(){return ServiceSection.of(heading);}Skin skin(){return Skin.GOLD;}String title(){return heading;}String subtitle(){return note;}int rows(){return Math.max(1,Math.min(6,(model.getSize()+8)/9));} + void draw(){for(int slot=0;slot{if(matches(model)&&gate.getAsBoolean())action.run();});}} +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/LoreArchiveMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/LoreArchiveMenu.java new file mode 100644 index 00000000..75cd7470 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/LoreArchiveMenu.java @@ -0,0 +1,21 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +final class LoreArchiveMenu extends Menu { + LoreArchiveMenu(DuneMenusPlugin plugin, Player player, Menu parent) { super(plugin, player, parent); } + + String id() { return "lore"; } + Skin skin() { return Skin.GOLD; } + String title() { return "Item lore archive"; } + int rows() { return 3; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + back(22); + var samples = backend().loreArchive(); + if (samples.isEmpty()) put(13, Ui.item(Material.BARRIER, "Item previews are temporarily unavailable")); + for (int i = 0; i < samples.size() && i < 9; i++) put(9 + i, samples.get(i)); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/MembersMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/MembersMenu.java new file mode 100644 index 00000000..79fb3a8b --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/MembersMenu.java @@ -0,0 +1,26 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** Heads only, no decoration noise. Shared by clan and company. */ +final class MembersMenu extends Menu { + private final String kind; + private final String organisationId; + MembersMenu(DuneMenusPlugin plugin, Player p, Menu parent, String kind, String organisationId) { super(plugin, p, parent); this.kind = kind; this.organisationId = organisationId; } + String id() { return "members"; } + Skin skin() { return kind.equals("clan") ? Skin.CLAN : Skin.COMPANY; } + String title() { return "Members"; } + int rows() { return 6; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + back(49); + load(backend().members(player, kind, organisationId), list -> { + for (int i = 0; i < Math.min(45, list.size()); i++) { + var m = list.get(i); + put(i, Ui.head(m.id(), "" + m.name(), "" + m.role())); + } + }); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/MentatMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/MentatMenu.java new file mode 100644 index 00000000..3169d587 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/MentatMenu.java @@ -0,0 +1,27 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +final class MentatMenu extends Menu { + MentatMenu(DuneMenusPlugin plugin, Player player, Menu parent) { super(plugin, player, parent); } + + String id() { return "mentat"; } + Skin skin() { return Skin.HOUSE; } + String title() { return "Your Mentat"; } + int rows() { return 3; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + back(18); + load(backend().mentat(player), name -> { + if (name.isBlank()) { + put(13, Ui.item(Material.WHITE_BANNER, "Choose your House"), click -> go(new HouseMenu(plugin, player, this))); + return; + } + put(13, Ui.item(Material.PLAYER_HEAD, ""+name)); + put(11, Ui.item(Material.WRITABLE_BOOK, "Mission journal"), click -> go(new MissionsMenu(plugin, player, this))); + put(15, Ui.item(Material.COMPASS, "Spacing Guild"), click -> go(new TravelMenu(plugin, player, this))); + }); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/Menu.java b/DuneMenus/src/main/java/com/dunerealms/menus/Menu.java new file mode 100644 index 00000000..4ef1e7f4 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/Menu.java @@ -0,0 +1,210 @@ +package com.dunerealms.menus; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.function.Consumer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; + +/** + * One menu definition, three renderers: chest inventory (Java), Floodgate form (Bedrock) and an optional + * fullscreen provider. Subclasses only describe a layout in draw(). One click does one thing: no confirm screens. + */ +abstract class Menu implements InventoryHolder { + interface Button { void click(ClickType type); } + enum Mode { BEDROCK, FULLSCREEN } + + protected final DuneMenusPlugin plugin; + protected final Player player; + protected final Menu parent; + private Inventory inv; + private final Map buttons = new TreeMap<>(); + private Mode mode; + private boolean active, redrawn; + private int gen, pending; + private long presentation; + + Menu(DuneMenusPlugin plugin, Player player, Menu parent) { this.plugin = plugin; this.player = player; this.parent = parent; } + + abstract String id(); + abstract Skin skin(); + abstract String title(); + abstract int rows(); + abstract void draw(); + String subtitle() { return ""; } + boolean launchNative() { return false; } + boolean renderWhileLoading() { return false; } + boolean navigationWhileLoading(int slot) { return false; } + + @Override public Inventory getInventory() { return inv; } + protected Backend backend() { return plugin.backend(); } + + // ---------------------------------------------------------------- lifecycle + final void open() { + if (launchNative()) return; + if (!available()) return; + active = true; + plugin.opened(player, this); + mode = plugin.modeFor(player); + if (inv == null) inv = Bukkit.createInventory(this, rows() * 9, plugin.titleFor(this)); + redraw(); + } + + final void closed() { + active = false; + presentation++; + plugin.closed(player, this); + } + + /** Leaves the menu system entirely (travel, house choice...). */ + protected void end() { closed(); player.closeInventory(); } + + protected void go(Menu next) { + if (!next.available()) return; + closed(); + Bukkit.getScheduler().runTask(plugin, next::open); + } + + private boolean available() { + return switch (id()) { + case "bank", "atm", "withdraw", "deposit", "redeem", "receipt" -> { + if (plugin.getConfig().getBoolean("rihla.enabled", false)) yield true; + say(Backend.Result.no("Rihla is currently unavailable in Minecraft.")); + yield false; + } + default -> true; + }; + } + + final void redraw() { + redrawn = true; gen++; pending = 0; + inv.clear(); buttons.clear(); + draw(); + if (pending == 0 || renderWhileLoading()) present(); + } + + final void handle(int slot, ClickType type) { + Button b = buttons.get(slot); + if (b == null || !active || pending != 0 && !navigationWhileLoading(slot)) return; + clickFeedback(); + redrawn = false; + b.click(type); + if (active && !redrawn && pending == 0) present(); // keep forms/screens alive + } + + protected void clickFeedback() { player.playSound(player.getLocation(), skin().click(), 0.5f, 1.2f); } + + // ---------------------------------------------------------------- drawing helpers + protected void backdrop(Material m) { ItemStack p = Ui.pane(m); for (int i = 0; i < inv.getSize(); i++) inv.setItem(i, p); } + protected void put(int slot, ItemStack item) { if (slot >= 0 && slot < inv.getSize()) inv.setItem(slot, item); } + protected void put(int slot, ItemStack item, Button b) { put(slot, item); buttons.put(slot, b); } + protected void back(int slot) { if (parent != null) put(slot, Ui.item(Material.ARROW, "Back"), t -> go(parent)); } + protected void say(Backend.Result r) { player.sendMessage(Component.text(r.message(), r.ok() ? net.kyori.adventure.text.format.NamedTextColor.GREEN : net.kyori.adventure.text.format.NamedTextColor.RED)); } + + /** Runs the backend call, continues on the main thread, and ignores answers for a screen that was redrawn or closed. */ + protected void load(CompletableFuture f, Consumer ok) { + final int g = gen; + pending++; + f.whenComplete((value, err) -> Bukkit.getScheduler().runTask(plugin, () -> { + if (g != gen || !active || !player.isOnline()) return; + pending--; + if (err != null) { + Throwable cause = err instanceof CompletionException && err.getCause() != null ? err.getCause() : err; + player.sendMessage(Ui.text(cause instanceof Backend.Unavailable + ? "J.A.R.V.I.S. could not complete this request. Reopen this menu." + : "Something went wrong. Please try again.")); + } else ok.accept(value); + if (g == gen && pending == 0) present(); + })); + } + + /** Backend action: tell the player the outcome, then refresh. */ + protected void act(CompletableFuture f) { load(f, r -> { say(r); redraw(); }); } + + // ---------------------------------------------------------------- Bedrock / fullscreen + private static String plain(ItemStack it) { + var m = it.getItemMeta(); + Component c = m == null ? null : m.displayName(); + return c == null ? "" : PlainTextComponentSerializer.plainText().serialize(c).trim(); + } + + private static List loreOf(ItemStack it) { + var m = it.getItemMeta(); + List l = m == null ? null : m.lore(); + List out = new ArrayList<>(); + if (l != null) for (Component c : l) out.add(PlainTextComponentSerializer.plainText().serialize(c).trim()); + return out; + } + + private List snapshot() { + List out = new ArrayList<>(); + if (routeCards()) { + for (int slot = 0; slot < inv.getSize(); slot++) { + ItemStack it = inv.getItem(slot); + if (disabledRoute(it) && !buttons.containsKey(slot) && !plain(it).isBlank()) + out.add(new Card(slot, plain(it), loreOf(it), "gray_dye", false)); + } + } + for (int slot : buttons.keySet()) { + ItemStack it = inv.getItem(slot); + if (it == null || plain(it).isBlank()) continue; + out.add(new Card(slot, plain(it), loreOf(it), it.getType().name().toLowerCase())); + } + if (routeCards()) out.sort(java.util.Comparator.comparingInt(Card::slot)); + return out; + } + + private List info() { + List out = new ArrayList<>(); + for (int i = 0; i < inv.getSize(); i++) { + ItemStack it = inv.getItem(i); + if (it == null || buttons.containsKey(i) || it.getType().name().endsWith("_PANE") || routeCards() && disabledRoute(it)) continue; + String n = plain(it); + if (n.isBlank()) continue; + List lore = loreOf(it).stream().filter(s -> !s.isBlank()).toList(); + out.add(lore.isEmpty() ? n : n + " โ€” " + String.join(" ยท ", lore)); + } + return out; + } + + private boolean routeCards() { return id().equals("travel") || id().equals("smuggler"); } + private static boolean disabledRoute(ItemStack item) { return item != null && item.getType()==Material.GRAY_DYE; } + + private void present() { + long shown = ++presentation; + var world = player.getWorld().getUID(); + java.util.function.IntConsumer select = slot -> { + if (!active || shown != presentation || !player.isOnline() || !world.equals(player.getWorld().getUID())) return; + presentation++; + handle(slot, ClickType.LEFT); + }; + Runnable close = () -> { + if (shown == presentation) closed(); + }; + List cards = snapshot(); + List info = info(); + if (mode == Mode.FULLSCREEN) { + FullscreenProvider provider = plugin.fullscreen(); + boolean ok = provider != null && provider.open(player, + new FullscreenProvider.Screen(id(), title(), subtitle(), cards, info, + java.util.Arrays.stream(inv.getContents()).map(i -> i == null ? null : i.clone()).toArray(ItemStack[]::new)), + select, close); + if (ok) return; + player.sendMessage(Component.text("The menu artwork is unavailable. Please reconnect after the resource pack loads.")); + closed(); + return; + } + Bedrock.show(plugin, player, title(), subtitle(), info, cards, select, close); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/MenuArt.java b/DuneMenus/src/main/java/com/dunerealms/menus/MenuArt.java new file mode 100644 index 00000000..52e09b20 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/MenuArt.java @@ -0,0 +1,42 @@ +package com.dunerealms.menus; +import java.nio.file.*; +import java.util.*; +import java.util.jar.JarFile; +import com.google.gson.*; +import org.bukkit.inventory.ItemStack; +/** Local, cached references to the exact central-pack item artwork; never invents a quality or model. */ +final class MenuArt { + private final DuneMenusPlugin plugin; + private final Map paths=new HashMap<>(); + MenuArt(DuneMenusPlugin plugin){this.plugin=plugin;} + void prepare(Path root)throws Exception{ + try(var jar=new JarFile(Path.of(plugin.getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).toFile())){ + var entries=jar.entries();while(entries.hasMoreElements()){ + var entry=entries.nextElement();String name=entry.getName();if(entry.isDirectory()||!name.startsWith("menu-art/"))continue; + String relative=name.substring(9);if(!relative.endsWith(".png"))continue; + Path target=root.resolve(relative).normalize();if(!target.startsWith(root.normalize()))throw new IllegalArgumentException("Invalid artwork path"); + Files.createDirectories(target.getParent());try(var in=jar.getInputStream(entry)){Files.copy(in,target,StandardCopyOption.REPLACE_EXISTING);} + } + } + } + String image(ItemStack item){ + if(item==null||item.getType().isAir())return ""; + var meta=item.getItemMeta();String key=meta!=null&&meta.hasItemModel()?meta.getItemModel().toString():"minecraft:"+item.getType().name().toLowerCase(Locale.ROOT); + return paths.computeIfAbsent(key,this::resolve); + } + private String resolve(String key){ + if(!key.matches("[a-z0-9_]+:[a-z0-9_/.-]+")||key.contains(".."))return ""; + String[] id=key.split(":",2); + if(id[0].equals("minecraft")){String icon=exists("pack/assets/minecraft/textures/item/"+id[1]+".png");return icon.isEmpty()?exists("pack/assets/minecraft/textures/block/"+id[1]+".png"):icon;} + try{ + JsonObject definition=json("pack/assets/"+id[0]+"/items/"+id[1]+".json");if(definition==null)return ""; + var model=definition.getAsJsonObject("model");if(model==null||!model.get("type").getAsString().equals("minecraft:model"))return ""; + String[] ref=model.get("model").getAsString().split(":",2);if(ref.length!=2)return ""; + var data=json("pack/assets/"+ref[0]+"/models/"+ref[1]+".json");if(data==null||!data.has("textures"))return ""; + var textures=data.getAsJsonObject("textures");if(!textures.has("layer0"))return ""; + String[] texture=textures.get("layer0").getAsString().split(":",2);return texture.length==2?exists("pack/assets/"+texture[0]+"/textures/"+texture[1]+".png"):""; + }catch(RuntimeException invalid){return "";} + } + private String exists(String path){if(path.contains("..")||!path.matches("[a-zA-Z0-9_/.-]+"))return "";try(var input=plugin.getResource("menu-art/"+path)){return input==null?"":path;}catch(java.io.IOException failure){return "";}} + private JsonObject json(String path){if(path.contains(".."))return null;try(var input=plugin.getResource("menu-art/"+path)){return input==null?null:JsonParser.parseReader(new java.io.InputStreamReader(input,java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject();}catch(Exception failure){return null;}} +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/MenuListener.java b/DuneMenus/src/main/java/com/dunerealms/menus/MenuListener.java new file mode 100644 index 00000000..d5a91615 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/MenuListener.java @@ -0,0 +1,72 @@ +package com.dunerealms.menus; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +final class MenuListener implements Listener { + private final Map last = new HashMap<>(); + private final DuneMenusPlugin plugin; + + MenuListener(DuneMenusPlugin plugin) { this.plugin = plugin; } + + static boolean isCodex(org.bukkit.inventory.ItemStack item) { + if (item == null || !item.hasItemMeta()) return false; + var data = item.getItemMeta().getPersistentDataContainer(); + var string = org.bukkit.persistence.PersistentDataType.STRING; + return "menu_opener".equals(data.get(new org.bukkit.NamespacedKey("dunerealms", "item"), string)) + || "dr_imperial_codex".equals(data.get(new org.bukkit.NamespacedKey("executableitems", "ei-id"), string)); + } + + @EventHandler(priority = org.bukkit.event.EventPriority.HIGHEST, ignoreCancelled = true) + public void protectMenuViewer(org.bukkit.event.entity.EntityDamageEvent event) { + if (event.getEntity() instanceof org.bukkit.entity.Player player && plugin.hasOpenMenu(player)) event.setCancelled(true); + } + + @EventHandler + public void onClick(InventoryClickEvent e) { + var top = e.getView().getTopInventory(); + if (!(top.getHolder() instanceof Menu menu)) return; + e.setCancelled(true); // menu items can never be taken + if (e.getClickedInventory() != top) return; + long now = System.currentTimeMillis(); + Long before = last.put(e.getWhoClicked().getUniqueId(), now); + if (before != null && now - before < 150) return; // swallow double-clicks so nothing is bought twice + menu.handle(e.getSlot(), e.getClick()); + } + + @EventHandler + public void onDrag(InventoryDragEvent e) { + if (e.getView().getTopInventory().getHolder() instanceof Menu) e.setCancelled(true); + } + + @EventHandler + public void onClose(InventoryCloseEvent e) { + if (e.getInventory().getHolder() instanceof Menu menu) menu.closed(); + } + + @EventHandler + public void onQuit(PlayerQuitEvent e) { + last.remove(e.getPlayer().getUniqueId()); + plugin.forgetPack(e.getPlayer()); + plugin.dismiss(e.getPlayer()); + } + + @EventHandler + public void onJoin(org.bukkit.event.player.PlayerJoinEvent event) { + plugin.getServer().getScheduler().runTaskLater(plugin, () -> plugin.requestPackStatus(event.getPlayer()), 5); + + } + + @EventHandler + public void onWorldChange(PlayerChangedWorldEvent e) { + plugin.dismiss(e.getPlayer()); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/MenuPolish.java b/DuneMenus/src/main/java/com/dunerealms/menus/MenuPolish.java new file mode 100644 index 00000000..1dc6f85f --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/MenuPolish.java @@ -0,0 +1,38 @@ +package com.dunerealms.menus; + +/** Presentation only: original slot identifiers and callbacks remain unchanged. */ +final class MenuPolish { + private MenuPolish() {} + static String apply(String html) { + if (html.contains("/* compact-dune-cards */")) return html; + return html.replace("", "/* compact-dune-cards */" + CSS + ""); + } + private static final String CSS = """ + +/* Compact service cards: 75% of their previous dimensions; retain the Dune palette. */ +.card{width:13.875%;height:103.5px;padding:5px;border-radius:8px;box-shadow:inset 0 0 0 1px #0a231f,0 2px 6px #071713} +.card:hover{box-shadow:inset 0 0 0 1px #0a231f,0 2px 8px #071713} +.hub .card{width:13.875%;min-height:66.75px}.journal .card{width:23.25%;height:103.5px;min-height:51px;padding:6px} +.council .card{width:25.875%;height:103.5px;min-height:86.25px}.bank .card{width:18%;min-height:75px} +.card .emblem{font-size:19.5px;width:24px;height:24px;line-height:20px;padding:1px;margin:0 auto 2px;border-radius:6px;box-shadow:none;text-shadow:none} +.card .item-icon{width:20px;height:20px}.card h2{font-size:11.5px;line-height:1.15;height:26.45px;overflow:hidden;margin:0 0 2px}.card p{font-size:9.5px;line-height:1.2;max-height:22.8px;overflow:hidden;margin:1px 0}.card p+p{max-height:11.4px}.house-choices .card p{max-height:11.4px}.locked.card{height:auto;min-height:103.5px}.locked.card p{max-height:none} +.house-choices .card{width:19.5%;height:78.75px;min-height:78.75px}.house-choices .card h2{font-size:11px} +.house-choices .card .emblem{font-size:19.5px;width:24px;height:24px;line-height:20px}.house-choices .card .item-icon{width:20px;height:20px} +.constellation{height:auto;min-height:262.5px;display:flex;flex-wrap:wrap;gap:12px;justify-content:center;align-items:flex-start;align-content:flex-start;padding:12px 0 36px} +.constellation .card{position:relative;top:auto;left:auto;right:auto;width:129.75px;height:54px;min-height:54px;padding:6px;border-radius:8px} +.constellation .locked.card{height:auto;min-height:63px}.constellation .back{position:absolute;bottom:0;left:0} +.detail-link{right:4px;top:4px;font-size:8px;padding:1px 3px;border-radius:5px} +.goods{width:75%;margin:0 auto;gap:12px}.travel .goods{gap:18px}.community .goods{gap:15px}.quest .goods{gap:7.5px}.hub .goods{max-width:637.5px;width:75%} +.slot{min-height:93px;padding:8.25px 5px 7.5px;border-width:2px;border-radius:8px;box-shadow:inset 0 0 0 1px #081d1b,0 2px 5px #091d17} +.slot:hover,.slot.selected{box-shadow:inset 0 0 0 1px #081d1b,0 2px 7px #091d17} +.hub .slot{min-height:99px}.slot strong,.hub .slot strong{font-size:12px;line-height:1.2;overflow-wrap:break-word} +.slot .cubby,.travel .cubby{width:36px;height:36px;border-radius:7px}.slot .cubby img{width:30px;height:30px} +.travel .slot{min-height:108.75px}.quest .slot{min-height:57.75px;padding:5px 11.25px;grid-template-columns:42.75px 1fr;column-gap:9.75px} +.quest .slot strong{font-size:15px}.quest .slot .cubby{width:36px;height:36px}.slot .tag{font-size:10px;margin-top:4.5px}.slot .cubby{margin-bottom:5.25px}.quest .slot .cubby{margin:0} +.mission{width:72%;min-height:27px;padding:5px 11px;font-size:12px;border-width:1px;border-radius:6px} +.mission span{font-size:11px}.primary{width:60%;min-height:32.25px;padding:5px 11px;font-size:15px;border-width:1px;border-radius:6px} +.secondary{width:54%;min-height:24.75px;padding:4.5px 11px;font-size:11.25px;border-width:1px;border-radius:6px} +.slots{width:75%;margin:0 auto;gap:5.25px}.member{min-height:35.25px;border-radius:6px;font-size:11px}.member .number{width:17.25px;padding:4.5px 0;font-size:9px} +@media(max-width:600px){.goods,.hub .goods{width:100%}.slot strong,.hub .slot strong{font-size:12px}} + """; +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/MissionsMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/MissionsMenu.java new file mode 100644 index 00000000..a5769880 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/MissionsMenu.java @@ -0,0 +1,62 @@ +package com.dunerealms.menus; + +import java.util.List; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** 6 rows. Each mission is one row: icon, a 7-segment progress bar, one action button. */ +final class MissionsMenu extends Menu { + private static final int PER_PAGE = 4; + private String filter = "ACTIVE"; + private int page = 0; + + MissionsMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); } + String id() { return "missions"; } + Skin skin() { return Skin.QUEST; } + String title() { return "Mission Journal"; } + String subtitle() { return "โ€œEvery deed is written in the chronicle.โ€"; } + int rows() { return 6; } + + private void tab(int slot, Material m, String label, String key) { + var item = Ui.item(m, (filter.equals(key) ? "" : "") + label); + if (filter.equals(key)) Ui.glow(item); + put(slot, item, t -> { filter = key; page = 0; redraw(); }); + } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + tab(1, Material.WRITABLE_BOOK, "In progress", "ACTIVE"); + tab(2, Material.COMPASS, "Available", "AVAILABLE"); + tab(3, Material.EMERALD, "Completed", "DONE"); + back(45); + load(backend().missions(player), all -> { + List list = all.stream().filter(m -> m.state().equals(filter)).toList(); + int from = page * PER_PAGE; + for (int i = 0; i < PER_PAGE && from + i < list.size(); i++) row(i + 1, list.get(from + i)); + if (list.isEmpty()) put(22, Ui.item(Material.PAPER, "Nothing here yet")); + if (page > 0) put(48, Ui.item(Material.ARROW, "โ—€ Previous"), t -> { page--; redraw(); }); + if (from + PER_PAGE < list.size()) put(50, Ui.item(Material.ARROW, "Next โ–ถ"), t -> { page++; redraw(); }); + }); + } + + private void row(int r, Backend.Mission m) { + int base = r * 9; + put(base, Ui.item(m.icon(), "" + m.title(), "" + m.summary(), "Progress: " + m.percent() + "%")); + int filled = Math.round(m.percent() * 7 / 100f); + for (int i = 0; i < 7; i++) + put(base + 1 + i, Ui.pane(i < filled ? Material.LIME_STAINED_GLASS_PANE : Material.GRAY_STAINED_GLASS_PANE)); + if (m.claimable()) + put(base + 8, Ui.glow(Ui.item(Material.EMERALD, "Claim reward ยท " + m.title())), t -> act(backend().missionAction(player, m, true))); + else if (m.turnIn() != null) { + var turnIn = m.turnIn(); + String items = (turnIn.quantity() > 0 ? turnIn.quantity() + " " : "") + turnIn.label(); + put(base + 8, Ui.item(Material.CHEST, "Surrender " + items, + "Visit " + turnIn.role().replace('_', ' ')), click -> act(backend().missionTurnIn(player, m))); + } else if (m.state().equals("AVAILABLE")) + put(base + 8, Ui.item(Material.LIME_DYE, "Start ยท " + m.title()), t -> act(backend().missionAction(player, m, false))); + else if (m.state().equals("DONE")) + put(base + 8, Ui.item(Material.GREEN_STAINED_GLASS_PANE, "Done")); + else + put(base + 8, Ui.item(Material.GRAY_DYE, "In progress")); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/NativePresentationRoutes.java b/DuneMenus/src/main/java/com/dunerealms/menus/NativePresentationRoutes.java new file mode 100644 index 00000000..5b53ea34 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/NativePresentationRoutes.java @@ -0,0 +1,30 @@ +package com.dunerealms.menus; +import java.util.*; +import org.bukkit.command.*; +import org.bukkit.entity.Player; +/** Wrap only presentation entry points; retained Essentials keeps every targeted/financial operation. */ +final class NativePresentationRoutes implements AutoCloseable { + private final Map originals=new IdentityHashMap<>(); + private final Map wrappers=new IdentityHashMap<>(); + NativePresentationRoutes(DuneMenusPlugin plugin){ + for(String label:List.of("duneess:duneess","duneess:server","duneess:dune","duneess:exchange")){ + PluginCommand command=plugin.getServer().getPluginCommand(label); + if(command==null||!command.getPlugin().getName().equals("DuneEss")||originals.containsKey(command))continue; + CommandExecutor original=command.getExecutor(); + CommandExecutor wrapper=(sender,called,alias,args)->{ + String menu=route(command.getName(),args); + if(menu!=null&&sender instanceof Player player){plugin.openMenu(player,menu);return true;} + return original.onCommand(sender,called,alias,args); + }; + originals.put(command,original);wrappers.put(command,wrapper);command.setExecutor(wrapper); + } + } + static String route(String command,String[] args){ + if(command.equalsIgnoreCase("duneess")&&args.length==1){if(args[0].equalsIgnoreCase("travel"))return "travel";if(args[0].equalsIgnoreCase("menu"))return "hub";if(args[0].equalsIgnoreCase("exchange"))return "exchange";} + if(command.equalsIgnoreCase("exchange")&&args.length==0)return "exchange"; + if(command.equalsIgnoreCase("server")&&args.length==0)return "travel"; + if(command.equalsIgnoreCase("dune")&&args.length==1&&args[0].equalsIgnoreCase("menu"))return "hub"; + return null; + } + public void close(){originals.forEach((command,original)->{if(command.getExecutor()==wrappers.get(command))command.setExecutor(original);});originals.clear();wrappers.clear();} +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/NativeServiceMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/NativeServiceMenu.java new file mode 100644 index 00000000..fc3d10bc --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/NativeServiceMenu.java @@ -0,0 +1,11 @@ +package com.dunerealms.menus; +import java.util.Set;import org.bukkit.entity.Player; +/** Only the presentation changes; original JARVIS/native service callbacks own behaviour. */ +final class NativeServiceMenu extends Menu { + static final Set IDS=Set.of("hub","travel","exchange","clan","company","missions","spice","war","politics","lore","cookbook","mentat","house","equipment"); + private final String target; + NativeServiceMenu(DuneMenusPlugin plugin,Player player,Menu parent,String target){super(plugin,player,parent);this.target=target;} + @Override boolean launchNative(){plugin.openNativeService(player,target);return true;} + String id(){return target;}Skin skin(){return Skin.GOLD;}String title(){return "Imperial services";}int rows(){return 6;} + void draw(){throw new IllegalStateException("Native service presentation required");} +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/OrganisationChoiceMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/OrganisationChoiceMenu.java new file mode 100644 index 00000000..8a5dbc39 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/OrganisationChoiceMenu.java @@ -0,0 +1,48 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +final class OrganisationChoiceMenu extends Menu { + private final String kind; + private int page; + + OrganisationChoiceMenu(DuneMenusPlugin plugin, Player player, Menu parent, String kind) { + super(plugin, player, parent); + this.kind = kind; + } + + String id() { return kind + "-chooser"; } + Skin skin() { return kind.equals("clan") ? Skin.CLAN : Skin.COMPANY; } + String title() { return kind.equals("clan") ? "Your clans" : "Your companies"; } + int rows() { return 6; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + back(49); + load(backend().organisations(player, kind), organisations -> { + if (organisations.isEmpty()) { + put(22, Ui.item(Material.BARRIER, "No current membership")); + return; + } + if (organisations.size() == 1) { + go(detail(organisations.getFirst().id(), parent)); + return; + } + page = Math.min(page, (organisations.size() - 1) / 45); + int start = page * 45; + for (int i = start; i < Math.min(start + 45, organisations.size()); i++) { + var organisation = organisations.get(i); + put(i - start, Ui.item(Material.PAPER, "" + organisation.name(), "" + organisation.role()), + click -> go(detail(organisation.id(), this))); + } + if (page > 0) put(45, Ui.item(Material.ARROW, "Previous"), click -> { page--; redraw(); }); + if (start + 45 < organisations.size()) + put(53, Ui.item(Material.ARROW, "Next"), click -> { page++; redraw(); }); + }); + } + + private Menu detail(String id, Menu back) { + return kind.equals("clan") ? new ClanMenu(plugin, player, back, id) : new CompanyMenu(plugin, player, back, id); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/PoliticsMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/PoliticsMenu.java new file mode 100644 index 00000000..7580d6eb --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/PoliticsMenu.java @@ -0,0 +1,41 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** 6 rows. A centre column of decisions, cost on its left, effect on its right. One click enacts. */ +final class PoliticsMenu extends Menu { + private static final int PER_PAGE = 4; + private int page = 0; + + PoliticsMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); } + String id() { return "politics"; } + Skin skin() { return Skin.POLITICS; } + String title() { return "Decisions of Office"; } + String subtitle() { return "โ€œA decree is only words until someone enacts it.โ€"; } + int rows() { return 6; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + for (int r = 1; r <= 4; r++) { put(r * 9 + 3, Ui.pane(Material.PURPLE_STAINED_GLASS_PANE)); put(r * 9 + 5, Ui.pane(Material.PURPLE_STAINED_GLASS_PANE)); } + put(4, Ui.item(Material.LECTERN, "Your office")); + back(45); + load(backend().decisions(player), list -> { + int from = page * PER_PAGE; + for (int i = 0; i < PER_PAGE && from + i < list.size(); i++) { + var d = list.get(from + i); + int r = i + 1; + put(r * 9 + 2, Ui.item(Material.GOLD_NUGGET, "Cost", "" + d.cost())); + put(r * 9 + 6, Ui.item(Material.BOOK, "Effect", "" + d.effect())); + if (d.allowed()) + put(r * 9 + 4, Ui.glow(Ui.item(d.icon(), "" + d.title(), "Cost: " + d.cost(), + "Effect: " + d.effect(), "", "Click to enact")), t -> act(backend().enact(player, d))); + else + put(r * 9 + 4, Ui.item(Material.GRAY_DYE, "" + d.title(), "Not available to you")); + } + if (list.isEmpty()) put(22, Ui.item(Material.PAPER, "No decisions available")); + if (page > 0) put(48, Ui.item(Material.ARROW, "โ—€ Previous"), t -> { page--; redraw(); }); + if (from + PER_PAGE < list.size()) put(50, Ui.item(Material.ARROW, "Next โ–ถ"), t -> { page++; redraw(); }); + }); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/RiaClipboard.java b/DuneMenus/src/main/java/com/dunerealms/menus/RiaClipboard.java new file mode 100644 index 00000000..18a2af89 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/RiaClipboard.java @@ -0,0 +1,20 @@ +package com.dunerealms.menus; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.event.HoverEvent; +import net.kyori.adventure.text.format.NamedTextColor; + +/** A private native-client copy action; never submits or redeems a voucher. */ +final class RiaClipboard { + private RiaClipboard() {} + + static Component message(String reference) { + String complete=RiaReference.normalize(reference); + if(complete==null)throw new IllegalArgumentException("A complete RIA reference is required"); + return Component.text("RIA ID: ",NamedTextColor.GOLD) + .append(Component.text(complete,NamedTextColor.AQUA)) + .clickEvent(ClickEvent.copyToClipboard(complete)) + .hoverEvent(HoverEvent.showText(Component.text("Click to copy the complete RIA ID"))); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/RiaReference.java b/DuneMenus/src/main/java/com/dunerealms/menus/RiaReference.java new file mode 100644 index 00000000..66fef1e5 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/RiaReference.java @@ -0,0 +1,5 @@ +package com.dunerealms.menus; +final class RiaReference { + private RiaReference(){} + static String normalize(String text){if(text==null)return null;String value=text.strip().toUpperCase(java.util.Locale.ROOT);return value.matches("RIA-[A-F0-9]{32}")?value:null;} +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/Rihla.java b/DuneMenus/src/main/java/com/dunerealms/menus/Rihla.java new file mode 100644 index 00000000..ab4a1bcd --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/Rihla.java @@ -0,0 +1,15 @@ +package com.dunerealms.menus; + +/** Rihla transfer tax, for previews only. The backend is authoritative. Rules from the Rihla Money Transfer page. */ +final class Rihla { + private Rihla() {} + static final long THRESHOLD_MINOR = 300_000; // 3,000.00 DM + + /** 1% of the full amount up to and including 3,000 DM, 5% above; rounded UP to the next cent. */ + static long tax(long amountMinor) { + long pct = amountMinor <= THRESHOLD_MINOR ? 1 : 5; + return (amountMinor * pct + 99) / 100; + } + static long total(long amountMinor) { return amountMinor + tax(amountMinor); } + static String rateText() { return "1% up to 3,000 DM ยท 5% above"; } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/SavedItemMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/SavedItemMenu.java new file mode 100644 index 00000000..a955926d --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/SavedItemMenu.java @@ -0,0 +1,27 @@ +package com.dunerealms.menus; + +import java.util.UUID; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +final class SavedItemMenu extends Menu { + private final UUID design; + private final int revision; + + SavedItemMenu(DuneMenusPlugin plugin, Player player, UUID design, int revision) { + super(plugin, player, new HubMenu(plugin, player)); + this.design = design; + this.revision = revision; + } + + String id() { return "saved-item"; } + Skin skin() { return Skin.GOLD; } + String title() { return "Saved item preview"; } + int rows() { return 3; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + back(22); + load(backend().savedItem(player, design, revision), item -> put(13, item)); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/ServiceMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/ServiceMenu.java new file mode 100644 index 00000000..5d8cf3cc --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/ServiceMenu.java @@ -0,0 +1,79 @@ +package com.dunerealms.menus; + +import java.util.Map; +import java.util.UUID; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +final class ServiceMenu extends Menu { + private final String section; + private final String title; + private final String subtitle; + private final ItemStack[] cards; + private final Map actions; + private final UUID world; + + ServiceMenu(DuneMenusPlugin plugin, Player player, String section, String title, String description, + Inventory inventory, Map actions) { + super(plugin, player, null); + this.section = section; + this.title = displayTitle(title); + this.subtitle = description.lines().findFirst().orElse(""); + this.cards = inventory.getContents(); + this.actions = uniqueActions(actions); + for (int slot : actions.keySet()) if (!this.actions.containsKey(slot)) this.cards[slot] = null; + this.world = player.getWorld().getUID(); + } + + static String displayTitle(String title) { return title.replaceFirst("^NPC (dashboard|turn-in) ยท ", "").replaceFirst("^Your Mentat ยท ", "Your House adviser ยท "); } + + static Map uniqueActions(Map actions) { + var seen=java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + var result=new java.util.TreeMap(); + new java.util.TreeMap<>(actions).forEach((slot,action)->{if(seen.add(action))result.put(slot,action);}); + return Map.copyOf(result); + } + + String id() { return section; } + Skin skin() { + return switch (section) { + case "missions" -> Skin.QUEST; + case "exchange" -> Skin.MARKET; + case "spice" -> Skin.SPICE; + case "war" -> Skin.WAR; + case "politics" -> Skin.POLITICS; + case "travel" -> Skin.TRAVEL; + case "house", "mentat" -> Skin.HOUSE; + default -> Skin.GOLD; + }; + } + String title() { return title; } + String subtitle() { return subtitle; } + int rows() { return cards.length / 9; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + for (int slot = 0; slot < cards.length; slot++) { + ItemStack card = cards[slot]; + Runnable action = actions.get(slot); + if (card == null || action == null && card.getType().name().endsWith("_PANE") && + (card.getItemMeta() == null || !card.getItemMeta().hasLore())) continue; + if (action == null) put(slot, card); + else put(slot, card, click -> { + if (click != ClickType.LEFT && !(section.equals("exchange") && click == ClickType.RIGHT)) return; + Runnable run = () -> { + if (plugin.hasOpenMenu(player, this) && player.isOnline() && world.equals(player.getWorld().getUID())) { + end(); + action.run(); + } + }; + if (player.getOpenInventory().getTopInventory().getHolder() == this) + plugin.getServer().getScheduler().runTask(plugin, run); + else run.run(); + }); + } + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/ServiceSection.java b/DuneMenus/src/main/java/com/dunerealms/menus/ServiceSection.java new file mode 100644 index 00000000..45ae1dd5 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/ServiceSection.java @@ -0,0 +1,5 @@ +package com.dunerealms.menus; +import java.util.Locale; +final class ServiceSection { + static String of(String title){String t=title.toLowerCase(Locale.ROOT);if(t.contains("war")||t.contains("muster"))return "war";if(t.contains("quest")||t.contains("mission"))return "missions";if(t.contains("exchange"))return "exchange";if(t.contains("spice"))return "spice";if(t.contains("guild")||t.contains("travel")||t.contains("navigator"))return "travel";if(t.contains("clan")||t.contains("company")||t.contains("house"))return "house";return "hub";} +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/Skin.java b/DuneMenus/src/main/java/com/dunerealms/menus/Skin.java new file mode 100644 index 00000000..248856b9 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/Skin.java @@ -0,0 +1,21 @@ +package com.dunerealms.menus; + +import net.kyori.adventure.text.format.TextColor; +import org.bukkit.Sound; + +/** Title colour and sounds per function. The LAYOUT is owned by each menu class, so no two functions look alike. */ +record Skin(TextColor color, Sound open, Sound click) { + static final Skin GOLD = of("#D4AD5A", Sound.BLOCK_ENDER_CHEST_OPEN, Sound.UI_BUTTON_CLICK); + static final Skin TRAVEL = of("#7FD6E8", Sound.ITEM_LODESTONE_COMPASS_LOCK, Sound.BLOCK_AMETHYST_BLOCK_CHIME); + static final Skin MARKET = of("#F2C94C", Sound.ENTITY_VILLAGER_TRADE, Sound.BLOCK_NOTE_BLOCK_CHIME); + static final Skin CLAN = of("#4FBF8A", Sound.BLOCK_BELL_USE, Sound.ITEM_ARMOR_EQUIP_IRON); + static final Skin COMPANY = of("#5CC8D6", Sound.BLOCK_BARREL_OPEN, Sound.ITEM_ARMOR_EQUIP_GOLD); + static final Skin QUEST = of("#9FC27A", Sound.ITEM_BOOK_PAGE_TURN, Sound.UI_BUTTON_CLICK); + static final Skin SPICE = of("#E07B2E", Sound.BLOCK_SAND_PLACE, Sound.BLOCK_AMETHYST_BLOCK_CHIME); + static final Skin WAR = of("#D2584A", Sound.EVENT_RAID_HORN, Sound.ITEM_ARMOR_EQUIP_CHAIN); + static final Skin POLITICS = of("#B07CE8", Sound.ITEM_BOOK_PAGE_TURN, Sound.BLOCK_NOTE_BLOCK_BELL); + static final Skin HOUSE = of("#EED49A", Sound.BLOCK_BEACON_ACTIVATE, Sound.UI_BUTTON_CLICK); + static final Skin FORGE = of("#7FB2D9", Sound.BLOCK_ANVIL_USE, Sound.BLOCK_SMITHING_TABLE_USE); + + private static Skin of(String hex, Sound open, Sound click) { return new Skin(TextColor.fromHexString(hex), open, click); } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/SpiceMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/SpiceMenu.java new file mode 100644 index 00000000..a78f1411 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/SpiceMenu.java @@ -0,0 +1,31 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** 3 rows. A single pipeline: your spice, the Guild, a smuggler, and the purse. */ +final class SpiceMenu extends Menu { + SpiceMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); } + String id() { return "spice"; } + Skin skin() { return Skin.SPICE; } + String title() { return "Arrakis ยท The Spice Trade"; } + String subtitle() { return "โ€œThe spice flows, and fortunes flow with it.โ€"; } + int rows() { return 3; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + for (int s : new int[]{11, 13, 15}) put(s, Ui.pane(Material.ORANGE_STAINED_GLASS_PANE)); + back(18); + load(backend().spice(player), s -> { + put(10, Ui.item(Material.BLAZE_POWDER, Math.max(1, s.carried()), "Your spice", "" + s.carried() + " Melange")); + put(12, Ui.item(Material.GOLD_INGOT, "Sell through the Guild", + "Eligible units: " + s.guildCount(), + "", s.guildEnabled() ? "Click to sell all" : "Unavailable"), t -> { if (s.guildEnabled()) act(backend().sellSpice(player, "guild", s.guildCount())); }); + put(14, Ui.item(Material.SPYGLASS, "Sell through a smuggler", + "Eligible units: " + s.smugglerCount(), + "", s.smugglerEnabled() ? "Click to sell all" : "Unavailable"), t -> { if (s.smugglerEnabled()) act(backend().sellSpice(player, "smuggler", s.smugglerCount())); }); + var collect = Ui.item(Material.CHEST, "Collect payments", "Pending payments: " + s.pendingCount()); + put(16, s.pendingCount() > 0 ? Ui.glow(collect) : collect, t -> act(backend().collectSpice(player))); + }); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/SuppliedDocument.java b/DuneMenus/src/main/java/com/dunerealms/menus/SuppliedDocument.java new file mode 100644 index 00000000..78a83488 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/SuppliedDocument.java @@ -0,0 +1,64 @@ +package com.dunerealms.menus; +import java.util.*; +/** Dedicated presentation for the supplied menu definitions. Each card invokes its original slot directly. */ +final class SuppliedDocument { + static String clean(String s){return s==null?"":s.replaceAll("(?i)ยง[0-9a-fk-orx]","").replaceAll("[\\p{Co}\\p{Cc}&&[^\\n]]","").replace("\uFFFD","").trim();} + static String escape(String s){return clean(s).replace("&","&").replace("<","<").replace(">",">").replace("\"",""").replace("'","'");} + static String accent(String id){return switch(id){case "travel"->"#7fd6e8";case "clan"->"#4fbf8a";case "company"->"#5cc8d6";case "spice"->"#e07b2e";case "war"->"#d2584a";case "politics"->"#b07ce8";case "missions"->"#9fc27a";case "equipment"->"#7fb2d9";default->"#d4ad5a";};} + static String symbol(Card c){return switch(c.material()){case "compass"->"โœฅ";case "emerald"->"โ—†";case "anvil"->"โš’";case "writable_book","book"->"โ–ค";case "white_banner","green_banner"->"โš‘";case "gold_block","gold_ingot"->"โ—ˆ";case "blaze_powder"->"โœฆ";case "lectern"->"โ™œ";case "player_head"->"โ™Ÿ";case "nether_star"->"โœท";case "arrow"->"โ†";case "barrier"->"ร—";default->"โ—‡";};} + static List lines(String text,int width){List out=new ArrayList<>();String rest=clean(text);while(rest.length()>width){int split=rest.lastIndexOf(' ',width);if(split summary(Card card){List ordered=new ArrayList<>();for(String pattern:List.of("(?i).*\\bDM\\b.*","(?i).*(available|in stock).*","(?i).*seller:.*"))for(String line:card.lore())if(clean(line).matches(pattern)&&!ordered.contains(line))ordered.add(line);for(String line:card.lore())if(!ordered.contains(line))ordered.add(line);List out=new ArrayList<>();for(String line:ordered)out.addAll(lines(line,24));return out;} + static String image(Card c,Map images){String image=images.getOrDefault(c.slot(),"");return image.matches("pack/assets/[a-z0-9_/.-]+\\.png")&&!image.contains("..")?"":symbol(c);} + static boolean marketTool(Card c){return Set.of(1,4,7,45,46,48,49,50,53).contains(c.slot())&&Set.of("Buy","Buy items","Kits","My listings","Sell item","Imperial Codex","Collect purchases","Resume pending purchase","Previous","Next","Back").contains(clean(c.title()));} + static String kind(Card c){if(!c.material().equals("arrow"))return "card";String t=clean(c.title()).toLowerCase(Locale.ROOT);return t.contains("back")?"back":t.contains("previous")||t.contains("next")?"pager":"card";} + static String html(String id,String title,String subtitle,List cards,List info){return html(id,title,subtitle,cards,info,Map.of());} + static String html(String id,String title,String subtitle,List cards,List info,Map images){return html(id,title,subtitle,cards,info,images,-1);} + static String html(String id,String title,String subtitle,List cards,List info,Map images,int selected){ + boolean rihla=Set.of("atm","withdraw","deposit","redeem","receipt").contains(id); + String layout=switch(id){case "travel"->"constellation";case "clan","company","house","politics"->"council";case "missions","war"->"journal";case "bank","atm","withdraw","deposit","redeem","receipt","transfer"->"bank";default->"doors";}; + if(id.equals("house")&&(title.equals("Choose your House")||title.equals("Your House")))layout+=" house-choices"; + StringBuilder b=new StringBuilder("
THE IMPERIAL CONCOURSE

").append(escape(title)).append("

").append(escape(subtitle)).append("

"); + if(layout.equals("constellation"))b.append("
โœทSPACING GUILD
"); + if(id.equals("exchange")){b.append("");cards=cards.stream().filter(c->!marketTool(c)).toList();} + if(rihla){ + String logo="
"; + String replacement="
"; + int at=b.indexOf(logo);if(at>=0)b.replace(at,at+logo.length(),replacement); + int brandText=b.indexOf("THE IMPERIAL CONCOURSE");if(brandText>=0)b.replace(brandText,brandText+"THE IMPERIAL CONCOURSE".length(),"RIHLA MONEY TRANSFER"); + if(id.equals("withdraw")||id.equals("deposit")){ + b.append("");cards=cards.stream().filter(c->c.slot()!=24&&c.slot()!=36).toList(); + } + } + Card focused=null;for(Card c:cards)if(c.slot()==selected){focused=c;break;} + if(focused!=null){b.append("

").append(escape(focused.title())).append("

");for(String line:focused.lore())b.append("

").append(escape(line)).append("

");b.append("
");} + b.append("
");int index=0; + int summaryLimit=id.equals("exchange")?2:1; + for(Card c:cards){b.append(c.enabled()?"":"
");} + b.append("
");for(String line:info)b.append("

").append(escape(line)).append("

");return MenuPolish.apply(b.append("
โ—† J.A.R.V.I.S. โ—†THE SPICE MUST FLOW
").toString()); + } + private static final String CSS=""" + .locked.card,.constellation .locked.card{color:#c0c4c8;background:#262c30;border-color:#72777a}.locked.card p{color:#c0c4c8}.constellation .locked.card{height:84px} .rihla-brand{height:62px;overflow:hidden;background:#faf6ed;border:1px solid #b59349}.rihla-logo{display:block;width:146px;height:auto;align-self:flex-start}.cash-controls{display:flex;justify-content:space-between;position:relative;z-index:3;padding:10px 0}.cash-action{border:1px solid #c6a154;background:#123b2d;padding:12px 24px;font-size:16px}.cash-action[data-slot='24']{order:2;background:#3f5a26}.cash-action[data-slot='36']{order:1}.receipt .facts{background:#102a24;border:1px solid #b59349;padding:18px;margin:12px auto;max-width:650px}.receipt .facts p{font-size:14px;line-height:1.6} *{box-sizing:border-box}body{margin:0;padding:12px;background:#03100f;color:#f1e7cd;font-family:Georgia,serif;font-size:13px}button{font-family:Georgia,serif;color:#f4df9d;cursor:pointer}.frame{min-height:570px;border:2px solid #b69149;outline:1px solid #645334;outline-offset:5px;background:#081e1b;position:relative;overflow:hidden}header{height:78px;border-bottom:2px solid #ae8943;background:linear-gradient(90deg,#102f29,#041512);display:flex;align-items:center;padding:8px 22px;gap:22px}.brand{display:flex;align-items:center;gap:8px;color:#d6ad58;font-size:38px;border-right:1px solid #7c683b;padding-right:20px}.brand span{font-size:16px;line-height:17px;letter-spacing:3px}.heading{flex:1}small{font-size:10px;letter-spacing:3px;color:#ad985f}h1{font-size:26px;margin:5px 0 0;color:#eed995;letter-spacing:1px}.close{width:31px;height:31px;border:1px solid #a58b4d;background:#112922;font-size:24px}.scene{position:relative;min-height:411px;padding:0 28px;overflow:hidden;background:linear-gradient(#162d30,#53665a 58%,#a88c52)}.quote{text-align:center;font-style:italic;position:relative;z-index:1;padding:12px 0 8px;margin:0;color:#f4e7bf}.dune{position:absolute;left:-12%;width:125%;height:180px;border-radius:55% 70% 0 0;pointer-events:none}.rear{bottom:0;background:#b4955a;transform:rotate(-8deg)}.front{bottom:-90px;background:#635a38;transform:rotate(9deg)}.moon{position:absolute;right:15%;top:23px;background:#e4dbb6;border-radius:50%;width:45px;height:45px;opacity:.55}main{position:relative;z-index:2}.doors,.bank{display:flex;flex-wrap:wrap;gap:12px;justify-content:center;align-items:flex-start;padding:12px 0 35px}.card{background:linear-gradient(135deg,#173e35,#0c201d);border:1px solid #b59349;box-shadow:inset 0 0 0 3px #0a231f,0 3px 8px #071713;padding:9px;height:140px;position:relative;display:block;text-align:left;width:16.875%;overflow:hidden}.card>div{width:100%;min-width:0}.card .emblem{display:block;width:38px;height:38px;line-height:32px;margin:0 auto 4px;padding:2px;border:1px solid #8b784c;background:#09251f;box-shadow:inset 0 0 0 2px #143a30;text-align:center}.market-tools{display:flex;flex-wrap:wrap;gap:8px;justify-content:center;position:relative;z-index:2;padding:8px 0}.market-tool{display:flex;align-items:center;gap:6px;border:1px solid #8b784c;background:#12352c;padding:6px 10px;font-size:11px}.tool-icon{display:block;width:24px;height:24px;line-height:24px;text-align:center}.tool-icon .item-icon{width:24px;height:24px}.detail-link{position:absolute;right:10px;top:10px;font-size:10px;padding:4px 6px;border:1px solid #8b784c;background:#163a30;color:#e4cd91}.detail-link:hover{background:#315c45}.item-icon{width:32px;height:32px;object-fit:contain;image-rendering:pixelated}.brand-logo{width:158px;height:58px;object-fit:contain}.brand{width:180px;flex-shrink:0;padding-right:0;justify-content:center}.card h2{line-height:1.2}.card p{line-height:1.25;white-space:normal;overflow-wrap:break-word}.item-details{border:1px solid #786338;background:#102a24;margin-top:12px;padding:16px}.item-details p{overflow-wrap:break-word}.card h2{overflow-wrap:break-word;white-space:normal}.card:hover{background:linear-gradient(135deg,#315c45,#183c32);border-color:#f3d784}.emblem{font-size:26px;color:var(--accent);width:35px;flex-shrink:0;text-align:center}h2{font-size:14px;margin:0 0 6px}p{margin:2px 0;font-size:10px;line-height:1.35;color:#d1d3bc}.back{position:absolute;bottom:2px;left:0;background:#12372c;border:1px solid #ad8c48;padding:7px 12px;display:flex;align-items:center;gap:8px}.pager{border:1px solid #ad8c48;background:#12372c;padding:10px;display:flex;gap:8px;align-items:center}.back .emblem,.pager .emblem{font-size:17px;width:22px;height:22px;line-height:18px;border:0;padding:0;margin:0;box-shadow:none;background:transparent}.back .item-icon,.pager .item-icon{width:20px;height:20px}.back h2{margin:0;font-size:12px}.back p{display:none}.hub .card{width:16.5%;min-height:89px}.hub .emblem{font-size:26px}.journal{display:flex;flex-wrap:wrap;justify-content:center;gap:12px;padding:8px 0 45px}.journal .card{width:30%;height:140px;min-height:68px;padding:9px}.journal .card p{display:block;margin:2px 0}.council{display:flex;flex-wrap:wrap;gap:16px;justify-content:center;padding:20px 8% 44px}.council .card{width:34.5%;height:140px;min-height:115px;border-top:3px solid var(--accent)}.bank .card{width:22.5%;min-height:100px}.travel .scene{background:radial-gradient(ellipse at center,#123a40,#061317)}.travel .dune,.travel .moon{display:none}.constellation{height:350px;position:relative}.constellation .card{position:absolute;width:173px;height:72px;min-height:68px;border-color:#74aeb6;background:linear-gradient(135deg,#173e43,#091c23)}.constellation .card .emblem{display:none}.constellation .n0{top:0;left:36%}.constellation .n1{top:98px;left:0}.constellation .n2{top:98px;right:0}.constellation .n3{top:225px;left:12%}.constellation .n4{top:225px;right:12%}.constellation .back{bottom:0}.guild{position:absolute;top:168px;left:44%;font-size:52px;color:#c4dcdf;text-align:center}.guild span{display:block;font-size:11px;letter-spacing:2px}.orbit{position:absolute;border:1px solid #467b84;width:62%;height:170px;top:130px;left:19%;border-radius:50%;transform:rotate(24deg)}.orbit.two{transform:rotate(-24deg)}footer{height:76px;padding:9px 22px;background:#0b211c;border-top:1px solid #a88b47;display:flex;align-items:center;gap:22px}.facts{position:relative;padding:12px 0 24px;z-index:2}.facts p{font-size:11px;color:#c0c9b2}.seal{font-size:10px;letter-spacing:2px;color:#bda464}.war .scene{background:linear-gradient(#2e2424,#182c26)}.spice .scene{background:linear-gradient(#715232,#bc9251)}.politics .scene{background:linear-gradient(#2f2444,#132c27)} + /* Compact, centred layout at 75% of the canvas, rounded edges and a Dune palette. Later rules override the base styles above. */ + body{padding:10px 0;font-family:"Noto Sans","DejaVu Sans","Segoe UI",sans-serif;background:radial-gradient(ellipse at 50% 0,#0d2c30,#03100f 72%)} + .frame{width:75%;margin:0 auto;min-height:520px;border-radius:14px;outline-offset:4px;box-shadow:0 0 0 1px #3a2f18,0 10px 30px #02080a} + h1,h2,small,.seal{font-family:"Palatino Linotype","Book Antiqua","Noto Serif",Georgia,serif} + header{height:64px;padding:6px 18px;gap:16px;border-radius:12px 12px 0 0;border-bottom:2px solid #c9a24d;background:linear-gradient(90deg,#14382f,#06201b 60%,#0b2a3a)} + h1{font-size:22px;margin:3px 0 0}.brand{width:150px}.brand-logo{width:132px;height:48px}.close{border-radius:8px} + .scene{min-height:360px} + .card{width:18.5%;height:138px;padding:8px;border-radius:10px;box-shadow:inset 0 0 0 2px #0a231f,inset 0 0 14px #0f4a52,0 3px 8px #071713} + .card:hover{box-shadow:inset 0 0 0 2px #0a231f,inset 0 0 16px #c98a2c,0 3px 10px #071713} + .card .emblem{width:40px;height:40px;border-radius:8px;text-shadow:0 0 6px var(--accent)} + .hub .card{width:18.5%}.journal .card{width:31%;height:138px}.council .card{height:138px}.bank .card{width:24%}.constellation .card{border-radius:12px} + .house-choices .card{width:26%;height:105px;min-height:105px} + .house-choices .card .emblem{width:32px;height:32px;line-height:26px} + .house-choices .card .item-icon{width:26px;height:26px} + .house-choices .card h2{font-size:12px} + h2{font-size:13px}.item-icon{width:32px;height:32px} + .market-tool,.back,.pager,.cash-action,.detail-link{border-radius:8px}.item-details,.facts,.receipt .facts{border-radius:10px} + footer{height:52px;padding:6px 18px;border-radius:0 0 12px 12px;gap:18px;background:linear-gradient(90deg,#0b211c,#0a2330)} + .detail-link{right:6px;top:6px;font-size:9px;padding:2px 5px;opacity:.85} + .motto{color:#e0a64e} + """; +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/TransferMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/TransferMenu.java new file mode 100644 index 00000000..99d098f8 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/TransferMenu.java @@ -0,0 +1,43 @@ +package com.dunerealms.menus; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** 6 rows. Online players on top; amount chips and a live tax preview below. Clicking a person sends at once. */ +final class TransferMenu extends Menu { + private long amount; + + TransferMenu(DuneMenusPlugin plugin, Player p, Menu parent, long startMinor) { super(plugin, p, parent); this.amount = Math.max(100, startMinor); } + String id() { return "transfer"; } + Skin skin() { return Skin.GOLD; } + String title() { return "Rihla ยท Send money"; } + String subtitle() { return "Set the amount, then click the person to send to."; } + int rows() { return 6; } + + private void chip(int slot, long delta) { + boolean up = delta > 0; + put(slot, Ui.item(up ? Material.LIME_DYE : Material.RED_DYE, (up ? "+" : "โˆ’") + Ui.dm(Math.abs(delta))), + t -> { amount = Math.max(100, amount + delta); redraw(); }); + } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + for (int r = 4; r <= 4; r++) for (int c = 0; c < 9; c++) put(r * 9 + c, Ui.pane(Material.YELLOW_STAINED_GLASS_PANE)); + back(45); + int i = 0; + for (Player other : Bukkit.getOnlinePlayers()) { + if (other.getUniqueId().equals(player.getUniqueId()) || i >= 36) continue; + put(i++, Ui.head(other.getUniqueId(), "" + other.getName(), + "Send " + Ui.dm(amount) + " (tax " + Ui.dm(Rihla.tax(amount)) + ")", "", "Click to send"), + t -> act(backend().bankSend(player, other.getUniqueId(), amount))); + } + if (i == 0) put(13, Ui.item(Material.BARRIER, "Nobody else is online")); + chip(36, -100_000); chip(37, -10_000); chip(38, -1_000); + chip(42, 1_000); chip(43, 10_000); chip(44, 100_000); + put(40, Ui.glow(Ui.item(Material.GOLD_NUGGET, "" + Ui.dm(amount), "Amount sent"))); + put(49, Ui.item(Material.OAK_SIGN, "Cost to you: " + Ui.dm(Rihla.total(amount)), + "Amount: " + Ui.dm(amount), "Tax: " + Ui.dm(Rihla.tax(amount)) + " (" + Rihla.rateText() + ")", + "They receive the full " + Ui.dm(amount))); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/TravelMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/TravelMenu.java new file mode 100644 index 00000000..9f4d660e --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/TravelMenu.java @@ -0,0 +1,51 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** 6 rows. Worlds laid out as a constellation around the Guild, joined by cyan light lanes. */ +final class TravelMenu extends Menu { + private static final int[] STARS = {4, 19, 25, 37, 43}; + private static final int[] LANES = {13, 22, 30, 29, 32, 33, 39, 38, 41, 42}; + + TravelMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); } + String id() { return "travel"; } + Skin skin() { return Skin.TRAVEL; } + String title() { return "Spacing Guild ยท Passage"; } + String subtitle() { return "โ€œThe Guild charts the void. Name your destination.โ€"; } + int rows() { return 6; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + for (int s : LANES) put(s, Ui.pane(Material.CYAN_STAINED_GLASS_PANE)); + put(31, Ui.glow(Ui.item(Material.NETHER_STAR, "Spacing Guild", "Choose a world.", "One click books your passage."))); + back(45); + if (!backend().inGuildLobby(player)) { + put(31, Ui.glow(Ui.item(Material.NETHER_STAR, "Return to the Spacing Guild")), + click -> { + end(); + try { say(backend().returnToGuild(player)); } + catch (RuntimeException unavailable) { say(Backend.Result.no("The Guild could not confirm your return.")); } + }); + return; + } + load(backend().worlds(player), worlds -> { + for (int i = 0; i < Math.min(STARS.length, worlds.size()); i++) { + var w = worlds.get(i); + String fare = w.fareMinor() > 0 ? "Fare: " + Ui.dm(w.fareMinor()) : w.fareMinor() == 0 ? "Free passage" : ""; + var icon = Ui.item(w.up() ? w.icon() : Material.GRAY_DYE, (w.up() ? "" : "") + w.name(), + (w.tagline().startsWith("Unsanctioned") ? "" : "") + w.tagline(), w.online() < 0 ? "" : "Players: " + w.online(), w.up() ? fare : "", "", + w.up() ? "Click to travel" : ""); + if (w.up()) put(STARS[i], icon, t -> { end(); book(w); }); + else put(STARS[i], icon); + } + }); + } + + private void book(Backend.World destination) { + backend().book(player, destination).whenComplete((r, err) -> org.bukkit.Bukkit.getScheduler().runTask(plugin, () -> { + if (err != null) player.sendMessage(Ui.text("Passage is unavailable right now.")); + else say(r); + })); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/Ui.java b/DuneMenus/src/main/java/com/dunerealms/menus/Ui.java new file mode 100644 index 00000000..e45e58d8 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/Ui.java @@ -0,0 +1,63 @@ +package com.dunerealms.menus; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.UUID; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.TextDecoration; +import net.kyori.adventure.text.minimessage.MiniMessage; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +final class Ui { + private Ui() {} + private static final MiniMessage MM = MiniMessage.miniMessage(); + + static Component text(String s) { return MM.deserialize(s).decoration(TextDecoration.ITALIC, false); } + static String dm(long minor) { return BigDecimal.valueOf(minor, 2).toPlainString() + " DM"; } + + private static void style(ItemMeta m, String name, String... lore) { + m.displayName(text(name)); + if (lore.length > 0) m.lore(Arrays.stream(lore).map(Ui::text).toList()); + m.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ADDITIONAL_TOOLTIP); + } + + static ItemStack item(Material m, String name, String... lore) { return item(m, 1, name, lore); } + + static ItemStack item(Material m, int amount, String name, String... lore) { + var s = new ItemStack(m, Math.max(1, Math.min(64, amount))); + var meta = s.getItemMeta(); + style(meta, name, lore); + s.setItemMeta(meta); + return s; + } + + static ItemStack glow(ItemStack s) { + var meta = s.getItemMeta(); + meta.setEnchantmentGlintOverride(true); + s.setItemMeta(meta); + return s; + } + + static ItemStack pane(Material m) { + var s = new ItemStack(m); + var meta = s.getItemMeta(); + meta.displayName(Component.empty()); + meta.setHideTooltip(true); + s.setItemMeta(meta); + return s; + } + + static ItemStack head(UUID id, String name, String... lore) { + var s = new ItemStack(Material.PLAYER_HEAD); + var meta = (SkullMeta) s.getItemMeta(); + meta.setOwningPlayer(Bukkit.getOfflinePlayer(id)); + style(meta, name, lore); + s.setItemMeta(meta); + return s; + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/WarMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/WarMenu.java new file mode 100644 index 00000000..2e1528a3 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/WarMenu.java @@ -0,0 +1,66 @@ +package com.dunerealms.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +/** 6 rows. Left half = your roster (2 x 4), right half = status. Right-click a member to clear the slot. */ +final class WarMenu extends Menu { + private static final int[] ROSTER = {10, 11, 19, 20, 28, 29, 37, 38}; + + WarMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); } + String id() { return "war"; } + Skin skin() { return Skin.WAR; } + String title() { return "War Muster Room"; } + String subtitle() { return "โ€œName your fighters. The banners are already raised.โ€"; } + int rows() { return 6; } + + void draw() { + var red = Ui.pane(Material.RED_STAINED_GLASS_PANE); + var dark = Ui.pane(Material.BLACK_STAINED_GLASS_PANE); + for (int i = 0; i < 54; i++) put(i, i % 9 <= 3 ? red : dark); + back(45); + load(backend().war(player), w -> { + put(4, Ui.item(Material.RED_BANNER, "" + w.title())); + for (int i = 0; i < ROSTER.length; i++) { + final int idx = i; + String name = idx < w.roster().size() ? w.roster().get(idx) : null; + boolean empty = name == null || name.isBlank(); + var seat = empty + ? Ui.item(Material.GRAY_DYE, "Slot " + (idx + 1) + " ยท empty", "Click to choose someone") + : Ui.item(Material.PLAYER_HEAD, "Slot " + (idx + 1) + " ยท " + name, "Click to change", "Right-click to clear"); + if (!w.editable()) { put(ROSTER[idx], seat); continue; } + put(ROSTER[idx], seat, t -> { + if (!empty && t.isRightClick()) act(backend().warAssign(player, w, idx, null)); + else go(new RosterPicker(plugin, player, this, idx, w)); + }); + } + put(16, Ui.item(Material.WRITABLE_BOOK, "Status", w.status().stream().map(s -> "" + s).toArray(String[]::new))); + put(51, w.canLaunch() ? Ui.glow(Ui.item(Material.TNT, "Launch war")) : Ui.item(Material.GRAY_DYE, "Launch not ready"), + t -> { if (w.canLaunch()) act(backend().warLaunch(player,w)); }); + if (w.editable()) put(47, Ui.item(Material.WRITABLE_BOOK, "Save roster"), t -> act(backend().warSave(player,w))); + }); + put(49, Ui.item(Material.CLOCK, "Refresh"), t -> redraw()); + } + + /** Pick a member for one roster slot. One click assigns and returns. */ + static final class RosterPicker extends Menu { + private final int slot; + private final Backend.War war; + RosterPicker(DuneMenusPlugin plugin, Player p, Menu parent, int slot, Backend.War war) { super(plugin, p, parent); this.slot = slot; this.war = war; } + String id() { return "war-picker"; } + Skin skin() { return Skin.WAR; } + String title() { return "Choose for slot " + (slot + 1); } + int rows() { return 3; } + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + back(22); + load(backend().warCandidates(player,war), list -> { + for (int i = 0; i < Math.min(18, list.size()); i++) { + var m = list.get(i); + put(i, Ui.head(m.id(), "" + m.name(), "" + m.role(), "", "Click to assign"), + t -> load(backend().warAssign(player, war, slot, m.id()), r -> { say(r); go(parent); })); + } + }); + } + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/WarObjectiveMenu.java b/DuneMenus/src/main/java/com/dunerealms/menus/WarObjectiveMenu.java new file mode 100644 index 00000000..7ebc00fe --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/WarObjectiveMenu.java @@ -0,0 +1,38 @@ +package com.dunerealms.menus; + +import com.google.gson.JsonObject; +import net.kyori.adventure.text.minimessage.MiniMessage; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +final class WarObjectiveMenu extends Menu { + private final JsonObject target; + private final Runnable capture; + + WarObjectiveMenu(DuneMenusPlugin plugin, Player player, JsonObject target, Runnable capture) { + super(plugin, player, new HubMenu(plugin, player)); + this.target = target; + this.capture = capture; + } + + String id() { return "war-objective"; } + Skin skin() { return Skin.CLAN; } + String title() { return "Home Block deed"; } + int rows() { return 3; } + + void draw() { + backdrop(Material.BLACK_STAINED_GLASS_PANE); + back(18); + var text = MiniMessage.miniMessage(); + put(4, Ui.item(Material.FILLED_MAP, "" + text.escapeTags(target.get("name").getAsString()), + "Held by " + text.escapeTags(target.get("owner").getAsString()))); + if (target.get("canCapture").getAsBoolean()) { + put(22, Ui.item(Material.WRITABLE_BOOK, "Capture deed"), click -> { + end(); + capture.run(); + }); + } else { + put(22, Ui.item(Material.GRAY_DYE, "This deed cannot be contested by your roster")); + } + } +} diff --git a/DuneMenus/src/main/resources/config.yml b/DuneMenus/src/main/resources/config.yml new file mode 100644 index 00000000..7061ac2b --- /dev/null +++ b/DuneMenus/src/main/resources/config.yml @@ -0,0 +1,14 @@ +# Owner-supplied DuneMenus presentation, authoritative JARVIS backend only. +bedrock: + forms: true +fullscreen: + enabled: true +rihla: + enabled: true +resource-pack: + logo-in-title: false + font: "dunerealms:menu" + item-card-sha1: "" +atm: + bills: [10, 20, 50, 100, 500] + coins: [1, 5, 10] diff --git a/DuneMenus/src/main/resources/menu-art/art/logo.png b/DuneMenus/src/main/resources/menu-art/art/logo.png new file mode 100644 index 00000000..6fe26b5f Binary files /dev/null and b/DuneMenus/src/main/resources/menu-art/art/logo.png differ diff --git a/DuneMenus/src/main/resources/menu-art/art/rihla.png b/DuneMenus/src/main/resources/menu-art/art/rihla.png new file mode 100644 index 00000000..d7304816 Binary files /dev/null and b/DuneMenus/src/main/resources/menu-art/art/rihla.png differ diff --git a/DuneMenus/src/main/resources/plugin.yml b/DuneMenus/src/main/resources/plugin.yml new file mode 100644 index 00000000..e06caf6e --- /dev/null +++ b/DuneMenus/src/main/resources/plugin.yml @@ -0,0 +1,14 @@ +name: DuneMenus +version: ${version} +main: com.dunerealms.menus.DuneMenusPlugin +api-version: '1.21' +depend: [JarvisTranslator, DunerealmsGUI] +softdepend: [DuneEss, floodgate] +commands: + dm: + description: Open a DuneRealms menu + usage: /dm [hub|travel|exchange|clan|company|missions|spice|war|politics|house|equipment|reload] + aliases: [dunemenu] +permissions: + dunemenus.use: {default: true} + dunemenus.admin: {default: op} diff --git a/DuneMenus/src/rendererTest/java/com/dunerealms/menus/RendererVerification.java b/DuneMenus/src/rendererTest/java/com/dunerealms/menus/RendererVerification.java new file mode 100644 index 00000000..356ca93f --- /dev/null +++ b/DuneMenus/src/rendererTest/java/com/dunerealms/menus/RendererVerification.java @@ -0,0 +1,169 @@ +package com.dunerealms.menus; +import java.nio.file.*;import java.util.*;import java.awt.geom.*;import javax.imageio.ImageIO;import ai.resourcepack.ui.html.*;import ai.resourcepack.ui.html.css.Selector; +public class RendererVerification { + public static void main(String[]args)throws Exception{ + Path dir=Path.of(args[0]);Files.createDirectories(dir);var loader=new Page.Loader(false,dir.resolve("engine-cache"));int checked=0; + Files.createDirectories(dir.resolve("art"));Files.copy(Path.of("src/main/resources/menu-art/art/logo.png"),dir.resolve("art/logo.png"),StandardCopyOption.REPLACE_EXISTING); + Files.copy(Path.of("src/main/resources/menu-art/art/rihla.png"),dir.resolve("art/rihla.png"),StandardCopyOption.REPLACE_EXISTING); + for(String operation:List.of("withdraw","deposit","redeem","receipt")){ + List cash=new ArrayList<>();Map cashArt=new HashMap<>(); + if(operation.equals("withdraw")||operation.equals("deposit")){ + String[] names={"note_10","note_20","note_50","note_100","note_500","coin_050","coin_1dm","coin_2dm"};String[] amounts={"10.00","20.00","50.00","100.00","500.00","0.50","1.00","2.00"}; + for(int n=0;n cards=new ArrayList<>();int count=id.equals("exchange")?28:id.equals("travel")?5:8; + for(int n=0;n",marker); + String baseline=html.substring(0,marker)+html.substring(styleEnd); + var oldPage=Page.of(baseline,dir.resolve(id+"-before.html"),loader); + var oldFrame=HtmlRenderer.render(oldPage,1536,896,1.5,0,Selector.State.NONE); + var oldBox=oldFrame.boundsOf(oldPage.document.selectFirst("main .card")); + var newBox=frame.boundsOf(page.document.selectFirst("main .card")); + if(Math.abs(newBox.getWidth()/oldBox.getWidth()-.75)>.002 || Math.abs(newBox.getHeight()/oldBox.getHeight()-.75)>.002) + throw new AssertionError(id+" card size must be 75%: "+oldBox+" -> "+newBox); + + ImageIO.write(frame.image(),"png",dir.resolve(id+"-matrix-engine.png").toFile()); + int styleClose=html.indexOf(""); + String withoutTextClipping=html.substring(0,styleClose)+".card p,.card p+p,.house-choices .card p{max-height:none;overflow:visible}"+html.substring(styleClose); + var fullPage=Page.of(withoutTextClipping,dir.resolve(id+"-full-money.html"),loader); + var fullFrame=HtmlRenderer.render(fullPage,1536,896,1.5,0,Selector.State.NONE); + var displayed=page.document.select("main .card p");var complete=fullPage.document.select("main .card p"); + for(int n=0;n1)throw new AssertionError(id+" icon not centered "+card.slot()+" "+box+" vs "+bounds);} + for(var text:element.select("h2,p")){var box=frame.boundsOf(text);if(box!=null&&(box.getMinX()bounds.getMaxX()+1||box.getMinY()bounds.getMaxY()+1))throw new AssertionError(id+" text outside card "+card.slot()+" text="+box+" card="+bounds);} + double scroll=Math.max(0,Math.min(frame.maxScroll(),bounds.getCenterY()-260));var visible=HtmlRenderer.render(page,1536,896,1.5,scroll,Selector.State.NONE); + var at=visible.elementAt(bounds.getCenterX(),bounds.getCenterY()-scroll);var button=at==null?null:at.closest("[data-slot]"); + if(button==null||!button.attr("data-slot").equals(""+card.slot()))throw new AssertionError(id+" hit slot "+card.slot()+" at "+bounds+" scroll="+scroll+" got="+button); + checked++; + } + System.out.println(id+": parser clean; "+cards.size()+" action hitboxes; maxScroll="+frame.maxScroll()+"; render-and-hitbox-ms="+((System.nanoTime()-started)/1_000_000)); + } + String readOnlyHtml=SuppliedDocument.html("hub","Status","",List.of(new Card(13,"Account status",List.of("Read only"),"paper",false)),List.of()); + var readOnlyPage=Page.of(readOnlyHtml,dir.resolve("read-only.html"),loader);var readOnlyFrame=HtmlRenderer.render(readOnlyPage,1536,896,1.5,0,Selector.State.NONE); + int readOnlyMarker=readOnlyHtml.indexOf("/* compact-dune-cards */"),readOnlyEnd=readOnlyHtml.indexOf("",readOnlyMarker); + var readOnlyBefore=Page.of(readOnlyHtml.substring(0,readOnlyMarker)+readOnlyHtml.substring(readOnlyEnd),dir.resolve("read-only-before.html"),loader); + var readOnlyOldFrame=HtmlRenderer.render(readOnlyBefore,1536,896,1.5,0,Selector.State.NONE); + var readOnlyBox=readOnlyFrame.boundsOf(readOnlyPage.document.selectFirst("main .card"));var readOnlyOldBox=readOnlyOldFrame.boundsOf(readOnlyBefore.document.selectFirst("main .card")); + if(Math.abs(readOnlyBox.getHeight()/readOnlyOldBox.getHeight()-.75)>.002 || !readOnlyPage.document.select("main [data-slot]").isEmpty())throw new AssertionError("Read-only card sizing or authority changed"); + verifyNavigators(dir,loader); + verifyHouseChoices(dir,loader); + var actualIcon=Path.of("../network/resource-pack/central/overlay/assets/dunerealms/textures/item/equipment/legendary_mk14_axe.png");Path iconTarget=dir.resolve("pack/assets/dunerealms/textures/item/equipment/legendary_mk14_axe.png");Files.createDirectories(iconTarget.getParent());Files.copy(actualIcon,iconTarget,StandardCopyOption.REPLACE_EXISTING); + for(String name:List.of("item/iron_sword","block/cobblestone")){Path target=dir.resolve("pack/assets/minecraft/textures/"+name+".png");Files.createDirectories(target.getParent());Files.copy(Path.of("../network/resource-pack/vanilla-art/overlay/assets/minecraft/textures/"+name+".png"),target,StandardCopyOption.REPLACE_EXISTING);} + var listing=new Card(13,"\uE400ยง6Paul's chopper",List.of("LEGENDARY | MK XIV","Used by Paul himself.","Efficiency VIII","Fortune IV","Mending I","Unbreaking IV","Seller: J.A.R.V.I.S. HQ","1 available ยท 500.00 DM each"),"netherite_axe"); + String listingHtml=SuppliedDocument.html("exchange","Exchange ยท Buy","Authoritative item artwork",List.of(new Card(1,"Buy",List.of("Browse available items"),"emerald"),new Card(4,"Kits",List.of(),"netherite_chestplate"),new Card(7,"My listings",List.of(),"chest"),new Card(49,"Sell item",List.of(),"hopper"),new Card(50,"Collect purchases",List.of(),"chest_minecart"),listing,new Card(14,"Cobblestone",List.of("64 available ยท 1.00 DM each"),"cobblestone"),new Card(15,"Iron sword",List.of("1 available ยท 10.00 DM each"),"iron_sword")),List.of(),Map.of(13,"pack/assets/dunerealms/textures/item/equipment/legendary_mk14_axe.png",14,"pack/assets/minecraft/textures/block/cobblestone.png",15,"pack/assets/minecraft/textures/item/iron_sword.png"),13); + var listingPage=Page.of(listingHtml,dir.resolve("exchange-item.html"),loader);var listingFrame=HtmlRenderer.render(listingPage,1536,896,1.5,0,Selector.State.NONE);if(!listingPage.problems.isEmpty())throw new AssertionError(listingPage.problems.toString());ImageIO.write(listingFrame.image(),"png",dir.resolve("exchange-item-engine.png").toFile()); + for(var element:listingPage.document.select(".market-tool,[data-slot='1013']")){var bounds=listingFrame.boundsOf(element);var at=listingFrame.elementAt(bounds.getCenterX(),bounds.getCenterY());if(at==null||!at.closest("[data-slot]").attr("data-slot").equals(element.attr("data-slot")))throw new AssertionError("Detail control hitbox");} + System.out.println("PASS: "+checked+" direct action hitboxes across15 menu families."); + } + + private static void verifyHouseChoices(Path dir,Page.Loader loader)throws Exception{ + List cards=List.of(new Card(10,"Aerdrecht",List.of("Click to select this House"),"paper"), + new Card(13,"Harkveen",List.of("Click to select this House"),"paper"), + new Card(16,"Korenholt",List.of("Click to select this House"),"paper"), + new Card(29,"Vlierdam",List.of("Click to select this House"),"paper"), + new Card(33,"Imperial House with a longer name",List.of("Selected ยท confirm below"),"paper")); + String html=SuppliedDocument.html("house","Choose your House","",cards,List.of()); + var page=Page.of(html,dir.resolve("house-choices.html"),loader); + var frame=HtmlRenderer.render(page,1536,896,1.5,0,Selector.State.NONE); + if(!page.problems.isEmpty())throw new AssertionError(page.problems.toString()); + var rendered=page.document.select("main > button"); + if(rendered.size()!=5)throw new AssertionError("Expected five House actions"); + double firstRow=frame.boundsOf(rendered.first()).getMinY(); + int onFirstRow=0; + for(var element:rendered){ + var box=frame.boundsOf(element); + if(box==null||box.isEmpty())throw new AssertionError("Missing House card"); + if(Math.abs(box.getMinY()-firstRow)<1)onFirstRow++; + var hit=frame.elementAt(box.getCenterX(),box.getCenterY()); + if(hit==null||hit.closest("[data-slot]")!=element)throw new AssertionError("House action not reachable"); + for(var text:element.select("h2,p")){ + var bounds=frame.boundsOf(text); + if(bounds!=null&&(bounds.getMinX()box.getMaxX()+1 + ||bounds.getMinY()box.getMaxY()+1)) + throw new AssertionError("House text outside card: "+bounds+" vs "+box); + } + } + int expectedColumns=page.document.selectFirst("main").hasClass("house-choices")?4:3; + if(onFirstRow!=expectedColumns)throw new AssertionError("Expected "+expectedColumns+" compact House cards across, got "+onFirstRow); + ImageIO.write(frame.image(),"png",dir.resolve("house-choices-engine.png").toFile()); + System.out.println("House selector: five original actions, variant-preserving compact columns, contained text"); + } + + private static void verifyNavigators(Path dir,Page.Loader loader)throws Exception{ + List guild=List.of( + new Card(4,"Arrakduin",List.of("Fare: 125.00 DM"),"compass"), + new Card(19,"Kaladam",List.of("Your House has no Imperial passage for this destination."),"gray_dye",false), + new Card(25,"Giedermark",List.of("Current Guild embargo"),"gray_dye",false), + new Card(37,"Kaiterhof",List.of("Fare: 125.00 DM"),"compass"), + new Card(43,"Sigmadraken IV",List.of("World currently offline"),"gray_dye",false), + new Card(45,"Back",List.of(),"arrow")); + var owned=new ArrayList(); + for(int i=0;i<28;i++){ + int slot=10+i/7*9+i%7; + owned.add(new Card(slot,"Company Home Block "+(i+1), + List.of(i%2==0?"Kaladam ยท View fare":"No registered Home Block"), + i%2==0?"cyan_banner":"gray_dye",i%2==0)); + } + owned.add(new Card(45,"Back",List.of(),"arrow")); + owned.add(new Card(51,"Next page",List.of(),"arrow")); + var confirm=List.of(new Card(22,"Company Home Block",List.of("Smuggler fare: 125.07 DM"),"compass"), + new Card(31,"Confirm paid passage",List.of("Payment settles after arrival"),"lime_dye"), + new Card(45,"Back",List.of(),"arrow")); + for(var family:Map.of("guild",guild,"esmar",guild,"owned-home",owned,"confirm",confirm).entrySet()){ + String name=family.getKey(); + var cards=family.getValue(); + String html=SuppliedDocument.html(name.equals("guild")?"travel":"smuggler","Smuggler Navigator","Choose a destination",cards,List.of()); + var page=Page.of(html,dir.resolve(name+"-navigator.html"),loader); + var frame=HtmlRenderer.render(page,1536,896,1.5,0,Selector.State.NONE); + if(!page.problems.isEmpty())throw new AssertionError(name+" parser problems "+page.problems); + var rendered=page.document.select("main > *"); + if(rendered.size()!=cards.size())throw new AssertionError(name+" duplicate or missing rows: "+rendered.size()); + for(int index=0;indexbounds.getMaxX()+1 + ||box.getMinY()bounds.getMaxY()+1)) + throw new AssertionError(name+" text outside card "+card.title()+": "+box+" vs "+bounds); + } + if(card.enabled()){ + double scroll=Math.max(0,Math.min(frame.maxScroll(),bounds.getCenterY()-260)); + var visible=HtmlRenderer.render(page,1536,896,1.5,scroll,Selector.State.NONE); + var hit=visible.elementAt(bounds.getCenterX(),bounds.getCenterY()-scroll); + if(hit==null||hit.closest("[data-slot]")==null||!hit.closest("[data-slot]").attr("data-slot").equals(""+card.slot())) + throw new AssertionError(name+" unreachable action "+card.title()); + } + } + ImageIO.write(frame.image(),"png",dir.resolve(name+"-navigator-engine.png").toFile()); + System.out.println(name+" navigator: "+cards.size()+" distinct rows, contained text, disabled routes have no actions"); + } + } +} diff --git a/DuneMenus/src/test/java/com/dunerealms/menus/ChatPromptLifecycleTest.java b/DuneMenus/src/test/java/com/dunerealms/menus/ChatPromptLifecycleTest.java new file mode 100644 index 00000000..f48fea01 --- /dev/null +++ b/DuneMenus/src/test/java/com/dunerealms/menus/ChatPromptLifecycleTest.java @@ -0,0 +1,48 @@ +package com.dunerealms.menus; +import io.papermc.paper.event.player.AsyncChatEvent; +import java.util.*; +import java.util.function.Consumer; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitScheduler; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import static org.mockito.Mockito.*; +class ChatPromptLifecycleTest { + @AfterEach void clear(){ChatPrompt.clear();} + @Test void answerIsCapturedOnceAndCancelReturnsNull(){ + try(var bukkit=mockStatic(Bukkit.class)){ + var f=new Fixture(bukkit);Consumer done=mock(Consumer.class); + ChatPrompt.ask(f.player,"RIA ID",done);var event=f.chat("cancel");f.listener.onChat(event);f.run(); + verify(event).setCancelled(true);verify(done).accept(null);verifyNoMoreInteractions(done); + f.listener.onChat(f.chat("another line"));f.run();verifyNoMoreInteractions(done); + } + } + @Test void replacingPromptSuppressesAlreadyQueuedOldAnswerEvenWithSameCallback(){ + try(var bukkit=mockStatic(Bukkit.class)){ + var f=new Fixture(bukkit);Consumer done=mock(Consumer.class); + ChatPrompt.ask(f.player,"old",done);f.listener.onChat(f.chat("old reference"));ChatPrompt.ask(f.player,"new",done);f.run();verifyNoInteractions(done); + f.listener.onChat(f.chat("new reference"));f.run();verify(done).accept("new reference");verifyNoMoreInteractions(done); + } + } + @Test void disableAndWorldChangeCannotReopenTheOldScreen(){ + try(var bukkit=mockStatic(Bukkit.class)){ + var f=new Fixture(bukkit);Consumer done=mock(Consumer.class); + ChatPrompt.ask(f.player,"RIA",done);f.listener.onChat(f.chat("reference"));ChatPrompt.clear();f.run();verifyNoInteractions(done); + ChatPrompt.ask(f.player,"RIA",done);f.listener.onChat(f.chat("reference"));when(f.world.getUID()).thenReturn(UUID.randomUUID());f.run();verifyNoInteractions(done); + ChatPrompt.ask(f.player,"RIA",done);f.listener.onChat(f.chat("reference"));when(f.plugin.isEnabled()).thenReturn(false);f.run();verifyNoInteractions(done); + } + } + private static class Fixture { + final DuneMenusPlugin plugin=mock(DuneMenusPlugin.class);final Player player=mock(Player.class);final World world=mock(World.class); + final ChatPrompt listener=new ChatPrompt(plugin);final List queue=new ArrayList<>(); + Fixture(org.mockito.MockedStatic bukkit){ + when(plugin.isEnabled()).thenReturn(true);when(player.getUniqueId()).thenReturn(UUID.randomUUID());when(player.isOnline()).thenReturn(true);when(player.getWorld()).thenReturn(world);when(world.getUID()).thenReturn(UUID.randomUUID()); + var scheduler=mock(BukkitScheduler.class);bukkit.when(Bukkit::getScheduler).thenReturn(scheduler);doAnswer(c->{queue.add(c.getArgument(1));return null;}).when(scheduler).runTask(eq(plugin),any(Runnable.class)); + } + AsyncChatEvent chat(String value){var e=mock(AsyncChatEvent.class);when(e.getPlayer()).thenReturn(player);when(e.message()).thenReturn(Component.text(value));return e;} + void run(){var ready=List.copyOf(queue);queue.clear();ready.forEach(Runnable::run);} + } +} diff --git a/DuneMenus/src/test/java/com/dunerealms/menus/JarvisBackendTest.java b/DuneMenus/src/test/java/com/dunerealms/menus/JarvisBackendTest.java new file mode 100644 index 00000000..e05d99aa --- /dev/null +++ b/DuneMenus/src/test/java/com/dunerealms/menus/JarvisBackendTest.java @@ -0,0 +1,104 @@ +package com.dunerealms.menus; + +import com.google.gson.JsonObject; +import java.util.UUID; +import org.bukkit.Material; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class JarvisBackendTest { + @Test void purchaseUsesTheShownOpaqueIdPriceQuantityAndSameRequestReference() { + var offer = new Backend.Listing("offer:018a", "Spice", Material.PAPER, "Guild", 12550, 16, null, true); + UUID id = UUID.randomUUID(); + var request = JarvisBackend.purchaseRequest(offer, 4, id); + assertEquals("offer:018a", request.get("listingId").getAsString()); + assertEquals(12550, request.get("priceMinor").getAsLong()); + assertEquals(4, request.get("amount").getAsInt()); + assertEquals(request, JarvisBackend.purchaseRequest(offer, 4, id)); + } + + @Test void kitPurchaseUsesThePublishedVersion() { + var offer = new Backend.Listing("kit:019b", "Kit", Material.PAPER, "Guild", 75500, 1, 7, true); + var request = JarvisBackend.purchaseRequest(offer, 1, UUID.randomUUID()); + assertEquals("buy_kit", request.get("action").getAsString()); + assertEquals("kit:019b", request.get("kitsetId").getAsString()); + assertEquals(7, request.get("listingVersion").getAsInt()); + assertFalse(request.has("listingId")); + } + + @Test void journalDoesNotOfferNativeStartForWebsiteOrCompletedMissions() { + var row = new JsonObject(); + row.addProperty("canStart", true); + row.addProperty("state", "pending"); + assertTrue(JarvisBackend.canStart(row)); + row.addProperty("state", "completed"); + assertFalse(JarvisBackend.canStart(row)); + row.addProperty("state", "pending"); + var requirements = new JsonObject(); + requirements.addProperty("website", true); + requirements.addProperty("minecraft", false); + row.add("executionRequirements",requirements); + assertFalse(JarvisBackend.canStart(row)); + } + @Test void organisationActionRequiresTheShownIdentityAndRevision() { + var shown = new Backend.Org("Guild", "Member", 3, null, "clan:11", "8", ""); + var current = new JsonObject(); + current.addProperty("id", "clan:11"); + current.addProperty("authorityVersion", "8"); + assertTrue(JarvisBackend.matchesOrganisation(shown, current)); + assertFalse(JarvisBackend.matchesOrganisation(null, current)); + current.addProperty("authorityVersion", "9"); + assertFalse(JarvisBackend.matchesOrganisation(shown, current)); + current.addProperty("authorityVersion", "8"); + current.addProperty("id", "clan:12"); + assertFalse(JarvisBackend.matchesOrganisation(shown, current)); + } + + @Test void decisionRequiresOneEligibleAccountOrExplicitlyNoFunding() { + var decision = new JsonObject(); + decision.addProperty("feeMinor", "1500"); + var accounts = new com.google.gson.JsonArray(); + decision.add("accounts", accounts); + assertNull(JarvisBackend.decisionAccount(decision)); + var eligible = new JsonObject(); + eligible.addProperty("availableMinor", "1500"); + eligible.addProperty("id", "org:1"); + accounts.add(eligible); + assertEquals("org:1", JarvisBackend.decisionAccount(decision)); + var second = eligible.deepCopy(); + second.addProperty("id", "org:2"); + accounts.add(second); + assertNull(JarvisBackend.decisionAccount(decision)); + decision.addProperty("fundingRequired", false); + assertEquals("", JarvisBackend.decisionAccount(decision)); + decision.add("parameters", new JsonObject()); + assertNull(JarvisBackend.decisionAccount(decision)); + decision.remove("parameters"); + decision.addProperty("kind", "website"); + assertNull(JarvisBackend.decisionAccount(decision)); + } + @Test void selectedOrganisationResolvesExactMembershipAndNeverFallsBackToAnother() throws Exception { + var rows = new com.google.gson.JsonArray(); + var other = new JsonObject(); + other.addProperty("id", "clan:88"); + var chosen = new JsonObject(); + chosen.addProperty("id", "clan:11"); + rows.add(other); + rows.add(chosen); + assertSame(chosen, JarvisBackend.selectOrganisation(rows, "clan:11")); + rows.remove(chosen); + assertThrows(java.io.IOException.class, () -> JarvisBackend.selectOrganisation(rows, "clan:11")); + } @Test void nativeTurnInKeepsExactSupplyAndContactAndDisappearsWhenClaimable() { + var row = new JsonObject(); + row.addProperty("state", "active"); + var supply = new JsonObject(); + supply.addProperty("role", "stilgar"); + supply.addProperty("item", "jerboa_water_vial"); + supply.addProperty("label", "Water Vials"); + supply.addProperty("quantity", 6); + row.add("supply", supply); + assertEquals(new Backend.TurnIn("prepare_pol_supply","stilgar","jerboa_water_vial","Water Vials",6), + JarvisBackend.turnIn(row)); + row.addProperty("canClaim", true); + assertNull(JarvisBackend.turnIn(row)); + }} diff --git a/DuneMenus/src/test/java/com/dunerealms/menus/NativeMenuLifecycleTest.java b/DuneMenus/src/test/java/com/dunerealms/menus/NativeMenuLifecycleTest.java new file mode 100644 index 00000000..d6c50b44 --- /dev/null +++ b/DuneMenus/src/test/java/com/dunerealms/menus/NativeMenuLifecycleTest.java @@ -0,0 +1,116 @@ +package com.dunerealms.menus; + +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitScheduler; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +/** Exercises actual menu lifecycle without a server, inventory mutations or financial requests. */ +class NativeMenuLifecycleTest { + @Test void retainedActionSeesCurrentInventoryAndGateRemainsAuthoritative() { + try (var bukkit = mockStatic(Bukkit.class)) { + var f = new Fixture(bukkit); + JavaPlugin owner = mock(JavaPlugin.class); + when(owner.isEnabled()).thenReturn(true); + Inventory original = mock(Inventory.class); + when(original.getSize()).thenReturn(9); + when(original.getItem(0)).thenReturn(f.item); + AtomicBoolean allowed = new AtomicBoolean(false); + Runnable action = mock(Runnable.class); + var menu = spy(new LegacyInventoryMenu(f.plugin, owner, f.player, "Navigator", original, + Map.of(0, action), allowed::get)); + doNothing().when(menu).clickFeedback(); + when(f.plugin.hasOpenMenu(f.player, menu)).thenReturn(true); + menu.open(); + menu.handle(0, ClickType.LEFT); + verifyNoInteractions(action); + allowed.set(true); + doAnswer(call -> { assertTrue(menu.matches(original)); return null; }).when(action).run(); + menu.handle(0, ClickType.LEFT); + verify(action).run(); + assertFalse(menu.matches(mock(Inventory.class))); + when(f.plugin.hasOpenMenu(f.player, menu)).thenReturn(false); + menu.handle(0, ClickType.LEFT); + verifyNoMoreInteractions(action); + when(f.plugin.hasOpenMenu(f.player, menu)).thenReturn(true); + when(owner.isEnabled()).thenReturn(false); + menu.handle(0, ClickType.LEFT); + verifyNoMoreInteractions(action); + } + } + + @Test void navigationSurvivesSlowReadsButActionAndStaleCompletionDoNot() { + try (var bukkit = mockStatic(Bukkit.class)) { + var f = new Fixture(bukkit); + var scheduler = mock(BukkitScheduler.class); + bukkit.when(Bukkit::getScheduler).thenReturn(scheduler); + doAnswer(call -> { ((Runnable) call.getArgument(1)).run(); return null; }) + .when(scheduler).runTask(eq(f.plugin), any(Runnable.class)); + class LoadingMenu extends Menu { + final CompletableFuture first = new CompletableFuture<>(); + int page, actions, completions; + LoadingMenu() { super(f.plugin, f.player, null); } + String id(){return "hub";} Skin skin(){return Skin.GOLD;} + String title(){return "Loading";} int rows(){return 1;} + boolean renderWhileLoading(){return true;} + boolean navigationWhileLoading(int slot){return slot==0;} + protected void clickFeedback(){} + void draw(){ + put(0,f.item,click->{page++;redraw();}); + put(1,f.item,click->actions++); + if(page==0)load(first,value->completions++); + } + } + var menu = new LoadingMenu(); + menu.open(); + verify(f.provider).open(eq(f.player),any(),any(),any()); + menu.handle(1,ClickType.LEFT); + assertEquals(0,menu.actions); + menu.handle(0,ClickType.LEFT); + assertEquals(1,menu.page); + menu.first.complete("old page"); + assertEquals(0,menu.completions); + menu.handle(1,ClickType.LEFT); + assertEquals(1,menu.actions); + menu.closed(); + menu.handle(1,ClickType.LEFT); + assertEquals(1,menu.actions); + } + } + + private static final class Fixture { + final DuneMenusPlugin plugin=mock(DuneMenusPlugin.class); + final Player player=mock(Player.class); + final FullscreenProvider provider=mock(FullscreenProvider.class); + final ItemStack item=mock(ItemStack.class); + Fixture(org.mockito.MockedStatic bukkit){ + var world=mock(World.class);when(world.getUID()).thenReturn(UUID.randomUUID()); + when(player.getWorld()).thenReturn(world);when(player.isOnline()).thenReturn(true); + when(plugin.modeFor(player)).thenReturn(Menu.Mode.FULLSCREEN); + when(plugin.titleFor(any(Menu.class))).thenReturn(Component.text("Menu")); + when(plugin.fullscreen()).thenReturn(provider);when(provider.open(any(),any(),any(),any())).thenReturn(true); + var meta=mock(ItemMeta.class);when(meta.displayName()).thenReturn(Component.text("Action")); + when(item.getItemMeta()).thenReturn(meta);when(item.getType()).thenReturn(org.bukkit.Material.PAPER); + when(item.clone()).thenReturn(item); + var contents=new HashMap();var inventory=mock(Inventory.class); + when(inventory.getSize()).thenReturn(9); + doAnswer(c->{contents.clear();return null;}).when(inventory).clear(); + doAnswer(c->{contents.put(c.getArgument(0),c.getArgument(1));return null;}).when(inventory).setItem(anyInt(),any()); + when(inventory.getItem(anyInt())).thenAnswer(c->contents.get(c.getArgument(0))); + when(inventory.getContents()).thenAnswer(c->{var result=new ItemStack[9];contents.forEach((slot,value)->result[slot]=value);return result;}); + bukkit.when(()->Bukkit.createInventory(any(org.bukkit.inventory.InventoryHolder.class),anyInt(),any(Component.class))).thenReturn(inventory); + } + } +} diff --git a/DuneMenus/src/test/java/com/dunerealms/menus/NativePresentationRoutesTest.java b/DuneMenus/src/test/java/com/dunerealms/menus/NativePresentationRoutesTest.java new file mode 100644 index 00000000..27e25598 --- /dev/null +++ b/DuneMenus/src/test/java/com/dunerealms/menus/NativePresentationRoutesTest.java @@ -0,0 +1,6 @@ +package com.dunerealms.menus; +import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*; +class NativePresentationRoutesTest { + @Test void oldNpcAndLobbyTravelEntryOpensNewPresentation(){assertEquals("travel",NativePresentationRoutes.route("duneess",new String[]{"travel"}));assertEquals("travel",NativePresentationRoutes.route("server",new String[]{}));assertEquals("hub",NativePresentationRoutes.route("dune",new String[]{"menu"}));assertEquals("hub",NativePresentationRoutes.route("duneess",new String[]{"menu"}));assertEquals("exchange",NativePresentationRoutes.route("duneess",new String[]{"exchange"}));assertEquals("exchange",NativePresentationRoutes.route("exchange",new String[]{}));} + @Test void targetedTravelAndFinancialAdministrationStayWithWorkingBackend(){for(String[] args:new String[][]{{"travel","arrakis"},{"pay","somebody","100"},{"sell"},{"balance"},{"admin","solari","set"},{"menu","reload"}})assertNull(NativePresentationRoutes.route("duneess",args));assertNull(NativePresentationRoutes.route("server",new String[]{"arrakis"}));assertNull(NativePresentationRoutes.route("dune",new String[]{"admin"}));} +} diff --git a/DuneMenus/src/test/java/com/dunerealms/menus/RetainedNativeMenusAbiTest.java b/DuneMenus/src/test/java/com/dunerealms/menus/RetainedNativeMenusAbiTest.java new file mode 100644 index 00000000..15455a8d --- /dev/null +++ b/DuneMenus/src/test/java/com/dunerealms/menus/RetainedNativeMenusAbiTest.java @@ -0,0 +1,13 @@ +package com.dunerealms.menus; +import java.util.*;import java.util.function.BooleanSupplier;import org.bukkit.entity.Player;import org.bukkit.inventory.Inventory;import org.bukkit.plugin.java.JavaPlugin;import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*; +/** Contract taken from actual retained Core/Ess NativeMenus, not from the new renderer implementation. */ +class RetainedNativeMenusAbiTest { + @Test void retainedInventoryFacadeCanFindExactBooleanShowSignatures()throws Exception{ + assertEquals(boolean.class,DuneMenusPlugin.class.getMethod("show",JavaPlugin.class,Player.class,String.class,Inventory.class,Map.class,BooleanSupplier.class).getReturnType()); + assertEquals(boolean.class,DuneMenusPlugin.class.getMethod("show",JavaPlugin.class,Player.class,String.class,Inventory.class,Map.class).getReturnType()); + } + @Test void retainedCurrentCloseAndChoiceFacadeArePresent()throws Exception{ + assertEquals(boolean.class,DuneMenusPlugin.class.getMethod("isCurrent",Player.class,Inventory.class).getReturnType());assertEquals(void.class,DuneMenusPlugin.class.getMethod("close",Player.class,Inventory.class).getReturnType());assertEquals(boolean.class,DuneMenusPlugin.class.getMethod("showChoices",JavaPlugin.class,Player.class,String.class,String.class,List.class).getReturnType()); + } + @Test void allPublicServiceRoutesHaveNativeEntriesInsteadOfPartialAlternateBackends(){assertEquals(Set.of("hub","travel","exchange","clan","company","missions","spice","war","politics","lore","cookbook","mentat","house","equipment"),NativeServiceMenu.IDS);} +} diff --git a/DuneMenus/src/test/java/com/dunerealms/menus/RiaClipboardTest.java b/DuneMenus/src/test/java/com/dunerealms/menus/RiaClipboardTest.java new file mode 100644 index 00000000..4b2a664c --- /dev/null +++ b/DuneMenus/src/test/java/com/dunerealms/menus/RiaClipboardTest.java @@ -0,0 +1,20 @@ +package com.dunerealms.menus; + +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class RiaClipboardTest { + @Test void copiesTheCompleteReferenceWithoutSubmittingAnyCommand(){ + String id="RIA-0123456789ABCDEF0123456789ABCDEF"; + var message=RiaClipboard.message(" "+id.toLowerCase(java.util.Locale.ROOT)+" "); + assertEquals(ClickEvent.Action.COPY_TO_CLIPBOARD,message.clickEvent().action()); + assertEquals(id,message.clickEvent().value()); + assertTrue(PlainTextComponentSerializer.plainText().serialize(message).contains(id)); + } + @Test void incompleteOrForeignReferencesCannotBecomeCopyActions(){ + for(String invalid:new String[]{null,"","RIA-1234","ITM-0123456789ABCDEF0123456789ABCDEF"}) + assertThrows(IllegalArgumentException.class,()->RiaClipboard.message(invalid)); + } +} diff --git a/DuneMenus/src/test/java/com/dunerealms/menus/RihlaReceiptTest.java b/DuneMenus/src/test/java/com/dunerealms/menus/RihlaReceiptTest.java new file mode 100644 index 00000000..4ba55d4a --- /dev/null +++ b/DuneMenus/src/test/java/com/dunerealms/menus/RihlaReceiptTest.java @@ -0,0 +1,14 @@ +package com.dunerealms.menus; +import com.google.gson.JsonObject; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +class RihlaReceiptTest { + @Test void recoveredReceiptUsesSettledFactsInsteadOfNewSelection(){ + var row=new JsonObject();row.addProperty("state","committed");row.addProperty("amountMinor",2000);row.addProperty("voucher","RIA-0123456789ABCDEF0123456789ABCDEF");row.addProperty("recovered",true); + var result=JarvisBackend.cashResult(row); + assertTrue(result.ok());assertEquals(2000,result.receipt().amountMinor());assertTrue(result.receipt().recovered());assertEquals(row.get("voucher").getAsString(),result.receipt().riaId()); + } + @Test void nonCommittedResultsDoNotProduceSuccessfulReceipts(){ + for(String state:new String[]{"aborted","prepared","queued"}){var row=new JsonObject();row.addProperty("state",state);row.addProperty("amountMinor",5000);var result=JarvisBackend.cashResult(row);assertFalse(result.ok());assertNull(result.receipt());} + } +} diff --git a/DuneMenus/src/test/java/com/dunerealms/menus/RihlaScreenTest.java b/DuneMenus/src/test/java/com/dunerealms/menus/RihlaScreenTest.java new file mode 100644 index 00000000..1ca9a947 --- /dev/null +++ b/DuneMenus/src/test/java/com/dunerealms/menus/RihlaScreenTest.java @@ -0,0 +1,25 @@ +package com.dunerealms.menus; +import java.util.*; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +class RihlaScreenTest { + @Test void referenceEntryAcceptsOnlyCompleteRiaReferences(){ + assertEquals("RIA-0123456789ABCDEF0123456789ABCDEF",RiaReference.normalize(" ria-0123456789abcdef0123456789abcdef ")); + for(String invalid:List.of("RIA-","RIA-1234","