feat: integrate Beta 1.0.2.0 Pillager update with paid raid recovery
All checks were successful
DuneRealms Plugin CI / plugins (push) Successful in 3m8s

This commit is contained in:
unimatrixgit 2026-11-29 16:27:58 +01:00
commit c599b2b708
57 changed files with 4107 additions and 23 deletions

View file

@ -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

View file

@ -50,6 +50,8 @@ jobs:
run: |
set -euo pipefail
python3 tools/test_plugin_ci_policy.py -v
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_menu_pack.py -v
python3 tools/test_plugin_backend_abi.py -v
@ -60,7 +62,7 @@ jobs:
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 plugin-artifacts/
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/

View file

@ -1,7 +1,7 @@
import java.security.MessageDigest
plugins { java }
group = "com.dunerealms"
version = "2.0.6"
version = "2.0.7-pillager1"
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")

View file

@ -0,0 +1,88 @@
{
"baselineSource": "67db68218c206dce239181a5b201bbc75b18a620",
"menuSha256": "7a34431c626a4c5bb2bb7faeb9bb3bc21c4bd3933841ffa31fdd5dbd6e99f606",
"guiSha256": "fb58d724d3421faea2e0600c197145f887a2ce6e016cec95621759cb855a179c",
"classes": {
"com/dunerealms/menus/AtmMenu$Tab.class": "4c226d7b400c6b0d8b0da9c9cb1d1c90ddcce076bab77aee7ec86b604c013c12",
"com/dunerealms/menus/AtmMenu.class": "3139e7085a1779098e8651f4fc79b32ae67de58fe61a59155843c6e9bd93eb62",
"com/dunerealms/menus/Backend$Account.class": "c91c493daaff1d3b0d44e6eec9ee834eac7dd43d0519abc8c9c3d6fa7302a573",
"com/dunerealms/menus/Backend$CashReceipt.class": "6c0cce779a86b21c499f464f5d51c5d63afcbcee91f83605220d0f13d0fc9474",
"com/dunerealms/menus/Backend$Decision.class": "6b9dad7f1c76898ca9b5cf4c6094379f31bfdb55bb572af14433a707a3e18d56",
"com/dunerealms/menus/Backend$House.class": "359a29f3844b0adc339ee818a2e74c0072aa9e323231beed53fa01d3598a990e",
"com/dunerealms/menus/Backend$Issued.class": "d849d618cb558647614d8840bfb845ee53ed7e7e9b487a35cfbdfd49d643aee3",
"com/dunerealms/menus/Backend$Listing.class": "946aa1d772f26b8ca388e69156cf5d2603c6fe2ed386de0c4a8d4c9964892290",
"com/dunerealms/menus/Backend$Member.class": "e31756a242f067a460e0eb5a810cf98556655867c0e7d2ef8b9944e7cba2ec61",
"com/dunerealms/menus/Backend$Mission.class": "a18c3b60ecded6492bf34e30996d3316e309851a4af1a4d3b466bb74c131ecad",
"com/dunerealms/menus/Backend$Org.class": "32d6de3157c02a7fcb9c51cab4b1c6dc5021fa2a9bd5621f15838ed48605cfc4",
"com/dunerealms/menus/Backend$Page.class": "4db5f3b7c0c9351cbb8e7ffedbc4ce699484f7006e3a76fe91cb9d262e8c6abd",
"com/dunerealms/menus/Backend$Refit.class": "62f8c8e22c6501b4c5f5016aa789e72d6cb46281d0fd003434c33577c0724275",
"com/dunerealms/menus/Backend$Result.class": "622ba092d3b508359220e97904c5caee0123f502ae6f3be233a24f0a002f8114",
"com/dunerealms/menus/Backend$Spice.class": "02014640f621831d308b3c8dd2c5f33030868149bdba752ddb47bb160ac78906",
"com/dunerealms/menus/Backend$Transfer.class": "19b544bce87ef758a0b36c1d1bd53a9a29971ef7334e69648a14922eea2ad3d0",
"com/dunerealms/menus/Backend$TurnIn.class": "8f410b3670512c986f12fd32ab938494227bf8bc4d9f38c7a0aaf353d54dd9cd",
"com/dunerealms/menus/Backend$Unavailable.class": "1a3dbccc3e905aab90559b14720fa1292589af2a2feae261ac551310de3c413c",
"com/dunerealms/menus/Backend$Voucher.class": "efd3d8464c8403ef5a08f8df9c74f133c52b977c14a8f1017bce227503a731b4",
"com/dunerealms/menus/Backend$War.class": "c3e8eed3fec4ea52b605d8d2db589d0a929b2cff2c1b8cc6e02aec7012e25203",
"com/dunerealms/menus/Backend$World.class": "8416163a53327f10c7ca52e92bd0afbb0bec35afb724d012fe5ea3bf45847dfa",
"com/dunerealms/menus/Backend.class": "a490987b7800cf55df5a3b8740d95c07f27675ead8e36638f47e1ecd7325ca72",
"com/dunerealms/menus/BankMenu.class": "63e2377eabcea4aa9e03213ba4adae340cd1ef6dc8d9d897b9716be7e49e7148",
"com/dunerealms/menus/Bedrock$Impl.class": "5866fde424ec4c4ba3cd3a1961310e3b66704aa30a70fa7f92f4240c0611040a",
"com/dunerealms/menus/Bedrock.class": "c60a70bcd61d30b92625a42f44e6366c8d55a3b309a98708ea2459a92f38ca2e",
"com/dunerealms/menus/CanvasProvider.class": "109a7f8fac866257ec6e4c5bcfd387275908b256b0ebb5fbc0cd17dd2e16b3b8",
"com/dunerealms/menus/Card.class": "22c3ce603d231ed05528d98a1b4f37b2d9e423d269ad574b2112cc28a578308d",
"com/dunerealms/menus/ChatPrompt$Request.class": "da98f79aed1ef40caac09a5f5584ea50d6f0c95eab53d13976f6e509f9df961b",
"com/dunerealms/menus/ChatPrompt.class": "6e34287689cc31e08537b355d1e2f4069ec650bbeac8429279adeb53756e9b61",
"com/dunerealms/menus/ClanMenu.class": "86508bc2888293eceed45e11065a31d9402c98cb66efa53ae7478db29f5b458e",
"com/dunerealms/menus/CompanyMenu.class": "0a118ea6a4257d9164491caf32386816d88ba9bf44cb15bc08736a0becedc40d",
"com/dunerealms/menus/DuneMenusPlugin.class": "c8d050ef6232632610360ea9e64aa49a4bacbe72e31eeb5edac324aa93852444",
"com/dunerealms/menus/EquipmentMenu.class": "c4ea1697c20beecaea3a576c991559b7fa3b3a2b9ddd6129e2149f1bd00b098e",
"com/dunerealms/menus/ExchangeMenu.class": "db57f723a4dc846baaccd28dfac1f48472b34b90aaf061c7675ff5c9d30b259c",
"com/dunerealms/menus/FullscreenProvider$Screen.class": "238e31298d0e290af49ef35f2085c16b468e1da78af70efe1bc255d0a553e332",
"com/dunerealms/menus/FullscreenProvider.class": "a6821d4f7a6684cc2d3d1314087bf78bec192ce7bfa3ac4f4a0ced5054d02d2a",
"com/dunerealms/menus/HouseMenu.class": "9453c5b2a267f9b64c0eaef13d9353b3bbc08e97052f71ebe83693b114bb1dcf",
"com/dunerealms/menus/HubMenu.class": "5572e40a53832e09fd1f7ce8482718254fc0cc683b127a4a554e8f7017383b26",
"com/dunerealms/menus/JarvisBackend$1.class": "30377d34b3bf3a287d0a6a7c1e4cedf8bccfff1735c1f6216737b219f0df6285",
"com/dunerealms/menus/JarvisBackend$Call.class": "0af950a6b5846d0c524d823970ae6488fb3da239dec0d9a6c7b930c78f064a78",
"com/dunerealms/menus/JarvisBackend$Purchase.class": "9b63fe7864c1a9169ed6788bcd493c7eeb3887b6d48bd57e94bc71b2189e7bec",
"com/dunerealms/menus/JarvisBackend$RefitPermit.class": "a28a30c94e80767ed54e46ead60b52a0d851d43cdf9cc342e7baffd2d671d41f",
"com/dunerealms/menus/JarvisBackend$RihlaSend.class": "933d93150fb5c68b56eabba26bb8ebf10eb94b849f3b4a2f61253150a9fcf296",
"com/dunerealms/menus/JarvisBackend$WarDraft.class": "ec550cee5f20c9e79cf7e6259ebaf8cb811e37e850a9656d1fbb4b5f1f93d49b",
"com/dunerealms/menus/JarvisBackend.class": "bc4beca5f4766c98d12d322411c1c10557db2a7f241f2d388bfa8689774cd314",
"com/dunerealms/menus/LegacyInventoryMenu.class": "bcaee7ae906c0b2a9f75d7e9ed92c3bf6c392a9ecd6c6616835406d4e2a6a1bb",
"com/dunerealms/menus/LoreArchiveMenu.class": "6f7933010e8807069759c6b16557eab7313532f953ee4bf2561531d3091e1268",
"com/dunerealms/menus/MembersMenu.class": "f7290e8f7a6ae7c9e67f6ec2507a8807e6fcaab0e8a770e4da4d5dac1b83c41b",
"com/dunerealms/menus/MentatMenu.class": "341db5340c59b901aa8a51d3d70e47e61a17483c671dcf3d45e6a27bb14cacec",
"com/dunerealms/menus/Menu$Button.class": "dfd48ddabda117e17d5eb5f4f7aee1f932f6dca97cc4ecdda8ba33f006ecfb7b",
"com/dunerealms/menus/Menu$Mode.class": "e4ed8db89f3a75be6d6225a3ebbbc93c669ef8a32ff293968b7570fdbf12156d",
"com/dunerealms/menus/Menu.class": "d6ea5bdbc96acdacac824fe5c89dea30e07371cf542edc793c8881f382c1f1ab",
"com/dunerealms/menus/MenuArt.class": "5cd57e8df5892f3386d2793c6ada2abbd3b87f4e5af74e295a05320685577155",
"com/dunerealms/menus/MenuListener.class": "c3081d5cb9b8760fa7c940643803e6931cb0c60dbfe41f4816dc75de8f10ef1c",
"com/dunerealms/menus/MissionsMenu.class": "73969d7a3874f8936deaf1c1046bcbc6d53c6e316f12809da9036d552f089cb0",
"com/dunerealms/menus/NativePresentationRoutes.class": "52e64deb769843abf129a6dc48f2cd19a6e212e025a34ddb4701a5867d25051f",
"com/dunerealms/menus/NativeServiceMenu.class": "97810c2c31c5a6c9c9953c561f231d11c11ef13498aeed8f2557a7a2d3734edc",
"com/dunerealms/menus/OrganisationChoiceMenu.class": "4cd42793d0761962ce9a3af620a21c6c71a6408f3543c562c76ea05b798ce63a",
"com/dunerealms/menus/PoliticsMenu.class": "968eaae1c0c23983f87be1baa404910def7de3800b6c82ea38448448788dc522",
"com/dunerealms/menus/RiaReference.class": "773d1740ba67db16dbc2d419395fce05b75a35893a282c795cdb480377ea106b",
"com/dunerealms/menus/Rihla.class": "82fe7207fd31a27230cdc1bf6dc45f9367779f461edb23fb9d0c714863731522",
"com/dunerealms/menus/SavedItemMenu.class": "4e0a8ba414fff023418dd5e3c2ea8e123c93ef976fec1d2cb8958a4bab86702d",
"com/dunerealms/menus/ServiceMenu.class": "c48ecdf85724c8b8a46c54ce7322e10cf74e650c73402431ab185d02b427e7e9",
"com/dunerealms/menus/ServiceSection.class": "91ff4915f60ac4727c2d3235819c42b81e39ee34d6e3dc69dbd5b171a3724700",
"com/dunerealms/menus/Skin.class": "3492a72b0da22912cc988dd56ec86374cff08c52519ae0419b715e292818903e",
"com/dunerealms/menus/SpiceMenu.class": "085900eab9cb3c8e80349ef876e285a048e11fc4a9923e2fcb277196765deff1",
"com/dunerealms/menus/SuppliedDocument.class": "4e074b76a64af7346325d95685ad20edcbc12fd07355fc0e705f1b4d71df758d",
"com/dunerealms/menus/TransferMenu.class": "e09fe8a5e0e83c482bf091aa3d21c83c00e20c15eacf9953029430ffaa97bf6b",
"com/dunerealms/menus/TravelMenu.class": "2e34acd98a95c104d3bb18bc3757602a116c0f0f560587c67cfbd149eeeaf33b",
"com/dunerealms/menus/Ui.class": "9762bc714937a88d0ad9af9d9505a6788d551d7529fb8d565360ae7ff0e2fd6a",
"com/dunerealms/menus/WarMenu$RosterPicker.class": "d7e004a022a713892f33aa613d008dd98311464ba62e105ca840f90d1d964df4",
"com/dunerealms/menus/WarMenu.class": "dd5f3f2a3db583054b90b5ec099b191926052a041db8aa5b26736a22d7ae1f87",
"com/dunerealms/menus/WarObjectiveMenu.class": "a4129b32cba83a1579af6c268d872f655e5e6807340d4b729a5adad0e0b59843"
},
"unchangedResourceTreeSha256": "21ff7ca4636a2284a931d3ac36f6a213130013e15b6b8b382dd79ccf15e28bee",
"allowedResourceChanges": [
"menu-art/pack/assets/dunerealms/items/pillager/goldmembers_shovel_mk8.json",
"menu-art/pack/assets/dunerealms/models/item/pillager/goldmembers_shovel_mk8.json",
"menu-art/pack/assets/dunerealms/textures/item/pillager/goldmembers_shovel_mk8.png",
"plugin.yml"
],
"guiContentTreeSha256": "ec86f395b004d0814f30e60c5ff8505242af7cca76d5af1f58d9608d53f6055f"
}

View file

@ -1,7 +1,7 @@
plugins { java }
group = "com.example"
version = "1.0.14-arrakis2"
version = "1.0.15-pillager1"
repositories {
mavenCentral()

View file

@ -38,6 +38,15 @@ public final class DuneTerrain extends JavaPlugin implements Listener {
private static final String[] PLANETS = {"arrakis", "giedi_prime", "kaitain", "caladan", "sigma_draconis_iv"};
private NamespacedKey sietchLootIdKey;
final SpiceDepositProvenance spiceProvenance=new SpiceDepositProvenance();
public boolean isGeneratedSpiceDeposit(Block block){return block!=null&&block.getWorld().getName().equals("arrakis")&&SpiceDepositProvenance.authentic(block);}
@EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void placedSpice(org.bukkit.event.block.BlockPlaceEvent event){if(event.getBlock().getWorld().getName().equals("arrakis")){SpiceDepositProvenance.forget(event.getBlock());SpiceDepositProvenance.invalidateBloom(event.getBlock());}}
@EventHandler public void spiceChunkPopulated(org.bukkit.event.world.ChunkPopulateEvent event){if(event.getWorld().getName().equals("arrakis"))spiceProvenance.commitBloom(event.getChunk());}
@EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void brokenBloom(org.bukkit.event.block.BlockBreakEvent event){if(event.getBlock().getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(event.getBlock());}
@EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void movedBloom(org.bukkit.event.block.BlockPistonExtendEvent event){for(Block block:event.getBlocks())if(block.getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(block);}
@EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void retractedBloom(org.bukkit.event.block.BlockPistonRetractEvent event){for(Block block:event.getBlocks())if(block.getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(block);}
@EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void explodedBloom(org.bukkit.event.entity.EntityExplodeEvent event){for(Block block:event.blockList())if(block.getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(block);}
@EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void changedBloom(org.bukkit.event.entity.EntityChangeBlockEvent event){if(event.getBlock().getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(event.getBlock());}
private final Map<UUID, PersonalLoot> openSietchLoot = new HashMap<>();
private record PersonalLoot(Inventory inventory, String id) {}
@ -124,6 +133,7 @@ public final class DuneTerrain extends JavaPlugin implements Listener {
private void detonateSpiceBlow(Block center) {
if (center.getType() != Material.MAGMA_BLOCK) return;
boolean authenticatedBloom=SpiceDepositProvenance.takeBloom(center);
World world = center.getWorld();
int x = center.getX(), z = center.getZ(), baseY = center.getY() - 1;
for (int dx = -1; dx <= 1; dx++) for (int dz = -1; dz <= 1; dz++)
@ -154,6 +164,7 @@ public final class DuneTerrain extends JavaPlugin implements Listener {
for (Block block : candidates) {
if (placed >= targetDeposits) break;
block.setType(Material.SUSPICIOUS_SAND, false);
if(authenticatedBloom)SpiceDepositProvenance.mark(block.getState());
placed++;
}
announceSpiceBloom(center.getLocation());
@ -367,7 +378,7 @@ public final class DuneTerrain extends JavaPlugin implements Listener {
PlanetChunkGenerator(DuneTerrain plugin, String planet) { this.plugin = plugin; this.planet = planet; }
@Override public List<BlockPopulator> getDefaultPopulators(World world) {
return planet.equals("arrakis") && world.getName().equalsIgnoreCase("arrakis")
? List.of(new SietchPopulator(plugin), new SpiceBlowPopulator(plugin), new DesertVillages(plugin), new HarkonnenFortress(plugin)) : List.of();
? List.of(new SietchPopulator(plugin), new SpiceBlowPopulator(plugin), new DesertVillages(plugin), new HarkonnenFortress(plugin),plugin.spiceProvenance) : List.of();
}
@Override public void generateNoise(WorldInfo world, Random random, int chunkX, int chunkZ, ChunkData data) {
if(TemperateLandscape.enabled(planet)){
@ -420,10 +431,11 @@ public final class DuneTerrain extends JavaPlugin implements Listener {
}
boolean arrakisWorld = planet.equals("arrakis") && world.getName().equalsIgnoreCase("arrakis");
if (arrakisWorld) placeOasisTree(data, chunkX, chunkZ, heights, minY, maxY);
var emittedSpice=new ArrayList<SpiceDepositProvenance.Position>();
if (arrakisWorld) {
placeDarkstoneIsland(data, chunkX, chunkZ, heights, minY, maxY);
placeSpiceDeposits(data, heights, random, minY, maxY);
placeRandomSpicePatch(data, chunkX, chunkZ, heights);
placeSpiceDeposits(data, heights, random, minY, maxY,emittedSpice);
placeRandomSpicePatch(data, chunkX, chunkZ, heights,emittedSpice);
if (plugin.getConfig().getBoolean("dense-spice.enabled", true)) {
int spacing = Math.max(128, plugin.getConfig().getInt("dense-spice.spacing", 512));
for (int x=0;x<16;x++) for(int z=0;z<16;z++)
@ -432,6 +444,7 @@ public final class DuneTerrain extends JavaPlugin implements Listener {
}
}
placeOres(data, random, path, minY, maxY);
if(arrakisWorld&&plugin.spiceProvenance!=null)plugin.spiceProvenance.capture(world,chunkX,chunkZ,emittedSpice,data);
}
@Override public BiomeProvider getDefaultBiomeProvider(WorldInfo worldInfo) {
return new PlanetBiomeProvider(plugin, planet);
@ -548,16 +561,16 @@ public final class DuneTerrain extends JavaPlugin implements Listener {
Material material = Material.matchMaterial(name == null ? "" : name);
return material == null ? fallback : material;
}
private void placeSpiceDeposits(ChunkData data, int[][] heights, Random random, int minY, int maxY) {
private void placeSpiceDeposits(ChunkData data, int[][] heights, Random random, int minY, int maxY,List<SpiceDepositProvenance.Position> emitted) {
int count = Math.max(0, plugin.getConfig().getInt("spice-deposits.per-chunk", 2));
for (int i = 0; i < count; i++) {
int x = random.nextInt(16), z = random.nextInt(16), y = heights[x][z];
Material surface = data.getType(x, y, z);
if (y + 1 < maxY && y > minY && (surface == Material.SAND || surface == Material.RED_SAND))
data.setBlock(x, y, z, Material.SUSPICIOUS_SAND);
if (y + 1 < maxY && y > minY && (surface == Material.SAND || surface == Material.RED_SAND)){
data.setBlock(x, y, z, Material.SUSPICIOUS_SAND);emitted.add(new SpiceDepositProvenance.Position(x,y,z));}
}
}
private void placeRandomSpicePatch(ChunkData data, int chunkX, int chunkZ, int[][] heights) {
private void placeRandomSpicePatch(ChunkData data, int chunkX, int chunkZ, int[][] heights,List<SpiceDepositProvenance.Position> emitted) {
String path = "spice-deposits.patches.";
if (!plugin.getConfig().getBoolean(path + "enabled", true)) return;
int spacing = Math.max(128, plugin.getConfig().getInt(path + "region-spacing", 600));
@ -585,7 +598,7 @@ public final class DuneTerrain extends JavaPlugin implements Listener {
if (hashUnit(blockSeed) >= density) continue;
int y = heights[x][z];
if (data.getType(x, y, z) == Material.SAND || data.getType(x, y, z) == Material.RED_SAND)
data.setBlock(x, y, z, Material.SUSPICIOUS_SAND);
{data.setBlock(x, y, z, Material.SUSPICIOUS_SAND);emitted.add(new SpiceDepositProvenance.Position(x,y,z));}
}
}
}
@ -947,6 +960,7 @@ public final class DuneTerrain extends JavaPlugin implements Listener {
for (int dx = -1; dx <= 1; dx++) for (int dz = -1; dz <= 1; dz++)
if (region.isInRegion(x + dx, y, z + dz)) region.setType(x + dx, y, z + dz, Material.MAGMA_BLOCK);
if (region.isInRegion(x, y + 1, z)) region.setType(x, y + 1, z, Material.MAGMA_BLOCK);
if(plugin.spiceProvenance!=null)plugin.spiceProvenance.bloom(world,chunkX,chunkZ,new SpiceDepositProvenance.Position(x,y+1,z));
}
}
}

View file

@ -0,0 +1,53 @@
package com.example.duneterrain;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.*;
import org.bukkit.block.*;
import org.bukkit.generator.*;
import org.bukkit.persistence.PersistentDataType;
/** Marks only coordinates actually emitted by our spice generator or authenticated bloom. */
final class SpiceDepositProvenance extends BlockPopulator {
static final NamespacedKey KEY=new NamespacedKey("dunerealms","generated_spice_deposit");
record Position(int x,int y,int z){}
private record ChunkKey(UUID world,int x,int z){}
private final Map<ChunkKey,Set<Position>> pending=new ConcurrentHashMap<>();
private final Map<ChunkKey,Position> blooms=new ConcurrentHashMap<>();
void bloom(WorldInfo world,int cx,int cz,Position position){if(world.getUID()!=null&&blooms.size()<4096)blooms.put(new ChunkKey(world.getUID(),cx,cz),position);}
void commitBloom(Chunk chunk){
Position p=blooms.remove(new ChunkKey(chunk.getWorld().getUID(),chunk.getX(),chunk.getZ()));if(p==null)return;
if(chunk.getBlock(p.x()&15,p.y(),p.z()&15).getType()==Material.MAGMA_BLOCK)chunk.getPersistentDataContainer().set(bloomKey(p.x(),p.y(),p.z()),PersistentDataType.BYTE,(byte)1);
}
private static NamespacedKey bloomKey(int x,int y,int z){return new NamespacedKey("dunerealms","generated_spice_bloom_"+(x&15)+"_"+y+"_"+(z&15));}
static boolean takeBloom(Block center){
var data=center.getChunk().getPersistentDataContainer();var key=bloomKey(center.getX(),center.getY(),center.getZ());
boolean authentic=Byte.valueOf((byte)1).equals(data.get(key,PersistentDataType.BYTE));data.remove(key);return authentic;
}
static void invalidateBloom(Block changed){
World world=changed.getWorld();for(int dx=-1;dx<=1;dx++)for(int dz=-1;dz<=1;dz++)for(int dy=-1;dy<=1;dy++){
int x=changed.getX()+dx,z=changed.getZ()+dz;if(!world.isChunkLoaded(x>>4,z>>4))continue;
world.getChunkAt(x>>4,z>>4).getPersistentDataContainer().remove(bloomKey(x,changed.getY()+dy,z));
}
}
void capture(WorldInfo world,int cx,int cz,Collection<Position> positions,ChunkGenerator.ChunkData data){
if(world.getUID()==null||pending.size()>=4096)return; // Fail closed; never grow an unbounded generation cache.
Set<Position> actual=new HashSet<>();
for(Position p:positions)if(data.getType(p.x(),p.y(),p.z())==Material.SUSPICIOUS_SAND)actual.add(new Position(cx*16+p.x(),p.y(),cz*16+p.z()));
if(!actual.isEmpty())pending.put(new ChunkKey(world.getUID(),cx,cz),Set.copyOf(actual));
}
@Override public void populate(WorldInfo world,Random random,int cx,int cz,LimitedRegion region){
Set<Position> positions=pending.remove(new ChunkKey(world.getUID(),cx,cz));if(positions==null)return;
for(Position p:positions)if(region.isInRegion(p.x(),p.y(),p.z())&&region.getType(p.x(),p.y(),p.z())==Material.SUSPICIOUS_SAND){
BlockState state=region.getBlockState(p.x(),p.y(),p.z());mark(state);
}
}
static boolean mark(BlockState state){
if(state.getType()!=Material.SUSPICIOUS_SAND||!(state instanceof BrushableBlock tile)||tile.getLootTable()!=null||tile.getItem()!=null&&!tile.getItem().isEmpty())return false;
tile.getPersistentDataContainer().set(KEY,PersistentDataType.BYTE,(byte)1);return tile.update(true,false);
}
static boolean authentic(Block block){
if(block.getType()!=Material.SUSPICIOUS_SAND||!(block.getState() instanceof BrushableBlock tile)||tile.getLootTable()!=null||tile.getItem()!=null&&!tile.getItem().isEmpty())return false;
return Byte.valueOf((byte)1).equals(tile.getPersistentDataContainer().get(KEY,PersistentDataType.BYTE));
}
static void forget(Block block){if(block.getState() instanceof TileState tile){tile.getPersistentDataContainer().remove(KEY);tile.update(false,false);}}
}

View file

@ -1,5 +1,5 @@
name: DuneTerrain
version: 1.0.14-arrakis2
version: 1.0.15-pillager1
main: com.example.duneterrain.DuneTerrain
api-version: '1.21'
load: STARTUP

View file

@ -0,0 +1,49 @@
package com.example.duneterrain;
import java.util.*;
import org.bukkit.*;
import org.bukkit.block.*;
import org.bukkit.generator.*;
import org.bukkit.persistence.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class SpiceDepositProvenanceTest {
@Test void onlyRecordedGeneratorCoordinatesAreMarkedAndPopulationConsumesPendingState(){
var provenance=new SpiceDepositProvenance();WorldInfo world=mock(WorldInfo.class);when(world.getUID()).thenReturn(UUID.randomUUID());
var data=mock(ChunkGenerator.ChunkData.class);when(data.getType(1,70,2)).thenReturn(Material.SUSPICIOUS_SAND);when(data.getType(3,70,4)).thenReturn(Material.SAND);
provenance.capture(world,-1,2,List.of(new SpiceDepositProvenance.Position(1,70,2),new SpiceDepositProvenance.Position(3,70,4)),data);
LimitedRegion region=mock(LimitedRegion.class);when(region.isInRegion(-15,70,34)).thenReturn(true);when(region.getType(-15,70,34)).thenReturn(Material.SUSPICIOUS_SAND);
BrushableBlock tile=mock(BrushableBlock.class);when(tile.getType()).thenReturn(Material.SUSPICIOUS_SAND);var pdc=mock(PersistentDataContainer.class);when(tile.getPersistentDataContainer()).thenReturn(pdc);
when(region.getBlockState(-15,70,34)).thenReturn(tile);
provenance.populate(world,new Random(1),-1,2,region);provenance.populate(world,new Random(1),-1,2,region);
verify(pdc,times(1)).set(SpiceDepositProvenance.KEY,PersistentDataType.BYTE,(byte)1);verify(tile).update(true,false);
verify(region,never()).getBlockState(-13,70,36);verify(region,times(1)).getBlockState(anyInt(),anyInt(),anyInt());
}
@Test void playerPlacedOrOldUnmarkedSandAndCompressedDisksAreNotAuthentic(){
Block block=mock(Block.class);when(block.getType()).thenReturn(Material.SUSPICIOUS_SAND);BrushableBlock tile=mock(BrushableBlock.class);when(block.getState()).thenReturn(tile);
var pdc=mock(PersistentDataContainer.class);when(tile.getPersistentDataContainer()).thenReturn(pdc);
assertFalse(SpiceDepositProvenance.authentic(block));
when(pdc.get(SpiceDepositProvenance.KEY,PersistentDataType.BYTE)).thenReturn((byte)1);assertTrue(SpiceDepositProvenance.authentic(block));
when(block.getType()).thenReturn(Material.DRIED_KELP_BLOCK);assertFalse(SpiceDepositProvenance.authentic(block));
SpiceDepositProvenance.forget(block);verify(pdc).remove(SpiceDepositProvenance.KEY);
}
@Test void changedOrMissingBlockEntityFailsClosed(){
assertFalse(SpiceDepositProvenance.mark(mock(BlockState.class)));
BrushableBlock tile=mock(BrushableBlock.class);when(tile.getType()).thenReturn(Material.SAND);assertFalse(SpiceDepositProvenance.mark(tile));
verify(tile,never()).getPersistentDataContainer();
}
@Test void onlyGeneratedBloomOriginCanAuthenticateItsOutputAndItIsSingleUse(){
var provenance=new SpiceDepositProvenance();World world=mock(World.class);UUID id=UUID.randomUUID();when(world.getUID()).thenReturn(id);
Chunk chunk=mock(Chunk.class);when(chunk.getWorld()).thenReturn(world);when(chunk.getX()).thenReturn(2);when(chunk.getZ()).thenReturn(3);
Block center=mock(Block.class);when(center.getChunk()).thenReturn(chunk);when(center.getX()).thenReturn(34);when(center.getY()).thenReturn(71);when(center.getZ()).thenReturn(50);when(center.getType()).thenReturn(Material.MAGMA_BLOCK);when(chunk.getBlock(2,71,2)).thenReturn(center);
var pdc=mock(PersistentDataContainer.class);when(chunk.getPersistentDataContainer()).thenReturn(pdc);Map<NamespacedKey,Byte> values=new HashMap<>();
doAnswer(c->{values.put(c.getArgument(0),c.getArgument(2));return null;}).when(pdc).set(any(NamespacedKey.class),eq(PersistentDataType.BYTE),anyByte());
when(pdc.get(any(NamespacedKey.class),eq(PersistentDataType.BYTE))).thenAnswer(c->values.get(c.getArgument(0)));
doAnswer(c->{values.remove(c.getArgument(0));return null;}).when(pdc).remove(any(NamespacedKey.class));
assertFalse(SpiceDepositProvenance.takeBloom(center)); // A player-built magma pattern has no producer record.
provenance.bloom(world,2,3,new SpiceDepositProvenance.Position(34,71,50));provenance.commitBloom(chunk);
assertTrue(SpiceDepositProvenance.takeBloom(center));assertFalse(SpiceDepositProvenance.takeBloom(center));
provenance.commitBloom(chunk);assertFalse(SpiceDepositProvenance.takeBloom(center));
}
}

View file

@ -1,6 +1,6 @@
plugins { java }
group = "com.dunerealms"
version = "0.5.35"
version = "0.5.36-pillager1"
repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/") }
dependencies {
compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")

View file

@ -0,0 +1,23 @@
package com.dunerealms.jarvis;
import java.util.List;
import java.util.function.Consumer;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.*;
import org.bukkit.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataType;
final class GoldmemberShovel {
static final String ID="goldmembers_shovel_mk8";
static ItemStack create(Consumer<ItemStack> stamp){
// The existing spice harvester requires a netherite shovel. Appearance is gold through item_model.
ItemStack item=new ItemStack(Material.NETHERITE_SHOVEL);var meta=item.getItemMeta();
meta.displayName(Component.text("Goldmember's Shovel MK VIII",NamedTextColor.GOLD).decoration(TextDecoration.ITALIC,false));
meta.lore(List.of(Component.text("\"I love gooooold!\"",NamedTextColor.YELLOW).decoration(TextDecoration.ITALIC,true),
Component.text("A Dutch collector's gilded blade, chasing gold beneath the spice.",NamedTextColor.GRAY)));
meta.setItemModel(new NamespacedKey("dunerealms","pillager/"+ID));
var pdc=meta.getPersistentDataContainer();pdc.set(new NamespacedKey("executableitems","ei-id"),PersistentDataType.STRING,ID);
pdc.set(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING,"shovel");
pdc.set(ItemOrigin.WORLD,PersistentDataType.STRING,"arrakis");item.setItemMeta(meta);stamp.accept(item);return item;
}
}

View file

@ -0,0 +1,305 @@
package com.dunerealms.jarvis;
import static com.dunerealms.jarvis.NativeReflection.call;
import static com.dunerealms.jarvis.NativeReflection.callStatic;
import java.io.File;
import java.util.*;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.title.Title;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.block.banner.Pattern;
import org.bukkit.block.banner.PatternType;
import org.bukkit.command.*;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BannerMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
/** Native execution of centrally accepted raid receipts. Bank, deed, quest and war authority stay in JARVIS. */
final class ImperialRaid implements Listener, CommandExecutor, TabCompleter {
private final JavaPlugin plugin;
private final java.util.function.Consumer<ItemStack> stamp;
private final NamespacedKey raidKey,ordererKey,captainKey;
private final ImperialRaidPlan.Settings settings;
private final ImperialRaidJournal journal;
private java.util.function.BiConsumer<Player,String> orderRequest;
private java.util.function.BiConsumer<Player,Boolean> pendingRequest;
private final File store;
private final Map<String,Raid> raids=new HashMap<>(); // keyed by raid id
private final Object factions;
private int task=-1;
private final RaidWorldGuard protection;
/** Everything about one raid in flight. */
private static final class Raid{
final String id,ordererId,targetId,ordererName,targetName;
final UUID world;final double x,y,z;final long startsAt;final int link;long endsAt;boolean started;boolean ending;long retreatAt;
final List<UUID> units=new ArrayList<>();ImperialRaidResolution.Outcome pendingOutcome;long pendingAt;
Raid(UUID orderId,String ordererId,String ordererName,String targetId,String targetName,Location home,long startsAt,long endsAt,int link){
this.id=orderId.toString();
this.ordererId=ordererId;this.ordererName=ordererName;this.targetId=targetId;this.targetName=targetName;
world=home.getWorld().getUID();x=home.getX();y=home.getY();z=home.getZ();this.startsAt=startsAt;this.endsAt=endsAt;this.link=link;
}
Location home(){World w=Bukkit.getWorld(world);return w==null?null:new Location(w,x,y,z);}
}
ImperialRaid(JavaPlugin plugin,java.util.function.Consumer<ItemStack> stamp)throws ReflectiveOperationException,java.io.IOException{
this.plugin=plugin;this.stamp=Objects.requireNonNull(stamp);
var mf=Bukkit.getPluginManager().getPlugin("MedievalFactions");
if(mf==null||!mf.isEnabled())throw new IllegalStateException("MedievalFactions unavailable");
factions=call(call(mf,"getServices"),"getFactionService");
protection=new RaidWorldGuard();
raidKey=new NamespacedKey(plugin,"imperial_raid");ordererKey=new NamespacedKey(plugin,"imperial_raid_orderer");captainKey=new NamespacedKey(plugin,"imperial_raid_captain");
settings=ImperialRaidPlan.Settings.defaults();
store=new File(plugin.getDataFolder(),"imperial-raids.json");journal=new ImperialRaidJournal(store.toPath());
recover();
Bukkit.getPluginManager().registerEvents(this,plugin);
var command=plugin.getCommand("clanraid");if(command!=null){command.setExecutor(this);command.setTabCompleter(this);}
task=Bukkit.getScheduler().runTaskTimer(plugin,this::tick,20L,20L).getTaskId();
}
void close(){if(task>=0)Bukkit.getScheduler().cancelTask(task);for(var raid:new ArrayList<>(raids.values())){terminal(raid,ImperialRaidResolution.Outcome.INTERRUPTED,System.currentTimeMillis());despawn(raid);}raids.clear();}
void orderRequests(java.util.function.BiConsumer<Player,String> handler){orderRequest=Objects.requireNonNull(handler);}
void pendingRequests(java.util.function.BiConsumer<Player,Boolean> handler){pendingRequest=Objects.requireNonNull(handler);}
ImperialRaidJournal journal(){return journal;}
private void recover()throws java.io.IOException{
for(var entry:journal.entries()){
for(UUID unit:entry.units()){Entity entity=Bukkit.getEntity(unit);if(entity instanceof Raider&&entry.id().toString().equals(entity.getPersistentDataContainer().get(raidKey,PersistentDataType.STRING)))entity.remove();}
if(entry.phase()==ImperialRaidJournal.Phase.ACCEPTED||entry.phase()==ImperialRaidJournal.Phase.STARTED)journal.terminal(entry.id(),ImperialRaidResolution.Outcome.INTERRUPTED,System.currentTimeMillis(),settings.durationMs());
}
}
private boolean terminal(Raid raid,ImperialRaidResolution.Outcome outcome,long now){
if(raid.pendingOutcome==null){raid.pendingOutcome=outcome;raid.pendingAt=now;}
try{journal.terminal(UUID.fromString(raid.id),raid.pendingOutcome,raid.pendingAt,settings.durationMs());raid.pendingOutcome=null;return true;}
catch(java.io.IOException|RuntimeException failure){plugin.getLogger().warning("Raid terminal journal unavailable: "+failure.getClass().getSimpleName());return false;}
}
// ---- clan lookups (native MedievalFactions roster, mirrored by JARVIS) ----
private Object factionOf(UUID player)throws ReflectiveOperationException{return call(factions,"getFactionByPlayerId",player.toString());}
private String idOf(Object faction)throws ReflectiveOperationException{return String.valueOf(call(faction,"getId"));}
private String nameOf(Object faction)throws ReflectiveOperationException{return String.valueOf(call(faction,"getName"));}
private Object factionByName(String name)throws ReflectiveOperationException{
for(Object f:(List<?>)call(factions,"getFactions"))if(nameOf(f).equalsIgnoreCase(name))return f;
return null;
}
private List<String> factionNames(){
try{var out=new ArrayList<String>();for(Object f:(List<?>)call(factions,"getFactions"))out.add(nameOf(f));return out;}catch(ReflectiveOperationException|RuntimeException unavailable){return List.of();}
}
/** Home Block position, or null when the clan has none or its world is not loaded. */
private Location homeOf(Object faction)throws ReflectiveOperationException{
Object position=call(faction,"getHome");if(position==null)return null;
Object world=position.getClass().getMethod("getWorldId").invoke(position);
World w=Bukkit.getWorld(UUID.fromString(String.valueOf(world)));if(w==null)return null;
double x=((Number)position.getClass().getMethod("getX").invoke(position)).doubleValue(),y=((Number)position.getClass().getMethod("getY").invoke(position)).doubleValue(),z=((Number)position.getClass().getMethod("getZ").invoke(position)).doubleValue();
return new Location(w,x,y,z);
}
private boolean inClan(Player player,String clanId){
try{Object f=factionOf(player.getUniqueId());return f!=null&&clanId.equals(idOf(f));}catch(ReflectiveOperationException|RuntimeException unknown){return false;}
}
private boolean allowedVictim(Player player,String orderer){
if(orderer==null||orderer.isBlank()||!player.isOnline()||player.getGameMode()==GameMode.CREATIVE||player.getGameMode()==GameMode.SPECTATOR)return false;
try{Object faction=factionOf(player.getUniqueId());return faction==null||!orderer.equals(idOf(faction));}catch(ReflectiveOperationException|RuntimeException unavailable){return false;}
}
private List<Player> onlineOf(String clanId){var out=new ArrayList<Player>();for(var p:Bukkit.getOnlinePlayers())if(inClan(p,clanId))out.add(p);return out;}
// ---- ordering ----
/** An authenticated paid bridge receipt is the only production entry. No native bank mutation. */
record Order(UUID id,String ordererId,String targetId,String ordererName,String targetName,UUID world,double x,double y,double z,long startsAt,int retaliationLevel){}
boolean preflight(Order order){
if(!Bukkit.isPrimaryThread())throw new IllegalStateException("Native preflight requires the server thread");
if(order.ordererId().equals(order.targetId())||order.retaliationLevel()<0||order.retaliationLevel()>3)return false;
try{Object target=call(factions,"getFactionByFactionId",order.targetId());if(target==null)return false;Location home=homeOf(target);
return home!=null&&home.getWorld().getUID().equals(order.world())&&home.getBlockX()==(int)Math.floor(order.x())&&home.getBlockY()==(int)Math.floor(order.y())&&home.getBlockZ()==(int)Math.floor(order.z())&&home.getWorld().isChunkLoaded(home.getBlockX()>>4,home.getBlockZ()>>4)&&spawnPoints(home,order.targetId()).size()>=ImperialRaidPlan.raiderCount(settings,onlineOf(order.targetId()).size());
}catch(ReflectiveOperationException|RuntimeException unavailable){return false;}
}
void accepted(Order order,com.google.gson.JsonObject authoritativePaidReceipt)throws java.io.IOException{
var previous=journal.get(order.id());
if(previous!=null){journal.accept(order.id(),authoritativePaidReceipt);return;}
journal.accept(order.id(),authoritativePaidReceipt);
if(!preflight(order)){journal.terminal(order.id(),ImperialRaidResolution.Outcome.SPAWN_FAILED,System.currentTimeMillis(),settings.durationMs());return;}
var home=new Location(Bukkit.getWorld(order.world()),order.x(),order.y(),order.z());
long startsAt=Math.max(order.startsAt(),journal.get(order.id()).warningAt()+settings.noticeMs());
var raid=new Raid(order.id(),order.ordererId(),order.ordererName(),order.targetId(),order.targetName(),home,startsAt,startsAt+settings.durationMs(),order.retaliationLevel());
raids.put(raid.id,raid);
for(var player:onlineOf(raid.targetId))player.sendMessage(Component.text("IMPERIAL RAID - Sardaukar arrive in "+ImperialRaidPlan.format(Math.max(0,raid.startsAt-System.currentTimeMillis()))+".",NamedTextColor.GOLD));
}
// ---- timeline ----
private void tick(){
long now=System.currentTimeMillis();
for(var raid:new ArrayList<>(raids.values()))try{
if(raid.pendingOutcome!=null){if(terminal(raid,raid.pendingOutcome,raid.pendingAt)){despawn(raid);raids.remove(raid.id);}continue;}
long left=raid.startsAt-now;
if(!raid.started){
for(long milestone:ImperialRaidPlan.COUNTDOWN)if(ImperialRaidPlan.crossed(left+1000,left,milestone))for(var p:onlineOf(raid.targetId))p.sendActionBar(Component.text("Sardaukar raid in "+ImperialRaidPlan.format(left),NamedTextColor.GOLD));
if(left<=0)start(raid);
}else if(raid.ending){
if(now>=raid.retreatAt)finish(raid,"The Sardaukar withdraw.");
}else if(now>=raid.endsAt){if(terminal(raid,ImperialRaidResolution.Outcome.SUCCESS,now))finish(raid,"The Sardaukar withdraw.");}
else if(allDown(raid))finish(raid,"The Sardaukar party has fallen.");
}catch(Exception|LinkageError failure){plugin.getLogger().warning("Raid execution interrupted: "+failure.getClass().getSimpleName());terminal(raid,raid.started?ImperialRaidResolution.Outcome.INTERRUPTED:ImperialRaidResolution.Outcome.SPAWN_FAILED,now);finish(raid,"The raid was interrupted safely.");}
}
private boolean allDown(Raid raid){for(var id:raid.units){var e=Bukkit.getEntity(id);if(e!=null&&e.isValid()&&!e.isDead())return false;}return true;}
private void start(Raid raid){
Location home=raid.home();if(home==null||!home.getWorld().isChunkLoaded(home.getBlockX()>>4,home.getBlockZ()>>4)){finish(raid,"The raid was called off.");return;}
long started=System.currentTimeMillis();
int defenders=onlineOf(raid.targetId).size();
var party=ImperialRaidPlan.party(ImperialRaidPlan.raiderCount(settings,defenders));
var positions=spawnPoints(home,raid.targetId);
if(positions.size()<party.size()){terminal(raid,ImperialRaidResolution.Outcome.SPAWN_FAILED,System.currentTimeMillis());finish(raid,"The raid could not arrive safely.");return;}
for(int i=0;i<party.size()&&i<positions.size();i++){
var entity=spawn(raid,positions.get(i),party.get(i));
if(entity!=null&&entity.isValid()){raid.units.add(entity.getUniqueId());try{journal.unit(UUID.fromString(raid.id),entity.getUniqueId());}catch(java.io.IOException failure){entity.remove();finish(raid,"The raid was called off safely.");return;}}
}
boolean commander=raid.units.stream().map(Bukkit::getEntity).filter(e->e!=null&&e.isValid()&&!e.isDead()).anyMatch(e->e.getPersistentDataContainer().has(captainKey,PersistentDataType.BYTE));
if(!commander||raid.units.stream().map(Bukkit::getEntity).filter(e->e!=null&&e.isValid()&&!e.isDead()).count()!=party.size()){terminal(raid,ImperialRaidResolution.Outcome.SPAWN_FAILED,System.currentTimeMillis());finish(raid,"The raid was called off: no commander could arrive safely.");return;}
started=System.currentTimeMillis();
try{journal.start(UUID.fromString(raid.id),started);}catch(java.io.IOException failure){finish(raid,"The raid was called off safely.");return;}
raid.started=true;raid.endsAt=started+settings.durationMs();
home.getWorld().strikeLightningEffect(home);
home.getWorld().playSound(home,Sound.EVENT_RAID_HORN,64f,0.8f);
var title=Title.title(Component.text("IMPERIAL RAID",NamedTextColor.GOLD),Component.text("The Sardaukar have come for "+raid.targetName,NamedTextColor.GRAY));
for(var p:onlineOf(raid.targetId))p.showTitle(title);
for(var p:onlineOf(raid.ordererId))p.sendMessage(Component.text("The Sardaukar have arrived at "+raid.targetName+". Move now.",NamedTextColor.GOLD));
Bukkit.getPluginManager().callEvent(new ImperialRaidStartEvent(raid.ordererId,raid.targetId,home,raid.link,raid.link>=3));
}
private List<Location> spawnPoints(Location home,String target){
List<Location> out=new ArrayList<>();World world=home.getWorld();
for(int i=0;i<32;i++){
double angle=i*Math.PI/16;int x=home.getBlockX()+(int)Math.round(Math.cos(angle)*16),z=home.getBlockZ()+(int)Math.round(Math.sin(angle)*16);
if(!world.isChunkLoaded(x>>4,z>>4))continue;int y=world.getHighestBlockYAt(x,z)+1;
if(y<world.getMinHeight()+1||y+1>=world.getMaxHeight())continue;var ground=world.getBlockAt(x,y-1,z).getType();
if(!ground.isSolid()||Set.of(Material.MAGMA_BLOCK,Material.CACTUS,Material.CAMPFIRE,Material.SOUL_CAMPFIRE,Material.POWDER_SNOW).contains(ground)||!world.getBlockAt(x,y,z).isPassable()||!world.getBlockAt(x,y+1,z).isPassable()||world.getBlockAt(x,y,z).isLiquid())continue;
if(protection.spawn(world.getBlockAt(x,y,z),target))out.add(new Location(world,x+.5,y,z+.5));
}return out;
}
com.google.gson.JsonObject preflightEvidence(ImperialRaidPermit permit){
if(!preflight(new Order(permit.id(),permit.orderingClan().toString(),permit.targetClan().toString(),permit.orderingName(),permit.targetName(),permit.world(),permit.x(),permit.y(),permit.z(),0,permit.retaliation())))throw new IllegalStateException("Travel to the target's registered world and load its safe home area first");
var result=new com.google.gson.JsonObject();result.addProperty("worldUuid",permit.world().toString());var p=new com.google.gson.JsonObject();p.addProperty("x",permit.x());p.addProperty("y",permit.y());p.addProperty("z",permit.z());result.add("position",p);result.addProperty("claimRevision",permit.claimRevision());result.addProperty("defendersOnline",onlineOf(permit.targetClan().toString()).size());result.addProperty("spawnable",true);result.addProperty("protected",false);result.addProperty("observedAt",System.currentTimeMillis());return result;
}
UUID clanOf(Player player)throws ReflectiveOperationException{Object clan=factionOf(player.getUniqueId());return clan==null?null:UUID.fromString(idOf(clan));}
UUID clanNamed(String name)throws ReflectiveOperationException{Object clan=factionByName(name);return clan==null?null:UUID.fromString(idOf(clan));}
private Raider spawn(Raid raid,Location at,ImperialRaidPlan.Slot slot){
Class<? extends Raider> type=slot.ranged()?Pillager.class:Vindicator.class;
return at.getWorld().spawn(at,type,r->{
r.setCanJoinRaid(false);r.setRemoveWhenFarAway(false);r.setPersistent(false);
var data=r.getPersistentDataContainer();data.set(raidKey,PersistentDataType.STRING,raid.id);data.set(ordererKey,PersistentDataType.STRING,raid.ordererId);
var gear=r.getEquipment();
if(slot.captain()){
data.set(captainKey,PersistentDataType.BYTE,(byte)1);
r.customName(Component.text("Sardaukar Commander",NamedTextColor.GOLD));r.setCustomNameVisible(true);r.setPatrolLeader(false);
var hp=r.getAttribute(Attribute.MAX_HEALTH);if(hp!=null){hp.setBaseValue(60);r.setHealth(60);}
gear.setHelmet(banner());gear.setHelmetDropChance(0f);
}else{
r.customName(Component.text("Sardaukar",NamedTextColor.GRAY));r.setCustomNameVisible(false);
}
if(slot.ranged())gear.setItemInMainHand(new ItemStack(Material.CROSSBOW));else gear.setItemInMainHand(new ItemStack(Material.IRON_AXE));
gear.setItemInMainHandDropChance(0f);
var follow=r.getAttribute(Attribute.FOLLOW_RANGE);if(follow!=null)follow.setBaseValue(32);
});
}
private ItemStack banner(){
var item=new ItemStack(Material.BLACK_BANNER);var meta=(BannerMeta)item.getItemMeta();
meta.addPattern(new Pattern(DyeColor.YELLOW,PatternType.BORDER));meta.addPattern(new Pattern(DyeColor.YELLOW,PatternType.CIRCLE));
meta.displayName(Component.text("Imperial Banner",NamedTextColor.GOLD));item.setItemMeta(meta);return item;
}
private void finish(Raid raid,String message){
boolean recorded=terminal(raid,ImperialRaidResolution.Outcome.CANCELLED,System.currentTimeMillis());
despawn(raid);if(recorded)raids.remove(raid.id);else{raid.ending=true;raid.retreatAt=Long.MAX_VALUE;}
for(var p:onlineOf(raid.targetId))p.sendMessage(Component.text(message,NamedTextColor.GRAY));
for(var p:onlineOf(raid.ordererId))p.sendMessage(Component.text(message,NamedTextColor.GRAY));
}
private void despawn(Raid raid){World world=Bukkit.getWorld(raid.world);if(world!=null)for(Entity e:world.getEntities())if(e instanceof Raider&&raid.id.equals(e.getPersistentDataContainer().get(raidKey,PersistentDataType.STRING)))e.remove();raid.units.clear();}
private Raid raidOf(Entity e){
String id=e.getPersistentDataContainer().get(raidKey,PersistentDataType.STRING);return id==null?null:raids.get(id);
}
private boolean isRaider(Entity e){return e.getPersistentDataContainer().has(raidKey,PersistentDataType.STRING);}
// ---- rules ----
/** Never target the ordering clan, and never anything but players. */
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)
public void onTarget(EntityTargetLivingEntityEvent event){
if(!isRaider(event.getEntity())||event.getTarget()==null)return;
String orderer=event.getEntity().getPersistentDataContainer().get(ordererKey,PersistentDataType.STRING);
if(!(event.getTarget() instanceof Player player)||!allowedVictim(player,orderer))event.setCancelled(true);
}
/** Stray bolts and blows must not hurt the ordering clan either. */
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)
public void onDamage(EntityDamageByEntityEvent event){
Entity source=event.getDamager();
if(source instanceof Projectile projectile&&projectile.getShooter() instanceof Entity shooter)source=shooter;
if(!isRaider(source))return;
if(!(event.getEntity() instanceof Player victim)){event.setCancelled(true);return;}
String orderer=source.getPersistentDataContainer().get(ordererKey,PersistentDataType.STRING);
if(!allowedVictim(victim,orderer))event.setCancelled(true);
}
/** The party is a diversion, not a demolition crew. */
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)
public void onBlockChange(EntityChangeBlockEvent event){if(isRaider(event.getEntity()))event.setCancelled(true);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)
public void onExplode(EntityExplodeEvent event){if(isRaider(event.getEntity()))event.blockList().clear();}
@EventHandler
public void onDeath(EntityDeathEvent event){
var e=event.getEntity();if(!isRaider(e))return;
event.getDrops().clear();event.setDroppedExp(0);
Raid raid=raidOf(e);if(raid==null||!raid.started)return;
boolean captain=e.getPersistentDataContainer().has(captainKey,PersistentDataType.BYTE);long deathAt=System.currentTimeMillis();
try{boolean claimed=captain?journal.commanderDeath(UUID.fromString(raid.id),e.getUniqueId(),deathAt,settings.durationMs()):journal.claimDeath(UUID.fromString(raid.id),e.getUniqueId());if(!claimed)return;}
catch(java.io.IOException failure){
if(captain){raid.pendingOutcome=deathAt-journal.get(UUID.fromString(raid.id)).startedAt()>=settings.durationMs()?ImperialRaidResolution.Outcome.SUCCESS:ImperialRaidResolution.Outcome.FAILURE;raid.pendingAt=deathAt;despawn(raid);}
plugin.getLogger().warning("Raid death journal unavailable; no loot issued");return;
}
if(captain&&!raid.ending){
raid.ending=true;raid.retreatAt=deathAt+20_000L;
var killer=e.getKiller();var message=Component.text("The Sardaukar Commander has fallen"+(killer!=null?" to "+killer.getName():"")+". The party retreats.",NamedTextColor.GOLD);
for(var p:onlineOf(raid.targetId))p.sendMessage(message);for(var p:onlineOf(raid.ordererId))p.sendMessage(message);
}
try{for(int amount:ImperialRaidResolution.deathLoot(captain))event.getDrops().add(ImperialRaidSpice.create(amount,stamp));}
catch(RuntimeException|LinkageError failure){plugin.getLogger().warning("Raid loot could not be created: "+failure.getClass().getSimpleName());}
}
// ---- command ----
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){
if(args.length==1&&Set.of("pending","cancel-order").contains(args[0].toLowerCase(Locale.ROOT))){
if(!(sender instanceof Player player)){sender.sendMessage("Players only.");return true;}
if(pendingRequest==null)sender.sendMessage("Raid request recovery is unavailable; the original reference is retained.");else pendingRequest.accept(player,args[0].equalsIgnoreCase("cancel-order"));return true;
}
if(args.length>=1&&args[0].equalsIgnoreCase("cancel")){
if(!sender.hasPermission("dunerealms.raid.admin")){sender.sendMessage("No permission.");return true;}
int count=raids.size();for(var raid:new ArrayList<>(raids.values()))finish(raid,"The raid was called off by staff.");
sender.sendMessage("Cancelled "+count+" raid(s).");return true;
}
if(args.length>=1&&args[0].equalsIgnoreCase("status")){
if(raids.isEmpty())sender.sendMessage("No active raids.");
for(var raid:raids.values())sender.sendMessage(raid.ordererName+" -> "+raid.targetName+(raid.started?" (in progress)":" (starts in "+ImperialRaidPlan.format(raid.startsAt-System.currentTimeMillis())+")"));
return true;
}
if(args.length>=2&&args[0].equalsIgnoreCase("order")){
if(!(sender instanceof Player player)){sender.sendMessage("Players only.");return true;}
if(!player.hasPermission("dunerealms.raid.order")){sender.sendMessage("No permission.");return true;}
if(orderRequest==null){sender.sendMessage("The authorised clan-bank raid service is unavailable. No money was taken.");return true;}
orderRequest.accept(player,String.join(" ",Arrays.copyOfRange(args,1,args.length)));return true;
}
sender.sendMessage("/clanraid order <clan> [--account <ID>] | pending | cancel-order | status | cancel");return true;
}
@Override public List<String> onTabComplete(CommandSender sender,Command command,String alias,String[] args){
if(args.length==1)return List.of("order","pending","cancel-order","status","cancel");
if(args.length>=2&&args[0].equalsIgnoreCase("order")){String prefix=String.join(" ",Arrays.copyOfRange(args,1,args.length)).toLowerCase();var out=new ArrayList<String>();for(var n:factionNames())if(n.toLowerCase().startsWith(prefix))out.add(n);return out;}
return List.of();
}
}

View file

@ -0,0 +1,31 @@
package com.dunerealms.jarvis;
import com.google.gson.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
/** Pure native outbox projection; timestamps and identities always come from durable receipts. */
final class ImperialRaidDelivery {
record Event(UUID id,String expectedState,boolean terminal,JsonObject body){
Event{body=body.deepCopy();}@Override public JsonObject body(){return body.deepCopy();}
}
static UUID id(UUID order,String kind){return UUID.nameUUIDFromBytes(("imperial-raid:"+order+":"+kind).getBytes(StandardCharsets.UTF_8));}
private static Event ack(ImperialRaidJournal.Entry entry,String phase,long time){
UUID event=id(entry.id(),phase);JsonObject q=new JsonObject();q.addProperty("action","ack");q.addProperty("orderId",entry.id().toString());q.addProperty("eventId",event.toString());q.addProperty("phase",phase);q.addProperty("occurredAt",time);return new Event(event,phase,false,q);
}
static List<Event> events(ImperialRaidJournal.Entry entry){
if(entry.phase()==ImperialRaidJournal.Phase.ACKNOWLEDGED)return List.of();
List<Event> events=new ArrayList<>();
if(entry.phase()!=ImperialRaidJournal.Phase.TERMINAL||entry.startedAt()>0)events.add(ack(entry,"warning",entry.warningAt()));
if(entry.startedAt()>0)events.add(ack(entry,"started",entry.startedAt()));
if(entry.phase()==ImperialRaidJournal.Phase.TERMINAL){
JsonObject q=new JsonObject();q.addProperty("action","outcome");q.addProperty("orderId",entry.id().toString());q.addProperty("eventId",entry.eventId().toString());
q.addProperty("outcome",switch(entry.outcome()){case SUCCESS->"survived";case FAILURE->"commander_defeated";case CANCELLED->"cancelled";case INTERRUPTED->"interrupted";case SPAWN_FAILED->"spawn_failed";});
q.addProperty("startedAt",entry.startedAt());q.addProperty("occurredAt",entry.occurredAt());q.addProperty("activeMillis",entry.startedAt()==0?0:Math.max(0,Math.min(900_000,entry.occurredAt()-entry.startedAt())));
events.add(new Event(entry.eventId(),switch(entry.outcome()){case SUCCESS->"completed";case FAILURE->"failed";default->"neutral";},true,q));
}return List.copyOf(events);
}
@FunctionalInterface interface Attempt<T>{void run(T entry)throws Exception;}
static <T> List<Exception> independently(Collection<T> entries,Attempt<T> delivery){
List<Exception> failures=new ArrayList<>();for(T entry:entries)try{delivery.run(entry);}catch(Exception failure){failures.add(failure);}return List.copyOf(failures);
}
}

View file

@ -0,0 +1,120 @@
package com.dunerealms.jarvis;
import com.google.gson.*;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.*;
/** Write-ahead native execution receipts. This journal never authorises or charges an order. */
final class ImperialRaidJournal {
enum Phase { ACCEPTED, STARTED, TERMINAL, ACKNOWLEDGED }
record Entry(UUID id,JsonObject permit,Phase phase,long warningAt,long startedAt,long occurredAt,
ImperialRaidResolution.Outcome outcome,Set<UUID> units,Set<UUID> paidDeaths){
Entry { permit=permit.deepCopy();units=Set.copyOf(units);paidDeaths=Set.copyOf(paidDeaths); }
@Override public JsonObject permit(){return permit.deepCopy();}
UUID eventId(){return UUID.nameUUIDFromBytes(("imperial-raid:"+id+":"+(phase==Phase.ACKNOWLEDGED?Phase.TERMINAL:phase)).getBytes(StandardCharsets.UTF_8));}
}
private final Path path;
private final java.util.function.LongSupplier clock;
private final LinkedHashMap<UUID,Entry> entries=new LinkedHashMap<>();
ImperialRaidJournal(Path path)throws IOException{
this(path,System::currentTimeMillis);
}
ImperialRaidJournal(Path path,java.util.function.LongSupplier clock)throws IOException{
this.path=path;this.clock=clock;
if(Files.exists(path)){
if(Files.isSymbolicLink(path)||Files.size(path)>8_000_000)throw new IOException("Invalid raid journal");
try{
JsonObject root=JsonParser.parseString(Files.readString(path)).getAsJsonObject();
if(root.get("schema").getAsInt()!=1)throw new IllegalArgumentException();
for(JsonElement element:root.getAsJsonArray("entries")){
JsonObject row=element.getAsJsonObject();UUID id=UUID.fromString(row.get("id").getAsString());
Phase phase=Phase.valueOf(row.get("phase").getAsString());
long started=row.get("startedAt").getAsLong(),occurred=row.get("occurredAt").getAsLong();
var outcome=row.has("outcome")?ImperialRaidResolution.Outcome.valueOf(row.get("outcome").getAsString()):null;
if(started<0||occurred<0||(phase==Phase.TERMINAL||phase==Phase.ACKNOWLEDGED)!=(outcome!=null))throw new IllegalArgumentException();
Entry entry=new Entry(id,row.getAsJsonObject("permit"),phase,row.has("warningAt")?row.get("warningAt").getAsLong():occurred,started,occurred,outcome,ids(row,"units"),ids(row,"paidDeaths"));
if(entries.putIfAbsent(id,entry)!=null)throw new IllegalArgumentException();
}
}catch(RuntimeException invalid){throw new IOException("Invalid raid journal",invalid);}
}
}
private static Set<UUID> ids(JsonObject row,String key){
Set<UUID> out=new HashSet<>();for(JsonElement e:row.getAsJsonArray(key))if(!out.add(UUID.fromString(e.getAsString())))throw new IllegalArgumentException();return out;
}
synchronized List<Entry> entries(){return List.copyOf(entries.values());}
synchronized Entry get(UUID id){return entries.get(id);}
synchronized Entry accept(UUID id,JsonObject verifiedPermit)throws IOException{
Objects.requireNonNull(id);Objects.requireNonNull(verifiedPermit);
Entry previous=entries.get(id);
if(previous!=null){if(!previous.permit().equals(verifiedPermit))throw new IllegalStateException("Raid receipt changed");return previous;}
if(entries.size()>=10_000)throw new IOException("Raid journal requires archival");
return persist(new Entry(id,verifiedPermit,Phase.ACCEPTED,clock.getAsLong(),0,0,null,Set.of(),Set.of()));
}
/** Persist each entity identity before it can be rewarded. */
synchronized Entry unit(UUID id,UUID unit)throws IOException{
Entry e=required(id);if(e.phase()!=Phase.ACCEPTED)throw new IllegalStateException("Raid party is already fixed");
Set<UUID> units=new HashSet<>(e.units());units.add(unit);
if(units.size()>14)throw new IllegalStateException("Raid party exceeds its accepted policy");
return persist(new Entry(e.id(),e.permit(),e.phase(),e.warningAt(),e.startedAt(),e.occurredAt(),e.outcome(),units,e.paidDeaths()));
}
synchronized Entry start(UUID id,long now)throws IOException{
Entry e=required(id);if(e.phase()==Phase.STARTED)return e;
if(e.phase()!=Phase.ACCEPTED||e.units().isEmpty()||now<=0)throw new IllegalStateException("Party must exist before starting");
return persist(new Entry(id,e.permit(),Phase.STARTED,e.warningAt(),now,now,null,e.units(),e.paidDeaths()));
}
synchronized Entry terminal(UUID id,ImperialRaidResolution.Outcome outcome,long now,long duration)throws IOException{
Entry e=required(id);Objects.requireNonNull(outcome);
if(e.outcome()!=null)return e;
if(now<0||duration<=0)throw new IllegalArgumentException("Invalid raid clock");
if(outcome==ImperialRaidResolution.Outcome.SUCCESS&&(e.phase()!=Phase.STARTED||now-e.startedAt()<duration))throw new IllegalStateException("Raid duration incomplete");
if(outcome==ImperialRaidResolution.Outcome.FAILURE&&e.phase()!=Phase.STARTED)throw new IllegalStateException("Raid never started");
return persist(new Entry(id,e.permit(),Phase.TERMINAL,e.warningAt(),e.startedAt(),now,outcome,e.units(),e.paidDeaths()));
}
/** Mark before native drops: a crash can lose a drop, but cannot duplicate one. */
synchronized boolean claimDeath(UUID id,UUID unit)throws IOException{
Entry e=required(id);
if(!(e.phase()==Phase.STARTED||(e.phase()==Phase.TERMINAL||e.phase()==Phase.ACKNOWLEDGED)&&e.outcome()==ImperialRaidResolution.Outcome.FAILURE)||!e.units().contains(unit)||e.paidDeaths().contains(unit))return false;
Set<UUID> paid=new HashSet<>(e.paidDeaths());paid.add(unit);
persist(new Entry(id,e.permit(),e.phase(),e.warningAt(),e.startedAt(),e.occurredAt(),e.outcome(),e.units(),paid));return true;
}
/** Persist commander result and its loot claim in one write before any native drops. */
synchronized boolean commanderDeath(UUID id,UUID unit,long now,long duration)throws IOException{
Entry e=required(id);if(e.phase()!=Phase.STARTED||!e.units().contains(unit)||e.paidDeaths().contains(unit))return false;
if(now<e.startedAt()||duration<=0)throw new IllegalArgumentException("Invalid raid death clock");
Set<UUID> paid=new HashSet<>(e.paidDeaths());paid.add(unit);
var outcome=now-e.startedAt()>=duration?ImperialRaidResolution.Outcome.SUCCESS:ImperialRaidResolution.Outcome.FAILURE;
persist(new Entry(id,e.permit(),Phase.TERMINAL,e.warningAt(),e.startedAt(),now,outcome,e.units(),paid));return true;
}
synchronized Entry acknowledge(UUID id,UUID expectedEvent)throws IOException{
Entry e=required(id);if(e.phase()==Phase.ACKNOWLEDGED){if(!e.eventId().equals(expectedEvent))throw new IllegalStateException("Terminal acknowledgement mismatch");return e;}
if(e.phase()!=Phase.TERMINAL||!e.eventId().equals(expectedEvent))throw new IllegalStateException("Terminal acknowledgement mismatch");
return persist(new Entry(id,e.permit(),Phase.ACKNOWLEDGED,e.warningAt(),e.startedAt(),e.occurredAt(),e.outcome(),e.units(),e.paidDeaths()));
}
private Entry required(UUID id){Entry e=entries.get(id);if(e==null)throw new IllegalStateException("No accepted raid receipt");return e;}
private Entry persist(Entry next)throws IOException{
LinkedHashMap<UUID,Entry> updated=new LinkedHashMap<>(entries);updated.put(next.id(),next);
JsonObject root=new JsonObject();root.addProperty("schema",1);JsonArray rows=new JsonArray();
for(Entry e:updated.values()){
JsonObject row=new JsonObject();row.addProperty("id",e.id().toString());row.add("permit",e.permit());row.addProperty("phase",e.phase().name());
row.addProperty("warningAt",e.warningAt());row.addProperty("startedAt",e.startedAt());row.addProperty("occurredAt",e.occurredAt());if(e.outcome()!=null)row.addProperty("outcome",e.outcome().name());
JsonArray units=new JsonArray();e.units().stream().sorted().forEach(u->units.add(u.toString()));row.add("units",units);
JsonArray paid=new JsonArray();e.paidDeaths().stream().sorted().forEach(u->paid.add(u.toString()));row.add("paidDeaths",paid);rows.add(row);
}root.add("entries",rows);
Files.createDirectories(path.toAbsolutePath().getParent());Path tmp=path.resolveSibling(path.getFileName()+".tmp");
if(Files.isSymbolicLink(path)||Files.isSymbolicLink(tmp))throw new IOException("Unsafe raid journal path");
try{
byte[] bytes=root.toString().getBytes(StandardCharsets.UTF_8);
try(FileChannel channel=FileChannel.open(tmp,StandardOpenOption.CREATE,StandardOpenOption.TRUNCATE_EXISTING,StandardOpenOption.WRITE)){
try{Files.setPosixFilePermissions(tmp,PosixFilePermissions.fromString("rw-------"));}catch(UnsupportedOperationException ignored){}
ByteBuffer buffer=ByteBuffer.wrap(bytes);while(buffer.hasRemaining())channel.write(buffer);channel.force(true);
}
Files.move(tmp,path,StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.ATOMIC_MOVE);
entries.clear();entries.putAll(updated);return next;
}finally{Files.deleteIfExists(tmp);}
}
}

View file

@ -0,0 +1,44 @@
package com.dunerealms.jarvis;
import com.google.gson.*;
import java.util.*;
/** Strict DTO for the authenticated existing JARVIS bridge; never treats a quote as payment. */
record ImperialRaidPermit(UUID id,UUID requestId,String inputHash,UUID nonce,long expiresAt,UUID actor,
UUID orderingClan,UUID targetClan,String orderingName,String targetName,
String sourceAccountId,long feeMinor,String server,UUID chainId,int retaliation,
UUID world,double x,double y,double z,long claimRevision,long noticeMs,long durationMs,
boolean accepted,long acceptedAt,UUID receiptKeyId,String bankOrderId,JsonObject binding){
ImperialRaidPermit{binding=binding.deepCopy();}
@Override public JsonObject binding(){return binding.deepCopy();}
private static String text(JsonObject o,String k){JsonElement e=o.get(k);if(e==null||!e.isJsonPrimitive()||!e.getAsJsonPrimitive().isString())throw new IllegalArgumentException("Invalid raid field: "+k);return e.getAsString();}
private static long number(JsonObject o,String k){JsonElement e=o.get(k);if(e==null||!e.isJsonPrimitive()||!e.getAsJsonPrimitive().isNumber()||!e.getAsString().matches("-?[0-9]{1,16}"))throw new IllegalArgumentException("Invalid raid number: "+k);return e.getAsLong();}
private static UUID id(JsonObject o,String k){String s=text(o,k);UUID id=UUID.fromString(s);if(!id.toString().equals(s.toLowerCase(Locale.ROOT)))throw new IllegalArgumentException("Invalid raid identity");return id;}
static ImperialRaidPermit parse(JsonObject response,String expectedServer,long now){
if(!response.has("ok")||!response.get("ok").getAsBoolean()||number(response,"schema")!=1)throw new IllegalArgumentException("Invalid raid response");
String state=text(response,"state");if(!Set.of("prepared","accepted").contains(state))throw new IllegalArgumentException("Invalid raid state");
boolean accepted=state.equals("accepted");JsonObject o=response.getAsJsonObject("order");if(o==null)throw new IllegalArgumentException("Missing raid order");
String server=text(o,"server"),hash=text(o,"inputHash"),currency=text(o,"currency"),account=text(o,"sourceAccountId"),money=text(o,"feeMinor");
if(!server.equals(expectedServer)||!hash.matches("[a-f0-9]{64}")||!currency.equals("DM")||!account.matches("[1-9][0-9]{0,11}")||!money.matches("[0-9]{1,16}"))throw new IllegalArgumentException("Invalid raid binding");
long level=number(o,"retaliationLevel"),fee=Long.parseLong(money),expires=number(o,"expiresAt");
if(level<0||level>3||fee!=2_500_000+500_000*level||!accepted&&expires<=now)throw new IllegalArgumentException("Raid terms expired or changed");
UUID ordering=id(o,"orderingClanId"),target=id(o,"targetClanId");if(ordering.equals(target))throw new IllegalArgumentException("Cannot raid same clan");
JsonObject home=o.getAsJsonObject("home"),position=home.getAsJsonObject("position"),policy=o.getAsJsonObject("policy");
double x=position.get("x").getAsDouble(),y=position.get("y").getAsDouble(),z=position.get("z").getAsDouble();
if(!Double.isFinite(x)||!Double.isFinite(y)||!Double.isFinite(z)||Math.abs(x)>30_000_000||Math.abs(z)>30_000_000||Math.abs(y)>2048)throw new IllegalArgumentException("Invalid raid home");
long revision=number(home,"claimRevision"),notice=number(policy,"noticeMs"),duration=number(policy,"durationMs");
if(revision<1||notice!=600_000||duration!=900_000||number(policy,"baseRaiders")!=4||number(policy,"perDefender")!=1||number(policy,"maxRaiders")!=14||number(policy,"minDefendersOnline")!=0)throw new IllegalArgumentException("Unsupported raid policy");
String orderingName=text(o,"orderingClanName"),targetName=text(o,"targetClanName");
if(orderingName.isBlank()||targetName.isBlank()||orderingName.length()>100||targetName.length()>100)throw new IllegalArgumentException("Invalid clan display name");
long acceptedAt=accepted?number(o,"acceptedAt"):0;UUID receipt=accepted?id(o,"receiptKeyId"):null;
String bankOrder=accepted?text(o,"bankOrderId"):null;
if(accepted&&(acceptedAt<=0||acceptedAt>now+30_000||bankOrder.isBlank()||bankOrder.length()>100))throw new IllegalArgumentException("Invalid accepted receipt");
UUID orderId=id(o,"id"),requestId=id(o,"requestId");JsonObject intent=new JsonObject();intent.addProperty("server",server);intent.addProperty("uuid",id(o,"actorUuid").toString());intent.addProperty("requestId",requestId.toString());intent.addProperty("orderingClanId",ordering.toString());intent.addProperty("targetClanId",target.toString());intent.addProperty("sourceAccountId",account);
if(!orderId.equals(requestId)||!ImperialRaidRequests.intentHash(intent).equals(hash))throw new IllegalArgumentException("Raid intent hash changed");
return new ImperialRaidPermit(orderId,requestId,hash,id(o,"preflightNonce"),expires,id(o,"actorUuid"),ordering,target,orderingName,targetName,
account,fee,server,id(o,"chainId"),(int)level,id(home,"worldUuid"),x,y,z,revision,notice,duration,accepted,acceptedAt,receipt,bankOrder,o);
}
ImperialRaid.Order execution(){
if(!accepted||receiptKeyId==null||bankOrderId==null)throw new IllegalStateException("Prepared order is unpaid");
return new ImperialRaid.Order(id,orderingClan.toString(),targetClan.toString(),orderingName,targetName,world,x,y,z,acceptedAt+noticeMs,retaliation);
}
}

View file

@ -0,0 +1,90 @@
package com.dunerealms.jarvis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Pure rules for an Imperial raid: no Bukkit types, so it is unit-testable without a server. */
final class ImperialRaidPlan {
/** All durations are milliseconds. */
record Settings(long noticeMs,long durationMs,long ordererCooldownMs,long targetCooldownMs,int minDefendersOnline,int baseRaiders,int perDefender,int maxRaiders,long baseFee,long feeStep){
Settings(long noticeMs,long durationMs,long ordererCooldownMs,long targetCooldownMs,int minDefendersOnline,int baseRaiders,int perDefender,int maxRaiders){this(noticeMs,durationMs,ordererCooldownMs,targetCooldownMs,minDefendersOnline,baseRaiders,perDefender,maxRaiders,25_000L,5_000L);}
static Settings defaults(){return new Settings(10*60_000L,15*60_000L,24*3_600_000L,6*3_600_000L,0,4,1,14);}
}
enum Verdict{OK,SAME_CLAN,NO_TARGET_HOME,RAID_ALREADY_ACTIVE,ORDERER_COOLDOWN,TARGET_PROTECTED,TOO_FEW_DEFENDERS}
/** One member of the party; the captain is always first. */
record Slot(boolean captain,boolean ranged){}
/** Remembers who ordered and who was raided; the caller persists {@link #snapshot()}. */
static final class Ledger{
private final Map<String,Long> ordered=new HashMap<>(),raided=new HashMap<>();
private final Map<String,Long> activeUntil=new HashMap<>();
/** Retaliation right: a raided clan may raid its raider back, once, without its own cooldown. */
private final Map<String,String> revengeAgainst=new HashMap<>();private final Map<String,Long> revengeUntil=new HashMap<>();private final Map<String,Integer> revengeLevel=new HashMap<>();
static final long REVENGE_MS=24*3_600_000L;
boolean hasRevenge(String orderer,String target,long now){return target.equals(revengeAgainst.get(orderer))&&revengeUntil.getOrDefault(orderer,0L)>now;}
/** Position in an unbroken tit-for-tat chain: 0 for a fresh raid, +1 for each retaliation. */
int level(String orderer,String target,long now){return hasRevenge(orderer,target,now)?revengeLevel.getOrDefault(orderer,0)+1:0;}
/** Fee in DM (major units) owed to taxes: base plus a step per sequential raid. The caller charges it. */
long fee(Settings s,String orderer,String target,long now){return s.baseFee()+s.feeStep()*level(orderer,target,now);}
Verdict check(Settings s,String orderer,String target,boolean targetHasHome,int defendersOnline,long now){
if(orderer.equals(target))return Verdict.SAME_CLAN;
if(!targetHasHome)return Verdict.NO_TARGET_HOME;
if(activeUntil.getOrDefault(target,0L)>now)return Verdict.RAID_ALREADY_ACTIVE;
if(!hasRevenge(orderer,target,now)&&now-ordered.getOrDefault(orderer,Long.MIN_VALUE/2)<s.ordererCooldownMs())return Verdict.ORDERER_COOLDOWN;
if(!hasRevenge(orderer,target,now)&&now-raided.getOrDefault(target,Long.MIN_VALUE/2)<s.targetCooldownMs())return Verdict.TARGET_PROTECTED;
if(defendersOnline<s.minDefendersOnline())return Verdict.TOO_FEW_DEFENDERS;
return Verdict.OK;
}
/** Records an accepted order. The raid occupies the target from the order until it ends. */
void accept(Settings s,String orderer,String target,long now){accept(s,orderer,target,now,0);}
/** warAfter>0: the retaliation that reaches that level ends the loop (a war takes over), so no further right is granted. */
void accept(Settings s,String orderer,String target,long now,int warAfter){
int next=level(orderer,target,now);boolean retaliation=hasRevenge(orderer,target,now);
if(retaliation){revengeAgainst.remove(orderer);revengeUntil.remove(orderer);revengeLevel.remove(orderer);}
else ordered.put(orderer,now);
// The clan just raided may now answer, so a chain can continue (each link costs more).
if(warAfter>0&&next>=warAfter){revengeAgainst.remove(target);revengeUntil.remove(target);revengeLevel.remove(target);}
else{revengeAgainst.put(target,orderer);revengeUntil.put(target,now+REVENGE_MS);revengeLevel.put(target,next);}
raided.put(target,now);activeUntil.put(target,now+s.noticeMs()+s.durationMs());
}
void finish(String target){activeUntil.remove(target);}
long ordererCooldownLeft(Settings s,String orderer,long now){return Math.max(0,s.ordererCooldownMs()-(now-ordered.getOrDefault(orderer,Long.MIN_VALUE/2)));}
long targetCooldownLeft(Settings s,String target,long now){return Math.max(0,s.targetCooldownMs()-(now-raided.getOrDefault(target,Long.MIN_VALUE/2)));}
/** Full advisory journal state. Central paid-order receipts remain authoritative. */
record State(Map<String,Long> ordered,Map<String,Long> raided,Map<String,Long> activeUntil,
Map<String,String> revengeAgainst,Map<String,Long> revengeUntil,Map<String,Integer> revengeLevel){
State{ordered=Map.copyOf(ordered);raided=Map.copyOf(raided);activeUntil=Map.copyOf(activeUntil);
revengeAgainst=Map.copyOf(revengeAgainst);revengeUntil=Map.copyOf(revengeUntil);revengeLevel=Map.copyOf(revengeLevel);}
}
State durableSnapshot(){return new State(ordered,raided,activeUntil,revengeAgainst,revengeUntil,revengeLevel);}
void restore(State state){
ordered.clear();ordered.putAll(state.ordered());raided.clear();raided.putAll(state.raided());
activeUntil.clear();activeUntil.putAll(state.activeUntil());revengeAgainst.clear();revengeAgainst.putAll(state.revengeAgainst());
revengeUntil.clear();revengeUntil.putAll(state.revengeUntil());revengeLevel.clear();revengeLevel.putAll(state.revengeLevel());
}
Map<String,Map<String,Long>> snapshot(){return Map.of("ordered",new HashMap<>(ordered),"raided",new HashMap<>(raided));}
void restore(Map<String,Long> orderedRows,Map<String,Long> raidedRows){ordered.clear();raided.clear();ordered.putAll(orderedRows);raided.putAll(raidedRows);}
}
/** Party size scales with the defenders online and is always capped. */
static int raiderCount(Settings s,int defendersOnline){
int wanted=s.baseRaiders()+Math.max(0,defendersOnline)*s.perDefender();
return Math.max(2,Math.min(s.maxRaiders(),wanted));
}
/** Captain first, then roughly one crossbow per three raiders, the rest melee. */
static List<Slot> party(int count){
var slots=new ArrayList<Slot>();slots.add(new Slot(true,false));
for(int i=1;i<count;i++)slots.add(new Slot(false,i%3==0));
return slots;
}
/** Milestones at which the target clan is told how long is left (ms before start). */
static final long[] COUNTDOWN={5*60_000L,60_000L,10_000L};
static boolean crossed(long previousLeft,long left,long milestone){return previousLeft>milestone&&left<=milestone;}
static String format(long ms){
long s=Math.max(0,ms/1000),h=s/3600,m=s%3600/60,sec=s%60;
if(h>0)return h+"h "+m+"m";if(m>0)return m+"m "+sec+"s";return sec+"s";
}
}

View file

@ -0,0 +1,63 @@
package com.dunerealms.jarvis;
import com.google.gson.*;
import java.io.IOException;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.util.*;
/** Durable client intent IDs, not payments. An uncertain request is never replaced by another UUID. */
final class ImperialRaidRequests {
private final Path file;private final Map<UUID,JsonObject> pending=new HashMap<>();
ImperialRaidRequests(Path file)throws IOException{
this.file=file;if(Files.exists(file)){
if(Files.isSymbolicLink(file)||Files.size(file)>1_000_000)throw new IOException("Invalid raid requests");
try{JsonObject root=JsonParser.parseString(Files.readString(file)).getAsJsonObject();for(var e:root.entrySet()){UUID actor=UUID.fromString(e.getKey());JsonObject request=e.getValue().getAsJsonObject();UUID.fromString(request.get("requestId").getAsString());if(!actor.toString().equals(request.get("uuid").getAsString()))throw new IllegalArgumentException();pending.put(actor,request.deepCopy());}}
catch(RuntimeException invalid){throw new IOException("Invalid raid requests",invalid);}
}
}
synchronized JsonObject begin(UUID actor,UUID ordering,UUID target,String account,String server)throws IOException{
JsonObject previous=pending.get(actor);
if(previous!=null){if(!previous.get("orderingClanId").getAsString().equals(ordering.toString())||!previous.get("targetClanId").getAsString().equals(target.toString())||!previous.get("sourceAccountId").getAsString().equals(account)||!previous.get("server").getAsString().equals(server))throw new IllegalStateException("Resolve the existing raid reference before starting a different order");return preparePayload(previous);}
JsonObject request=new JsonObject();request.addProperty("action","prepare");request.addProperty("uuid",actor.toString());request.addProperty("requestId",UUID.randomUUID().toString());request.addProperty("orderingClanId",ordering.toString());request.addProperty("targetClanId",target.toString());request.addProperty("sourceAccountId",account);request.addProperty("server",server);
Map<UUID,JsonObject> updated=new HashMap<>(pending);updated.put(actor,request);save(updated);pending.put(actor,request.deepCopy());return request;
}
synchronized void complete(UUID actor,UUID requestId)throws IOException{
JsonObject current=pending.get(actor);if(current==null)return;if(!current.get("requestId").getAsString().equals(requestId.toString()))throw new IllegalStateException("Raid request reference mismatch");
Map<UUID,JsonObject> updated=new HashMap<>(pending);updated.remove(actor);save(updated);pending.remove(actor);
}
synchronized JsonObject current(UUID actor){JsonObject p=pending.get(actor);return p==null?null:p.deepCopy();}
static String intentHash(JsonObject intent){
JsonArray array=new JsonArray();for(String key:List.of("server","uuid","requestId","orderingClanId","targetClanId","sourceAccountId"))array.add(intent.get(key).getAsString());
try{return java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(array.toString().getBytes(StandardCharsets.UTF_8)));}catch(java.security.NoSuchAlgorithmException impossible){throw new AssertionError(impossible);}
}
synchronized JsonObject query(UUID actor,boolean cancel){JsonObject current=pending.get(actor);if(current==null)return null;JsonObject q=preparePayload(current);q.addProperty("action",cancel?"cancel_prepared":"status");return q;}
synchronized boolean definitive(UUID actor,JsonObject response)throws IOException{
JsonObject current=pending.get(actor);if(current==null)return false;
try{
for(String key:List.of("ok","definitive","charged"))if(!response.get(key).isJsonPrimitive()||!response.getAsJsonPrimitive(key).isBoolean())return false;
if(!response.get("ok").getAsBoolean()||response.get("schema").getAsInt()!=1||!response.get("definitive").getAsBoolean()||response.get("charged").getAsBoolean()||!Set.of("cancelled","rejected","expired").contains(response.get("state").getAsString()))return false;
String id=current.get("requestId").getAsString();if(!id.equals(response.get("orderId").getAsString())||!id.equals(response.get("requestId").getAsString())||!intentHash(current).equals(response.get("inputHash").getAsString()))return false;
complete(actor,UUID.fromString(id));return true;
}catch(RuntimeException invalid){return false;}
}
private static JsonObject preparePayload(JsonObject stored){JsonObject q=stored.deepCopy();q.remove("acceptIntent");return q;}
synchronized JsonObject acceptance(UUID actor,UUID requestId,JsonObject body)throws IOException{
JsonObject current=pending.get(actor);if(current==null||!requestId.toString().equals(current.get("requestId").getAsString()))throw new IllegalStateException("No matching pending raid intent");
if(current.has("acceptIntent")){
JsonObject previous=current.getAsJsonObject("acceptIntent");
for(String field:List.of("orderId","eventId","inputHash","preflightNonce"))if(!previous.get(field).equals(body.get(field)))throw new IllegalStateException("Raid acceptance reference changed");
return previous.deepCopy(); // Preserve original preflight timestamp and payload on an uncertain retry.
}
JsonObject updated=current.deepCopy();updated.add("acceptIntent",body.deepCopy());Map<UUID,JsonObject> rows=new HashMap<>(pending);rows.put(actor,updated);save(rows);pending.put(actor,updated);return body.deepCopy();
}
private void save(Map<UUID,JsonObject> rows)throws IOException{
JsonObject root=new JsonObject();rows.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e->root.add(e.getKey().toString(),e.getValue()));
Files.createDirectories(file.toAbsolutePath().getParent());Path temp=file.resolveSibling(file.getFileName()+".tmp");if(Files.isSymbolicLink(file)||Files.isSymbolicLink(temp))throw new IOException("Unsafe raid request path");
try{try(FileChannel channel=FileChannel.open(temp,StandardOpenOption.CREATE,StandardOpenOption.TRUNCATE_EXISTING,StandardOpenOption.WRITE)){
try{Files.setPosixFilePermissions(temp,java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"));}catch(UnsupportedOperationException ignored){}
ByteBuffer bytes=ByteBuffer.wrap(root.toString().getBytes(StandardCharsets.UTF_8));while(bytes.hasRemaining())channel.write(bytes);channel.force(true);
}Files.move(temp,file,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}finally{Files.deleteIfExists(temp);}
}
}

View file

@ -0,0 +1,16 @@
package com.dunerealms.jarvis;
import java.util.*;
/** Deterministic terminal policy. Payment/quest authority remains central; this emits evidence, not rewards. */
final class ImperialRaidResolution {
enum Outcome { SUCCESS(1000), FAILURE(100), CANCELLED(0), INTERRUPTED(0), SPAWN_FAILED(0);final int reputationXp;Outcome(int xp){reputationXp=xp;} }
record Result(UUID orderId,Outcome outcome,long occurredAt){}
private final UUID orderId;private final long durationMs;private Long startedAt;private Result result;
ImperialRaidResolution(UUID orderId,long durationMs){this.orderId=Objects.requireNonNull(orderId);if(durationMs<=0||durationMs>3_600_000)throw new IllegalArgumentException("Invalid raid duration");this.durationMs=durationMs;}
boolean started(long now){if(now<0||startedAt!=null||result!=null)return false;startedAt=now;return true;}
Optional<Result> tick(long now){if(result==null&&startedAt!=null&&now-startedAt>=durationMs)result=new Result(orderId,Outcome.SUCCESS,startedAt+durationMs);return Optional.ofNullable(result);}
Optional<Result> commanderDefeated(long now){if(startedAt==null||now<startedAt)return Optional.empty();tick(now);if(result==null)result=new Result(orderId,Outcome.FAILURE,now);return Optional.of(result);}
Result cancel(long now){if(result==null)result=new Result(orderId,Outcome.CANCELLED,now);return result;}
Result interrupted(long now){if(result==null)result=new Result(orderId,Outcome.INTERRUPTED,now);return result;}
/** Only an actual unit death uses this policy. Retreat/despawn/restart must never call it. */
static List<Integer> deathLoot(boolean commander){int total=commander?1000:25;List<Integer> out=new ArrayList<>();while(total>0){int amount=Math.min(64,total);out.add(amount);total-=amount;}return List.copyOf(out);}
}

View file

@ -0,0 +1,13 @@
package com.dunerealms.jarvis;
import java.util.function.Consumer;
import org.bukkit.*;import org.bukkit.inventory.ItemStack;import org.bukkit.persistence.PersistentDataType;
import net.kyori.adventure.text.Component;import net.kyori.adventure.text.format.NamedTextColor;
/** Same raw-spice identity consumed by the existing Exchange; no player mining proof is fabricated. */
final class ImperialRaidSpice {
static ItemStack create(int amount,Consumer<ItemStack> stamp){
if(amount<1||amount>64)throw new IllegalArgumentException("Spice stack bound");
var item=new ItemStack(Material.ORANGE_DYE,amount);var meta=item.getItemMeta();meta.displayName(Component.text("Melange Spice",NamedTextColor.GOLD));
meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING,"spice");meta.getPersistentDataContainer().set(ItemOrigin.WORLD,PersistentDataType.STRING,"arrakis");item.setItemMeta(meta);stamp.accept(item);
if(!ExchangeInventory.rawSpice(item)||item.getAmount()!=amount)throw new IllegalStateException("Raid spice did not retain commodity identity");return item;
}
}

View file

@ -0,0 +1,22 @@
package com.dunerealms.jarvis;
import org.bukkit.Location;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/** Fired when an Imperial raid party spawns. A war or reputation hook can listen without touching the raid code. */
public final class ImperialRaidStartEvent extends Event {
private static final HandlerList HANDLERS=new HandlerList();
private final String ordererClanId,targetClanId;private final Location home;private final int retaliationLevel;private final boolean warThresholdReached;
ImperialRaidStartEvent(String ordererClanId,String targetClanId,Location home){this(ordererClanId,targetClanId,home,0,false);}
ImperialRaidStartEvent(String ordererClanId,String targetClanId,Location home,int retaliationLevel,boolean warThresholdReached){this.retaliationLevel=retaliationLevel;this.warThresholdReached=warThresholdReached;this.ordererClanId=ordererClanId;this.targetClanId=targetClanId;this.home=home.clone();}
public String ordererClanId(){return ordererClanId;}
public String targetClanId(){return targetClanId;}
/** 0 for a fresh raid, +1 per unbroken retaliation. */
public int retaliationLevel(){return retaliationLevel;}
/** True once the configured number of retaliations in a row is reached (default 3); nothing here starts the war. */
public boolean warThresholdReached(){return warThresholdReached;}
public Location home(){return home.clone();}
@Override public HandlerList getHandlers(){return HANDLERS;}
public static HandlerList getHandlerList(){return HANDLERS;}
}

Some files were not shown because too many files have changed in this diff Show more