From a6d4389470129fb6ead469d6e49fd6349765f92b Mon Sep 17 00:00:00 2001 From: Dev Date: Mon, 23 Nov 2026 20:29:15 +0100 Subject: [PATCH] Normalize integration source text without changing pinned texture bytes --- DuneRealmsGUI/planet-artwork/.gitattributes | 12 +- DuneRealmsGUI/planet-artwork/README.md | 172 +++--- .../main/java/com/dunerealms/gui/DuneGUI.java | 542 +++++++++--------- .../dunerealms/gui/PlanetMaterialPolicy.java | 28 +- .../dunerealms/gui/PlanetTexturePacks.java | 170 +++--- .../src/main/resources/planet-textures.yml | 76 +-- .../gui/PlanetMaterialPolicyTest.java | 50 +- tools/build-planet-texture-packs.mjs | 148 ++--- tools/build-planet-texture-packs.test.mjs | 100 ++-- 9 files changed, 649 insertions(+), 649 deletions(-) diff --git a/DuneRealmsGUI/planet-artwork/.gitattributes b/DuneRealmsGUI/planet-artwork/.gitattributes index 7f938e71..6cb3b6cf 100644 --- a/DuneRealmsGUI/planet-artwork/.gitattributes +++ b/DuneRealmsGUI/planet-artwork/.gitattributes @@ -1,6 +1,6 @@ -# Preserve upstream asset bytes so checkout line endings cannot change pack pins. -pixel-perfection-ce/** -text -diff -whitespace -release-v1/*.zip -text -release-v1/*.json text eol=lf -release-v1/*.yml text eol=lf -profiles.json text eol=lf +# Preserve upstream asset bytes so checkout line endings cannot change pack pins. +pixel-perfection-ce/** -text -diff -whitespace +release-v1/*.zip -text +release-v1/*.json text eol=lf +release-v1/*.yml text eol=lf +profiles.json text eol=lf diff --git a/DuneRealmsGUI/planet-artwork/README.md b/DuneRealmsGUI/planet-artwork/README.md index 195a5de8..b7995340 100644 --- a/DuneRealmsGUI/planet-artwork/README.md +++ b/DuneRealmsGUI/planet-artwork/README.md @@ -1,86 +1,86 @@ -# Planet material packs · Java Edition - -Six ready-to-publish material layers: five distinct planets and a neutral Vaerkring port. -The ordinary Minecraft block IDs, recipes, drops and mechanics remain unchanged. -The same stone block has a different texture on each planet. The packs deliberately -contain **only** `minecraft/textures/block` and `minecraft/textures/item` assets; -no Dune item definitions, GUI fonts, screens, models, mobs or equipment overrides. -The three `dried_kelp_*` faces used by Network Artwork v1 as the Dune spice -carrier are explicitly excluded, even though they use vanilla texture paths. -Newer vanilla materials missing from the upstream set retain the client's own textures. - -## Art direction and source - -The existing [planet descriptions](https://www.dunerealms.com/races.html) and -`DuneTerrain` profiles are authoritative: - -| Planet | Materials | Stone texture | -| --- | --- | --- | -| Arrakduin | Warm granite, sandstone masonry, coarse earth, dry acacia timber | Granite | -| Kaladam | Wet coastal andesite, mossy ruins, coarse jungle soil, dark timber | Andesite | -| Giedermark | Industrial blackstone, basalt, cracked dark masonry, heavy timber | Blackstone | -| Kaiterhof | Pale dressed stone, quartz-like court masonry, light birch timber | Polished diorite | -| Sigmadraken IV | Cold grey rock, snow and ice, northern timber | Stone | -| Vaerkring | Neutral shared craft style | Stone | - -These are visual mappings, not new block types. `profiles.json` lists every -planet-specific substitution. Ordinary swords, tools, food and other base items -use the shared 16-pixel style on every planet, preserving their recognisability. -The original pixels are retained; no shaders, OptiFine, client mods or AI art required. - -![Material comparison](material-preview.png) - -Base: **Pixel Perfection Community Edition**, XSSheep and community contributors, -, pinned commit -`28e38cab7c1f03f86364ef704f705bebcc13cb3d`. -Its block/item art is vendored in `pixel-perfection-ce/`, with the complete -CC-BY-SA-4.0 license and original upstream README. The extracted textures and -our material mappings remain CC-BY-SA-4.0. Each distributable includes credit, -source URL, source revision, changes and the license. This licensing applies -to these art packs, not the unrelated Dune artwork or plugin source code. -Upstream's orphan `rail_golden_powered.png.mcmeta` is retained in the source -snapshot but omitted from releases because its matching PNG does not exist. - -## Build and verify - -From the repository root, Node 22 or newer, no third-party npm dependencies: - -```sh -node tools/build-planet-texture-packs.mjs -node --test tools/build-planet-texture-packs.test.mjs -``` - -`release-v1/` contains six ZIPs, SHA-1/SHA-256/size manifest and generated YAML. -Rebuilds use fixed entry timestamps and sorted paths. Use the same Node/zlib -version for exact archive-byte reproduction; another compressor may change hashes. -Every asset name and PNG signature, animation companion, ZIP round-trip, -hash pin and cross-planet stone distinction is checked. The resource-pack -format range follows the existing network pack: 64–97. - -When rebuilding a release, copy `release-v1/planet-textures.yml` to -`src/main/resources/planet-textures.yml`. Publish a new immutable version and -new pins if any distributed bytes change. Never overwrite a published pinned ZIP. - -## Activation after merge/deployment - -1. Publish all six ZIPs under their exact `/downloads/` URLs in `manifest.json`. - Verify their SHA-1/SHA-256 before enabling them. -2. Install the built `DunerealmsGUI.jar` on each Java Paper backend. -3. Set `enabled: true` in `plugins/DunerealmsGUI/planet-textures.yml` on each - backend and restart the plugin/server normally. Existing local config is - preserved. Defaults remain disabled until the downloads are published. -4. Standard canonical and public world aliases are included. For a backend - whose world is literally `world`, add an exact mapping under `worlds`, e.g. - `world: caladan`. Nether/End and unrecognised worlds remove this material - layer instead of inheriting the previous planet's textures. - -The listener uses one stable pack UUID across the network, replaces only that -layer on join/world change, skips repeated offers for the same planet and -removes stale layers at unknown worlds or disabled backends. Other pack UUIDs -remain intact. Downloads are optional: declining preserves ordinary vanilla -materials. Minecraft caches each immutable ZIP, but switching planet packs -still causes a client resource reload; it is not a zero-cost palette switch. - -Java packs are skipped for Floodgate players. A Bedrock/Geyser conversion is -not included or claimed. Live client rendering and proxy-transfer verification -must follow activation; local compilation is not that verification. +# Planet material packs · Java Edition + +Six ready-to-publish material layers: five distinct planets and a neutral Vaerkring port. +The ordinary Minecraft block IDs, recipes, drops and mechanics remain unchanged. +The same stone block has a different texture on each planet. The packs deliberately +contain **only** `minecraft/textures/block` and `minecraft/textures/item` assets; +no Dune item definitions, GUI fonts, screens, models, mobs or equipment overrides. +The three `dried_kelp_*` faces used by Network Artwork v1 as the Dune spice +carrier are explicitly excluded, even though they use vanilla texture paths. +Newer vanilla materials missing from the upstream set retain the client's own textures. + +## Art direction and source + +The existing [planet descriptions](https://www.dunerealms.com/races.html) and +`DuneTerrain` profiles are authoritative: + +| Planet | Materials | Stone texture | +| --- | --- | --- | +| Arrakduin | Warm granite, sandstone masonry, coarse earth, dry acacia timber | Granite | +| Kaladam | Wet coastal andesite, mossy ruins, coarse jungle soil, dark timber | Andesite | +| Giedermark | Industrial blackstone, basalt, cracked dark masonry, heavy timber | Blackstone | +| Kaiterhof | Pale dressed stone, quartz-like court masonry, light birch timber | Polished diorite | +| Sigmadraken IV | Cold grey rock, snow and ice, northern timber | Stone | +| Vaerkring | Neutral shared craft style | Stone | + +These are visual mappings, not new block types. `profiles.json` lists every +planet-specific substitution. Ordinary swords, tools, food and other base items +use the shared 16-pixel style on every planet, preserving their recognisability. +The original pixels are retained; no shaders, OptiFine, client mods or AI art required. + +![Material comparison](material-preview.png) + +Base: **Pixel Perfection Community Edition**, XSSheep and community contributors, +, pinned commit +`28e38cab7c1f03f86364ef704f705bebcc13cb3d`. +Its block/item art is vendored in `pixel-perfection-ce/`, with the complete +CC-BY-SA-4.0 license and original upstream README. The extracted textures and +our material mappings remain CC-BY-SA-4.0. Each distributable includes credit, +source URL, source revision, changes and the license. This licensing applies +to these art packs, not the unrelated Dune artwork or plugin source code. +Upstream's orphan `rail_golden_powered.png.mcmeta` is retained in the source +snapshot but omitted from releases because its matching PNG does not exist. + +## Build and verify + +From the repository root, Node 22 or newer, no third-party npm dependencies: + +```sh +node tools/build-planet-texture-packs.mjs +node --test tools/build-planet-texture-packs.test.mjs +``` + +`release-v1/` contains six ZIPs, SHA-1/SHA-256/size manifest and generated YAML. +Rebuilds use fixed entry timestamps and sorted paths. Use the same Node/zlib +version for exact archive-byte reproduction; another compressor may change hashes. +Every asset name and PNG signature, animation companion, ZIP round-trip, +hash pin and cross-planet stone distinction is checked. The resource-pack +format range follows the existing network pack: 64–97. + +When rebuilding a release, copy `release-v1/planet-textures.yml` to +`src/main/resources/planet-textures.yml`. Publish a new immutable version and +new pins if any distributed bytes change. Never overwrite a published pinned ZIP. + +## Activation after merge/deployment + +1. Publish all six ZIPs under their exact `/downloads/` URLs in `manifest.json`. + Verify their SHA-1/SHA-256 before enabling them. +2. Install the built `DunerealmsGUI.jar` on each Java Paper backend. +3. Set `enabled: true` in `plugins/DunerealmsGUI/planet-textures.yml` on each + backend and restart the plugin/server normally. Existing local config is + preserved. Defaults remain disabled until the downloads are published. +4. Standard canonical and public world aliases are included. For a backend + whose world is literally `world`, add an exact mapping under `worlds`, e.g. + `world: caladan`. Nether/End and unrecognised worlds remove this material + layer instead of inheriting the previous planet's textures. + +The listener uses one stable pack UUID across the network, replaces only that +layer on join/world change, skips repeated offers for the same planet and +removes stale layers at unknown worlds or disabled backends. Other pack UUIDs +remain intact. Downloads are optional: declining preserves ordinary vanilla +materials. Minecraft caches each immutable ZIP, but switching planet packs +still causes a client resource reload; it is not a zero-cost palette switch. + +Java packs are skipped for Floodgate players. A Bedrock/Geyser conversion is +not included or claimed. Live client rendering and proxy-transfer verification +must follow activation; local compilation is not that verification. diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java index 0dfa29cd..fb12f458 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java @@ -1,271 +1,271 @@ -package com.dunerealms.gui; - - - -import com.google.gson.*; -import net.kyori.adventure.key.Key; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; -import org.bukkit.*; -import org.bukkit.boss.*; -import org.bukkit.command.*; -import org.bukkit.entity.*; -import org.bukkit.event.*; -import org.bukkit.event.inventory.*; -import org.bukkit.event.player.*; -import org.bukkit.inventory.*; -import org.bukkit.persistence.PersistentDataType; -import org.bukkit.plugin.java.JavaPlugin; -import java.time.*; -import java.util.*; -import java.util.function.Consumer; - -/** Lobby presentation only. Character authority and committed keys remain central. */ -public final class DuneGUI extends JavaPlugin implements Listener,CommandExecutor { - private HouseBridge bridge; - private OrganisationMenus organisations; - private MCGUIMenus modernMenus; - private EcologyArtwork ecologyArtwork; - private QuestMenus quests; - private ExchangeMenus exchange; - private SpiceMenus spice; - private ItemPreviewMenu itemPreviews; - private final Map requests=new HashMap<>(); - private final Map records=new HashMap<>(); - private BossBar departure; - private NamespacedKey registrar; - private PersonalSidebar sidebar; - private PublicNameplates nameplates; - private final Map detached=new HashMap<>(); - private final Set dragonWarnings=new HashSet<>(); - private ExistingGuildService guild; - private final GuildBookings bookings=new GuildBookings(); - private final Set boarding=new HashSet<>(); - private final Set guiPackLoaded=new HashSet<>(); - private record Pack(UUID id,String url,String hash){} - private static final Pack DEFAULT_PACK=new Pack(UUID.fromString("a7b5ab7d-d8d8-5b51-b016-71a5f4c00008"),"https://www.dunerealms.com/downloads/DuneRealms-Network-Artwork-v1.zip","f1bc7d4851f1b361f14f96d260d5a91f769aa966"); - private Pack guiPack(){ - var file=new java.io.File(getDataFolder(),"gui-pack.yml");if(!file.isFile())return DEFAULT_PACK; - var data=org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(file); - try{String url=data.getString("url",""),hash=data.getString("sha1","");if(!url.matches("https://www\\.dunerealms\\.com/downloads/DuneRealms-(?:GUI-Houses-1\\.21\\.8|Network-Artwork)-v[0-9]+\\.zip")||!hash.matches("[0-9a-f]{40}"))throw new IllegalArgumentException();return new Pack(UUID.fromString(data.getString("id","")),url,hash);} - catch(IllegalArgumentException invalid){getLogger().warning("Invalid gui-pack.yml; using the bundled pack definition.");return DEFAULT_PACK;} - } - private long lastDepartureNotice=-1; - static final int[] CENTRES={10,13,16,29,33}; - static final String[] IDS={"atreides","harkonnen","corrino","ordos","fremen"}; - private static final Set HOUSE_IDS=Set.of(IDS); - private static final class Screen implements InventoryHolder { - final UUID owner,worldId;final GuiSession gate;final Map actions=new HashMap<>();Inventory inventory; - Screen(Player player){owner=player.getUniqueId();worldId=player.getWorld().getUID();gate=new GuiSession(owner);} - public Inventory getInventory(){return inventory;} - } - @Override public void onEnable(){ - bridge=new HouseBridge(); - spice=new SpiceMenus(this,bridge,p->organisations.console(p)); - exchange=new ExchangeMenus(this,bridge,p->organisations.console(p),p->guiPackLoaded.contains(p.getUniqueId())); - quests=new QuestMenus(this,bridge,p->organisations.console(p)); - itemPreviews=new ItemPreviewMenu(this,bridge,p->guiPackLoaded.contains(p.getUniqueId())); - organisations=new OrganisationMenus(this,bridge,p->fetch(p,null,0,null,data->mentat(p,data)),p->openGuild(p,null),p->fetch(p,null,0,null,data->select(p,data,null)),p->quests.open(p),p->exchange.open(p),p->spice.open(p),p->guiPackLoaded.contains(p.getUniqueId())); - registrar=new NamespacedKey(this,"house_registrar"); - modernMenus=new MCGUIMenus(this); - ecologyArtwork=new EcologyArtwork(this); - new PlanetTexturePacks(this); - - sidebar=new PersonalSidebar(this);nameplates=new PublicNameplates(this); - for(String command:List.of("spice","sellall","exchange","house","mentat","drgui","drscoreboard","guildtravel","clan","company","polgui"))Objects.requireNonNull(getCommand(command)).setExecutor(this); - try{guild=new ExistingGuildService(p->spice.open(p),(p,world)->openGuild(p,world),p->exchange.open(p),p->quests.open(p),p->organisations.console(p),p->{if(!sidebar.enabled(p))sidebar.toggle(p);refreshSidebar(p);p.sendMessage("Your central bank balance appears in your personal scoreboard.");});getLogger().info("Spacing Guild lobby entry connected to current House keys and twenty-minute boarding windows.");}catch(RuntimeException unavailable){getLogger().warning("Spacing Guild travel consumer unavailable; no journeys can be booked.");} - getServer().getPluginManager().registerEvents(this,this); - departure=Bukkit.createBossBar("Spacing Guild · next Imperial departure",BarColor.YELLOW,BarStyle.SOLID); - Bukkit.getScheduler().runTaskTimer(this,this::tick,20L,20L); - Bukkit.getScheduler().runTaskLater(this,this::ensureRegistrar,40L); - new QuartermasterNpc(this,p->quests.quartermaster(p,()->exchange.open(p),()->exchange.openKits(p))); - Bukkit.getScheduler().runTaskTimer(this,()->{for(Player p:Bukkit.getOnlinePlayers()){removeOldNavigators(p);refreshSidebar(p);}},80L,600L); - getLogger().info("House selector and Mentat screens enabled; central J.A.R.V.I.S. bridge; no Core/Lobby replacement."); - } - @Override public void onDisable(){if(modernMenus!=null)modernMenus.close();if(nameplates!=null)nameplates.close();if(exchange!=null)exchange.close();if(itemPreviews!=null)itemPreviews.close();if(quests!=null)quests.close();requests.clear();records.clear();bookings.clear();boarding.clear();if(guild!=null)guild.close();GuiSession.clear();if(sidebar!=null)sidebar.clear();for(var controller:detached.values())try{controller.restore();}catch(ReflectiveOperationException ignored){}detached.clear();if(departure!=null)departure.removeAll();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Screen)p.closeInventory();} - private boolean lobby(Player p){return p.getWorld().getName().equals("guild_lobby");} - @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){ - if(sender instanceof Player p&&command.getName().equals("sellall")){spice.sellAll(p,args.length==0?"guild":args[0].toLowerCase(Locale.ROOT));return true;} - if(sender instanceof Player p&&(command.getName().equals("spice")||command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("spice"))){spice.open(p);return true;} - if(sender instanceof Player player&&(command.getName().equals("exchange")||command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("exchange"))){exchange.open(player);return true;} - if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length>0&&args[0].equalsIgnoreCase("previewitem")){try{if(args.length!=3)throw new IllegalArgumentException();int revision=Integer.parseInt(args[2]);if(revision<1||revision>999999)throw new IllegalArgumentException();itemPreviews.open(player,UUID.fromString(args[1]),revision);}catch(IllegalArgumentException invalid){player.sendMessage("Use /drgui previewitem ");}return true;} - if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("quests")){quests.open(player);return true;} - if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("lore")){organisations.lore(player);return true;} - if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==0){organisations.console(player);return true;} - if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("item")){giveCodex(player,true);return true;} - if(sender instanceof Player member&&List.of("clan","company","polgui").contains(command.getName())){organisations.open(member,command.getName().equals("clan")?"clans":command.getName().equals("company")?"companies":"offices");return true;} - if(!(sender instanceof Player p))return true; - if(command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("organisations")){organisations.open(p,null);return true;} - if(command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("pack")){ - p.closeInventory();offerGuiPack(p); - p.sendMessage("Loading the DuneRealms GUI pack. Reopen your menu after loading.");return true; - } - if(command.getName().equals("drscoreboard")||args.length==1&&args[0].equalsIgnoreCase("scoreboard")){toggleSidebar(p);return true;} - if(command.getName().equals("guildtravel")||args.length==1&&args[0].equalsIgnoreCase("travel")){if(args.length==1&&args[0].equalsIgnoreCase("cancel")){cancelBooking(p);return true;}openGuild(p,null);return true;} - fetch(p,null,0,null,data->{if(command.getName().equals("mentat")&&selection(data)!=null)mentat(p,data);else select(p,data,null);});return true; - } - private void giveCodex(Player p,boolean explain){ - removeOldNavigators(p); - NamespacedKey itemId=new NamespacedKey("executableitems","ei-id"); - for(ItemStack item:p.getInventory().getContents())if(item!=null&&item.hasItemMeta()&&"dr_imperial_codex".equals(item.getItemMeta().getPersistentDataContainer().get(itemId,PersistentDataType.STRING))){if(explain)p.sendMessage("Your Imperial Codex is already in your inventory.");return;} - if(p.getInventory().firstEmpty()<0){if(explain)p.sendMessage("Make one inventory slot available, then use /drgui item.");return;} - try{var item=bridge.menuItem(p);int slot=p.getInventory().firstEmpty();p.getInventory().addItem(item);try{bridge.addedItem(p,item,slot);}catch(Exception eventFailure){getLogger().warning("ExecutableItems inventory hook unavailable: "+eventFailure.getClass().getSimpleName());}if(explain)p.sendMessage("Imperial Codex received. Right-click to open DuneRealms.");}catch(Exception unavailable){if(explain)p.sendMessage("The Imperial Codex item is temporarily unavailable. /drgui still opens your console.");getLogger().warning("Imperial Codex item could not be built: "+unavailable.getClass().getSimpleName());} - } - private void removeOldNavigators(Player p){ - var inventory=p.getInventory();for(int slot=0;slot{String house=selection(data);if(house==null){p.sendMessage("Choose and confirm your House before Guild passage.");select(p,data,null);return;}travelMenu(p,data);});} - private static GuildBookings.Permit permit(JsonObject data){String house=selection(data);if(house==null||!data.has("keyId")||data.get("keyId").isJsonNull())return null;try{return new GuildBookings.Permit(house,UUID.fromString(data.get("keyId").getAsString()),data.get("version").getAsInt());}catch(RuntimeException invalid){return null;}} - private void travelMenu(Player p,JsonObject data){var q=new JsonObject();q.addProperty("action","quote");guildRequest(p,q,quote->{data.add("guildQuote",quote);renderTravelMenu(p,data);});} - private void guildRequest(Player p,JsonObject input,Consumer done){UUID id=p.getUniqueId(),world=p.getWorld().getUID();if(!boarding.add(id)){p.sendMessage("J.A.R.V.I.S. is processing your passage.");return;}Bukkit.getScheduler().runTaskAsynchronously(this,()->{JsonObject result=null;String failure=null;try{result=bridge.guild(id,input);}catch(Exception e){failure=e.getMessage();}var response=result;String message=failure;if(!isEnabled())return;Bukkit.getScheduler().runTask(this,()->{if(!boarding.remove(id)||!p.isOnline()||!p.getWorld().getUID().equals(world))return;if(response==null){p.sendMessage(message==null?"The central Guild service is unavailable.":message);return;}done.accept(response);});});} - private void renderTravelMenu(Player p,JsonObject data){ - String house=selection(data);var home=GuildRoutes.home(house);if(home==null){select(p,data,null);return;} - String quote="Guild fare: "+String.format(java.util.Locale.ROOT,"%.2f",data.getAsJsonObject("guildQuote").get("fareMinor").getAsInt()/100.0)+" DM from your central personal bank account. Collected after arrival."; - var booked=bookings.get(p.getUniqueId());String detail=quote+"\nTravel opens at :00, :20 and :40 for five minutes."+(booked==null?"":"\nYour passage is already booked."); - if(BedrockForms.isBedrock(p)){List choices=new ArrayList<>();for(var route:GuildRoutes.ALL){boolean allowed=quotedDestinations(data.getAsJsonObject("guildQuote")).contains(route.world());choices.add(new BedrockForms.Choice((allowed?"§6":"§8")+route.name()+(allowed?(route.house().equals(house)?" · Your House":" · Imperial passage"):" · Unavailable"),allowed?detail:"Another House world",allowed?()->bookPassage(p,data,route.world()):()->travelMenu(p,data),"https://www.dunerealms.com/assets/gui/guild-world-"+route.world().replace('_','-')+(allowed?"":"-locked")+"-v1.png"));}choices.add(new BedrockForms.Choice("Cancel booking","No fare has been charged",()->{cancelBooking(p);travelMenu(p,data);}));choices.add(new BedrockForms.Choice("Your Mentat","Return to your House adviser",()->mentat(p,data)));BedrockForms.show(this,p,"Spacing Guild · Imperial passage",detail,choices);return;} - int own=Arrays.asList(IDS).indexOf(house);Screen screen=screen(p,"Spacing Guild · Imperial passage",0xE330+own); - for(int i=0;ibookPassage(p,data,route.world()));}} - button(screen,p,45,"Your Mentat","Return to your House adviser",Material.ARROW,()->mentat(p,data));screen.actions.put(46,screen.actions.get(45)); - button(screen,p,49,"Cancel booking","No fare is taken for a cancelled booking",Material.BARRIER,()->{cancelBooking(p);travelMenu(p,data);});for(int slot:new int[]{48,50})screen.actions.put(slot,screen.actions.get(49)); - if(guild!=null){button(screen,p,53,booked==null?"Book passage":"Review booked passage",detail,Material.EMERALD,()->bookPassage(p,data));screen.actions.put(52,screen.actions.get(53));} - if(MCGUIMenus.show(p,"Spacing Guild · Imperial passage","",screen.inventory,screen.actions,screen.gate))return; - p.openInventory(screen.inventory);expire(screen); - } - private void cancelBooking(Player p){boolean removed=bookings.cancel(p.getUniqueId());removed=boarding.remove(p.getUniqueId())||removed;p.sendMessage(removed?"Guild passage cancelled. No fare was charged.":"You have no pending Guild booking.");} - private static Set quotedDestinations(JsonObject quote){Set worlds=new HashSet<>();if(quote.has("destinations"))for(var value:quote.getAsJsonArray("destinations"))worlds.add(value.getAsString());else worlds.add(quote.get("destination").getAsString());return Set.copyOf(worlds);} - private void bookPassage(Player p,JsonObject shown){var booked=bookings.get(p.getUniqueId());bookPassage(p,shown,booked==null?GuildRoutes.home(selection(shown)).world():booked.world());} - private void bookPassage(Player p,JsonObject shown,String destination){ - if(boarding.contains(p.getUniqueId())){p.sendMessage("Guild boarding is already being confirmed.");return;} - var expected=permit(shown);if(expected==null){p.sendMessage("Confirm your current House key before booking passage.");select(p,shown,selection(shown));return;} - fetch(p,null,0,null,fresh->{var current=permit(fresh);if(current==null||!current.equals(expected)){p.sendMessage("Your House key changed. Review the current passage.");travelMenu(p,fresh);return;} - var q=new JsonObject();q.addProperty("action","quote");guildRequest(p,q,quote->{if(!quote.get("affordable").getAsBoolean()){p.sendMessage("Not enough available Dunemarks in your central personal bank account.");return;}var home=GuildRoutes.ALL.stream().filter(r->r.world().equals(destination)).findFirst().orElseThrow();int fare=quote.get("fareMinor").getAsInt();if(!quotedDestinations(quote).contains(destination)){p.sendMessage("Your House destination changed. Reopen the menu.");return;}var booked=bookings.book(p.getUniqueId(),current,home.world(),fare,Instant.now().getEpochSecond(),quotedDestinations(quote));p.closeInventory();p.sendMessage(Component.text("Passage booked to "+home.name()+". Fare "+String.format(java.util.Locale.ROOT,"%.2f",booked.fare()/100.0)+" DM is reserved at boarding and collected after arrival.",NamedTextColor.GOLD));}); - }); - } - private void board(GuildBookings.Booking booking){ - Player p=Bukkit.getPlayer(booking.player());if(p==null||!p.isOnline()||!lobby(p)||!boarding.add(booking.player()))return; - Bukkit.getScheduler().runTaskAsynchronously(this,()->{JsonObject ticket=null;String failure=null;try{var fresh=bridge.request(booking.player(),null,0,null);var current=permit(fresh);if(current==null||!booking.matches(current,booking.fare(),Instant.now().getEpochSecond())||!bridge.worldOnline(booking.world()))throw new IllegalStateException("Your key, boarding window or destination changed. Please rebook.");var q=new JsonObject();q.addProperty("action","board");q.addProperty("requestId",booking.requestId().toString());q.addProperty("keyId",current.keyId().toString());q.addProperty("version",current.version());q.addProperty("fareMinor",booking.fare());q.addProperty("destination",booking.world());ticket=bridge.guild(booking.player(),q);}catch(Exception e){failure=e.getMessage();}var result=ticket;String message=failure;if(!isEnabled())return;Bukkit.getScheduler().runTask(this,()->{if(!boarding.remove(booking.player())||!p.isOnline()||!lobby(p))return;try{if(result==null){p.sendMessage(message==null?"Passage was not confirmed. Any unused reservation expires automatically.":message);return;}p.closeInventory();bridge.dispatchGuild(p,result);}catch(Exception unavailable){p.sendMessage("The transfer was not sent. Your unused fare reservation will expire automatically.");}});}); - } - private void fetch(Player p,String house,int version,UUID requestId,Consumer callback){ - UUID owner=p.getUniqueId();if(requests.containsKey(owner)){p.sendMessage("The House register is processing your request.");return;} - UUID operation=UUID.randomUUID(),worldId=p.getWorld().getUID();requests.put(owner,operation);p.closeInventory();p.sendMessage(Component.text("Jarvis executing matrix",NamedTextColor.GOLD)); - Bukkit.getScheduler().runTaskAsynchronously(this,()->{ - JsonObject result=null;String error=null; - try{result=bridge.request(owner,house,version,requestId);}catch(Exception unavailable){error=unavailable instanceof java.io.IOException?unavailable.getMessage():"The House register is unavailable. Please retry.";} - JsonObject received=result;String failure=error;if(!isEnabled())return; - Bukkit.getScheduler().runTask(this,()->{if(!operation.equals(requests.get(owner)))return;requests.remove(owner);if(!p.isOnline()||!worldId.equals(p.getWorld().getUID()))return; - if(received==null){p.sendMessage(Component.text(failure,NamedTextColor.RED));return;} - records.put(owner,received);updateSidebar(p,received);callback.accept(received); - }); - }); - } - private void refreshSidebar(Player p){ - UUID owner=p.getUniqueId();if(requests.containsKey(owner))return;UUID operation=UUID.randomUUID();requests.put(owner,operation); - Bukkit.getScheduler().runTaskAsynchronously(this,()->{JsonObject result=null;try{result=bridge.request(owner,null,0,null);}catch(Exception unavailable){}JsonObject received=result;if(!isEnabled())return; - Bukkit.getScheduler().runTask(this,()->{if(!operation.equals(requests.get(owner)))return;requests.remove(owner);if(!p.isOnline())return; - if(received!=null){records.put(owner,received);updateSidebar(p,received);}else{records.remove(owner);sidebar.update(p,null,null);nameplates.update(p,null,null,null);} - }); - }); - } - private void updateSidebar(Player p,JsonObject data){String house=selection(data),label=house==null?null:houseName(data,house);sidebar.update(p,data,label);nameplates.update(p,data,house,label);} - private void toggleSidebar(Player p){sidebar.toggle(p);p.sendMessage(Component.text(sidebar.enabled(p)?"Personal scoreboard enabled.":"Personal scoreboard hidden.",NamedTextColor.GOLD));if(sidebar.enabled(p)){JsonObject data=records.get(p.getUniqueId());if(data!=null)updateSidebar(p,data);refreshSidebar(p);}} - @EventHandler public void scoreboardCommand(PlayerCommandPreprocessEvent e){String command=e.getMessage().trim();if(command.equalsIgnoreCase("/scoreboard")){e.setCancelled(true);toggleSidebar(e.getPlayer());}} - @EventHandler(priority=EventPriority.HIGHEST) public void oldNavigator(PlayerInteractEvent e){if(e.getHand()!=EquipmentSlot.HAND||e.getItem()==null||!e.getItem().hasItemMeta()||!e.getAction().isRightClick())return;var data=e.getItem().getItemMeta().getPersistentDataContainer();for(var key:data.getKeys())if(data.has(key,PersistentDataType.STRING)&&"menu_opener".equals(data.get(key,PersistentDataType.STRING))){e.setCancelled(true);organisations.console(e.getPlayer());return;}} - @EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=true) public void legacyTravel(PlayerCommandPreprocessEvent e){String[] args=e.getMessage().substring(1).trim().toLowerCase(Locale.ROOT).split("\\s+");String label=args[0].replaceFirst("^[^:]+:","");if(label.equals("balance")||label.equals("bal")||label.equals("money")){e.setCancelled(true);if(!sidebar.enabled(e.getPlayer()))sidebar.toggle(e.getPlayer());refreshSidebar(e.getPlayer());return;}if(label.equals("exchange")){e.setCancelled(true);exchange.open(e.getPlayer());return;}if(label.equals("server")||label.equals("duneess")&&args.length>1&&args[1].equals("travel")){e.setCancelled(true);openGuild(e.getPlayer(),null);}} - private void offerGuiPack(Player p){ - if(!lobby(p)){p.sendMessage("Visit Spacing Guild lobby to update your DuneRealms artwork.");return;} - guiPackLoaded.remove(p.getUniqueId()); - var pack=guiPack();p.addResourcePack(pack.id(),pack.url(),java.util.HexFormat.of().parseHex(pack.hash()),"DuneRealms menus and item artwork",true); - MCGUIMenus.offerPack(p); - ecologyArtwork.offer(p); - } - @EventHandler public void join(PlayerJoinEvent e){Bukkit.getScheduler().runTaskLater(this,()->{ - Player p=e.getPlayer();if(!p.isOnline())return; - // Offer once in the play phase too: configuration-phase pack loading may finish - // before the ordinary Bukkit player status event is available. The hash reuses cache. - if(lobby(p)&&!BedrockForms.isBedrock(p)){if(!guiPackLoaded.contains(p.getUniqueId()))offerGuiPack(p);else ecologyArtwork.offer(p);} - giveCodex(p,false); - if(sidebar.enabled(p))refreshSidebar(p); - },40L);} - @EventHandler public void packStatus(PlayerResourcePackStatusEvent e){ - if(!guiPack().id().equals(e.getID()))return; - getLogger().info("GUI pack status for "+e.getPlayer().getName()+": "+e.getStatus()); - if(e.getStatus()==PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED){guiPackLoaded.add(e.getPlayer().getUniqueId());e.getPlayer().sendMessage(Component.text("DuneRealms artwork loaded. Reopen your menu.",NamedTextColor.GREEN));return;} - guiPackLoaded.remove(e.getPlayer().getUniqueId()); - } - @EventHandler public void world(PlayerChangedWorldEvent e){bookings.cancel(e.getPlayer().getUniqueId());boarding.remove(e.getPlayer().getUniqueId());sidebar.hide(e.getPlayer());records.remove(e.getPlayer().getUniqueId());if(sidebar.enabled(e.getPlayer()))refreshSidebar(e.getPlayer());} - static String selection(JsonObject data){if(!data.has("selection")||data.get("selection").isJsonNull())return null;String value=data.get("selection").getAsString();return HOUSE_IDS.contains(value)?value:null;} - private String houseName(JsonObject data,String id){for(var entry:data.getAsJsonArray("choices")){var h=entry.getAsJsonObject();if(h.get("id").getAsString().equals(id))return h.get("name").getAsString();}throw new IllegalArgumentException("Unknown House");} - private void select(Player p,JsonObject data,String picked){ - String current=selection(data),chosen=picked!=null?picked:current; - if(BedrockForms.isBedrock(p)){ - List choices=new ArrayList<>(); - for(var entry:data.getAsJsonArray("choices")){var house=entry.getAsJsonObject();String id=house.get("id").getAsString();if(!HOUSE_IDS.contains(id))continue; - choices.add(new BedrockForms.Choice(house.get("name").getAsString()+(id.equals(current)?" · Your House":""),"Review and confirm allegiance",()->confirmForm(p,data,id),"https://www.dunerealms.com/assets/seals/"+house.get("seal").getAsString())); - } - choices.add(new BedrockForms.Choice(sidebar.enabled(p)?"Hide scoreboard":"Show scoreboard","Personal briefing display",()->{toggleSidebar(p);select(p,data,picked);})); - BedrockForms.show(this,p,"Choose your House","Declare your allegiance. Review a House before confirming.",choices);return; - } - Screen screen=screen(p,"Choose your House",0xE300+(chosen==null?0:Arrays.asList(IDS).indexOf(chosen)+1)); - for(int i=0;iselect(p,data,id));} - } - button(screen,p,45,"Close","Return to the lobby",Material.ARROW,p::closeInventory); - button(screen,p,49,sidebar.enabled(p)?"Hide scoreboard":"Show scoreboard","Toggle your personal briefing",Material.LEVER,()->{toggleSidebar(p);select(p,data,chosen);}); - for(int slot:new int[]{48,50})screen.actions.put(slot,screen.actions.get(49)); - if(chosen!=null)button(screen,p,53,"Confirm "+houseName(data,chosen),"Write your confirmed House key",Material.LIME_DYE,()->confirm(p,data,chosen)); - screen.actions.put(46,screen.actions.get(45));if(chosen!=null)screen.actions.put(52,screen.actions.get(53)); - if(MCGUIMenus.show(p,"Choose your House","",screen.inventory,screen.actions,screen.gate))return; - p.openInventory(screen.inventory);expire(screen); - } - private void confirmForm(Player p,JsonObject data,String id){BedrockForms.show(this,p,"Confirm House · "+houseName(data,id),"Confirm your allegiance to "+houseName(data,id)+". This initial selection does not grant an elected office.",List.of(new BedrockForms.Choice("Confirm House","Save through J.A.R.V.I.S.",()->confirm(p,data,id)),new BedrockForms.Choice("Back","Review all five Houses",()->select(p,data,id))));} - private void confirm(Player p,JsonObject data,String id){ - if(id.equals(selection(data))&&data.has("keyId")&&!data.get("keyId").isJsonNull()){mentat(p,data);return;} - fetch(p,id,data.get("version").getAsInt(),UUID.randomUUID(),saved->{p.sendMessage(Component.text("House allegiance confirmed in J.A.R.V.I.S.",NamedTextColor.GREEN));mentat(p,saved);}); - } - private void mentat(Player p,JsonObject data){ - String house=selection(data);if(house==null){select(p,data,null);return;} - JsonObject mentor=data.getAsJsonObject("mentat");String name=mentor.get("name").getAsString();int index=Arrays.asList(IDS).indexOf(house); - if(BedrockForms.isBedrock(p)){BedrockForms.show(this,p,"Your Mentat · "+name,houseName(data,house)+"\nYour House briefing is ready.",List.of(new BedrockForms.Choice("Open Mentat Report","Open your website mission journal",()->quests.open(p),"https://www.dunerealms.com/assets/gui/mentat-"+house+"-v1.png"),new BedrockForms.Choice(sidebar.enabled(p)?"Hide scoreboard":"Show scoreboard","Personal briefing display",()->{toggleSidebar(p);mentat(p,data);}),new BedrockForms.Choice("Spacing Guild travel","Book passage to your House world",()->openGuild(p,null))));return;} - Screen screen=screen(p,"Your Mentat · "+name,0xE310+index); - var portrait=icon(p,name,houseName(data,house),"drgui_transparent",Material.PLAYER_HEAD);menuArt(portrait,"mentat_"+house);screen.inventory.setItem(13,portrait); - button(screen,p,38,"Open Mentat Report","Personal level, Reputation and active quests",Material.WRITABLE_BOOK,()->quests.open(p)); - button(screen,p,42,"Spacing Guild travel","Book passage to your House world",Material.COMPASS,()->openGuild(p,null)); - button(screen,p,45,"Your House",houseName(data,house),Material.ARROW,()->select(p,data,house)); - button(screen,p,49,sidebar.enabled(p)?"Hide scoreboard":"Show scoreboard","Toggle your personal briefing",Material.LEVER,()->{toggleSidebar(p);mentat(p,data);});for(int slot:new int[]{48,50})screen.actions.put(slot,screen.actions.get(49)); - for(int slot:new int[]{37,39})screen.actions.put(slot,screen.actions.get(38));for(int slot:new int[]{41,43})screen.actions.put(slot,screen.actions.get(42));screen.actions.put(46,screen.actions.get(45)); - if(MCGUIMenus.show(p,"Your Mentat · "+name,"",screen.inventory,screen.actions,screen.gate))return; - p.openInventory(screen.inventory);expire(screen); - } - private static void menuArt(ItemStack item,String artwork){var meta=item.getItemMeta();meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","menu_art"),PersistentDataType.STRING,artwork);item.setItemMeta(meta);} - private void report(Player p){p.closeInventory();p.sendMessage(Component.text("Open your Mentat Report →",NamedTextColor.GOLD).clickEvent(net.kyori.adventure.text.event.ClickEvent.openUrl("https://clans.dunerealms.com/#quests/quests")));} - private Screen screen(Player p,String title,int glyph){Screen s=new Screen(p);Component heading=guiPackLoaded.contains(p.getUniqueId())?Component.text(GuiArtwork.background(glyph),NamedTextColor.WHITE).font(Key.key("dunerealms:house_selector")):Component.text(title,NamedTextColor.GOLD);s.inventory=Bukkit.createInventory(s,54,heading);return s;} - private ItemStack icon(Player p,String title,String description,String model,Material fallback){ItemStack item=new ItemStack(guiPackLoaded.contains(p.getUniqueId())?Material.PAPER:fallback);var meta=item.getItemMeta();meta.displayName(Component.text(title,NamedTextColor.GOLD));meta.lore(List.of(Component.text(description,NamedTextColor.GRAY)));if(guiPackLoaded.contains(p.getUniqueId()))meta.setItemModel(new NamespacedKey("dunerealms",model));item.setItemMeta(meta);return item;} - private void button(Screen s,Player p,int slot,String title,String description,Material material,Runnable action){s.inventory.setItem(slot,icon(p,title,description,"drgui_transparent",material));s.actions.put(slot,action);} - private void expire(Screen screen){Bukkit.getScheduler().runTaskLater(this,screen.gate::expire,2400L);} - @EventHandler public void click(InventoryClickEvent event){if(!(event.getView().getTopInventory().getHolder() instanceof Screen s))return;event.setCancelled(true); - if(!(event.getWhoClicked() instanceof Player p)||!p.getUniqueId().equals(s.owner)||event.getClickedInventory()!=s.inventory||event.getClick()!=ClickType.LEFT)return; - Runnable action=s.actions.get(event.getRawSlot());if(action==null||!s.gate.claim(p.getUniqueId()))return; - Bukkit.getScheduler().runTask(this,()->{if(p.isOnline()&&s.worldId.equals(p.getWorld().getUID())&&p.getOpenInventory().getTopInventory()==s.inventory)action.run();}); - } - @EventHandler public void drag(InventoryDragEvent e){if(e.getView().getTopInventory().getHolder() instanceof Screen)e.setCancelled(true);} - @EventHandler public void close(InventoryCloseEvent e){if(e.getInventory().getHolder() instanceof Screen s)s.gate.expire();} - @EventHandler public void quit(PlayerQuitEvent e){guiPackLoaded.remove(e.getPlayer().getUniqueId());bookings.cancel(e.getPlayer().getUniqueId());boarding.remove(e.getPlayer().getUniqueId());requests.remove(e.getPlayer().getUniqueId());records.remove(e.getPlayer().getUniqueId());sidebar.hide(e.getPlayer());departure.removePlayer(e.getPlayer());} - private void ensureRegistrar(){World world=Bukkit.getWorld("guild_lobby");if(world==null)return;Location at=world.getSpawnLocation().clone().add(2,0,0);at.getChunk().load(); - for(Entity entity:world.getEntities())if(entity.getPersistentDataContainer().has(registrar,PersistentDataType.BYTE))return; - Villager npc=world.spawn(at,Villager.class);npc.setAI(false);npc.setInvulnerable(true);npc.setPersistent(true);npc.setSilent(true);npc.setCollidable(false);npc.setProfession(Villager.Profession.LIBRARIAN);npc.customName(Component.text("House Registrar · Choose your House",NamedTextColor.GOLD));npc.setCustomNameVisible(true);npc.getPersistentDataContainer().set(registrar,PersistentDataType.BYTE,(byte)1); - } - @EventHandler public void npc(PlayerInteractEntityEvent e){if(!e.getRightClicked().getPersistentDataContainer().has(registrar,PersistentDataType.BYTE))return;e.setCancelled(true);if(e.getHand()!=EquipmentSlot.HAND||!lobby(e.getPlayer()))return;fetch(e.getPlayer(),null,0,null,data->{if(selection(data)!=null)mentat(e.getPlayer(),data);else select(e.getPlayer(),data,null);});} - private void tick(){ - long seconds=Instant.now().getEpochSecond(),remaining=DepartureWindow.remaining(seconds);var phase=DepartureWindow.phase(seconds);departure.setTitle("Spacing Guild · "+switch(phase){case BOARDING->"Travel open · closes in ";case LAUNCHING->"Launching · ";case WAITING->"Boarding opens in ";}+String.format(Locale.ROOT,"%02d:%02d",remaining/60,remaining%60));departure.setColor(phase==DepartureWindow.Phase.BOARDING?BarColor.GREEN:BarColor.YELLOW);departure.setProgress(DepartureWindow.progress(seconds)); - long now=Instant.now().getEpochSecond();for(var booking:bookings.due(now))board(booking); - if(((phase==DepartureWindow.Phase.BOARDING&&remaining==300)||(phase==DepartureWindow.Phase.WAITING&&(remaining==300||remaining==60||remaining==10)))&&lastDepartureNotice!=now){lastDepartureNotice=now;for(Player p:Bukkit.getOnlinePlayers())if(lobby(p))p.sendMessage(Component.text(phase==DepartureWindow.Phase.BOARDING?"Spacing Guild · travel is open for five minutes.":"Spacing Guild · boarding opens in "+(remaining>=60?remaining/60+" minute(s).":remaining+" seconds."),NamedTextColor.GOLD));} - for(World world:Bukkit.getWorlds())if(world.getName().equals("guild_lobby")){var battle=world.getEnderDragonBattle();if(battle!=null){if(battle.getBossBar()!=null){battle.getBossBar().setVisible(false);battle.getBossBar().removeAll();} - if(!detached.containsKey(world.getUID()))try{Object handle=world.getClass().getMethod("getHandle").invoke(world);detached.put(world.getUID(),DragonController.detach(handle));getLogger().info("Lobby dragon controller detached; native bossbar disabled.");}catch(ReflectiveOperationException|RuntimeException unsupported){if(dragonWarnings.add(world.getUID()))getLogger().warning("Lobby dragon controller could not be detached; native bossbar fallback active.");} - }} - for(Player p:Bukkit.getOnlinePlayers())if(lobby(p)){if(!departure.getPlayers().contains(p))departure.addPlayer(p);}else departure.removePlayer(p); - } -} +package com.dunerealms.gui; + + + +import com.google.gson.*; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.*; +import org.bukkit.boss.*; +import org.bukkit.command.*; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.inventory.*; +import org.bukkit.event.player.*; +import org.bukkit.inventory.*; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.plugin.java.JavaPlugin; +import java.time.*; +import java.util.*; +import java.util.function.Consumer; + +/** Lobby presentation only. Character authority and committed keys remain central. */ +public final class DuneGUI extends JavaPlugin implements Listener,CommandExecutor { + private HouseBridge bridge; + private OrganisationMenus organisations; + private MCGUIMenus modernMenus; + private EcologyArtwork ecologyArtwork; + private QuestMenus quests; + private ExchangeMenus exchange; + private SpiceMenus spice; + private ItemPreviewMenu itemPreviews; + private final Map requests=new HashMap<>(); + private final Map records=new HashMap<>(); + private BossBar departure; + private NamespacedKey registrar; + private PersonalSidebar sidebar; + private PublicNameplates nameplates; + private final Map detached=new HashMap<>(); + private final Set dragonWarnings=new HashSet<>(); + private ExistingGuildService guild; + private final GuildBookings bookings=new GuildBookings(); + private final Set boarding=new HashSet<>(); + private final Set guiPackLoaded=new HashSet<>(); + private record Pack(UUID id,String url,String hash){} + private static final Pack DEFAULT_PACK=new Pack(UUID.fromString("a7b5ab7d-d8d8-5b51-b016-71a5f4c00008"),"https://www.dunerealms.com/downloads/DuneRealms-Network-Artwork-v1.zip","f1bc7d4851f1b361f14f96d260d5a91f769aa966"); + private Pack guiPack(){ + var file=new java.io.File(getDataFolder(),"gui-pack.yml");if(!file.isFile())return DEFAULT_PACK; + var data=org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(file); + try{String url=data.getString("url",""),hash=data.getString("sha1","");if(!url.matches("https://www\\.dunerealms\\.com/downloads/DuneRealms-(?:GUI-Houses-1\\.21\\.8|Network-Artwork)-v[0-9]+\\.zip")||!hash.matches("[0-9a-f]{40}"))throw new IllegalArgumentException();return new Pack(UUID.fromString(data.getString("id","")),url,hash);} + catch(IllegalArgumentException invalid){getLogger().warning("Invalid gui-pack.yml; using the bundled pack definition.");return DEFAULT_PACK;} + } + private long lastDepartureNotice=-1; + static final int[] CENTRES={10,13,16,29,33}; + static final String[] IDS={"atreides","harkonnen","corrino","ordos","fremen"}; + private static final Set HOUSE_IDS=Set.of(IDS); + private static final class Screen implements InventoryHolder { + final UUID owner,worldId;final GuiSession gate;final Map actions=new HashMap<>();Inventory inventory; + Screen(Player player){owner=player.getUniqueId();worldId=player.getWorld().getUID();gate=new GuiSession(owner);} + public Inventory getInventory(){return inventory;} + } + @Override public void onEnable(){ + bridge=new HouseBridge(); + spice=new SpiceMenus(this,bridge,p->organisations.console(p)); + exchange=new ExchangeMenus(this,bridge,p->organisations.console(p),p->guiPackLoaded.contains(p.getUniqueId())); + quests=new QuestMenus(this,bridge,p->organisations.console(p)); + itemPreviews=new ItemPreviewMenu(this,bridge,p->guiPackLoaded.contains(p.getUniqueId())); + organisations=new OrganisationMenus(this,bridge,p->fetch(p,null,0,null,data->mentat(p,data)),p->openGuild(p,null),p->fetch(p,null,0,null,data->select(p,data,null)),p->quests.open(p),p->exchange.open(p),p->spice.open(p),p->guiPackLoaded.contains(p.getUniqueId())); + registrar=new NamespacedKey(this,"house_registrar"); + modernMenus=new MCGUIMenus(this); + ecologyArtwork=new EcologyArtwork(this); + new PlanetTexturePacks(this); + + sidebar=new PersonalSidebar(this);nameplates=new PublicNameplates(this); + for(String command:List.of("spice","sellall","exchange","house","mentat","drgui","drscoreboard","guildtravel","clan","company","polgui"))Objects.requireNonNull(getCommand(command)).setExecutor(this); + try{guild=new ExistingGuildService(p->spice.open(p),(p,world)->openGuild(p,world),p->exchange.open(p),p->quests.open(p),p->organisations.console(p),p->{if(!sidebar.enabled(p))sidebar.toggle(p);refreshSidebar(p);p.sendMessage("Your central bank balance appears in your personal scoreboard.");});getLogger().info("Spacing Guild lobby entry connected to current House keys and twenty-minute boarding windows.");}catch(RuntimeException unavailable){getLogger().warning("Spacing Guild travel consumer unavailable; no journeys can be booked.");} + getServer().getPluginManager().registerEvents(this,this); + departure=Bukkit.createBossBar("Spacing Guild · next Imperial departure",BarColor.YELLOW,BarStyle.SOLID); + Bukkit.getScheduler().runTaskTimer(this,this::tick,20L,20L); + Bukkit.getScheduler().runTaskLater(this,this::ensureRegistrar,40L); + new QuartermasterNpc(this,p->quests.quartermaster(p,()->exchange.open(p),()->exchange.openKits(p))); + Bukkit.getScheduler().runTaskTimer(this,()->{for(Player p:Bukkit.getOnlinePlayers()){removeOldNavigators(p);refreshSidebar(p);}},80L,600L); + getLogger().info("House selector and Mentat screens enabled; central J.A.R.V.I.S. bridge; no Core/Lobby replacement."); + } + @Override public void onDisable(){if(modernMenus!=null)modernMenus.close();if(nameplates!=null)nameplates.close();if(exchange!=null)exchange.close();if(itemPreviews!=null)itemPreviews.close();if(quests!=null)quests.close();requests.clear();records.clear();bookings.clear();boarding.clear();if(guild!=null)guild.close();GuiSession.clear();if(sidebar!=null)sidebar.clear();for(var controller:detached.values())try{controller.restore();}catch(ReflectiveOperationException ignored){}detached.clear();if(departure!=null)departure.removeAll();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Screen)p.closeInventory();} + private boolean lobby(Player p){return p.getWorld().getName().equals("guild_lobby");} + @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){ + if(sender instanceof Player p&&command.getName().equals("sellall")){spice.sellAll(p,args.length==0?"guild":args[0].toLowerCase(Locale.ROOT));return true;} + if(sender instanceof Player p&&(command.getName().equals("spice")||command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("spice"))){spice.open(p);return true;} + if(sender instanceof Player player&&(command.getName().equals("exchange")||command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("exchange"))){exchange.open(player);return true;} + if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length>0&&args[0].equalsIgnoreCase("previewitem")){try{if(args.length!=3)throw new IllegalArgumentException();int revision=Integer.parseInt(args[2]);if(revision<1||revision>999999)throw new IllegalArgumentException();itemPreviews.open(player,UUID.fromString(args[1]),revision);}catch(IllegalArgumentException invalid){player.sendMessage("Use /drgui previewitem ");}return true;} + if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("quests")){quests.open(player);return true;} + if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("lore")){organisations.lore(player);return true;} + if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==0){organisations.console(player);return true;} + if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("item")){giveCodex(player,true);return true;} + if(sender instanceof Player member&&List.of("clan","company","polgui").contains(command.getName())){organisations.open(member,command.getName().equals("clan")?"clans":command.getName().equals("company")?"companies":"offices");return true;} + if(!(sender instanceof Player p))return true; + if(command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("organisations")){organisations.open(p,null);return true;} + if(command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("pack")){ + p.closeInventory();offerGuiPack(p); + p.sendMessage("Loading the DuneRealms GUI pack. Reopen your menu after loading.");return true; + } + if(command.getName().equals("drscoreboard")||args.length==1&&args[0].equalsIgnoreCase("scoreboard")){toggleSidebar(p);return true;} + if(command.getName().equals("guildtravel")||args.length==1&&args[0].equalsIgnoreCase("travel")){if(args.length==1&&args[0].equalsIgnoreCase("cancel")){cancelBooking(p);return true;}openGuild(p,null);return true;} + fetch(p,null,0,null,data->{if(command.getName().equals("mentat")&&selection(data)!=null)mentat(p,data);else select(p,data,null);});return true; + } + private void giveCodex(Player p,boolean explain){ + removeOldNavigators(p); + NamespacedKey itemId=new NamespacedKey("executableitems","ei-id"); + for(ItemStack item:p.getInventory().getContents())if(item!=null&&item.hasItemMeta()&&"dr_imperial_codex".equals(item.getItemMeta().getPersistentDataContainer().get(itemId,PersistentDataType.STRING))){if(explain)p.sendMessage("Your Imperial Codex is already in your inventory.");return;} + if(p.getInventory().firstEmpty()<0){if(explain)p.sendMessage("Make one inventory slot available, then use /drgui item.");return;} + try{var item=bridge.menuItem(p);int slot=p.getInventory().firstEmpty();p.getInventory().addItem(item);try{bridge.addedItem(p,item,slot);}catch(Exception eventFailure){getLogger().warning("ExecutableItems inventory hook unavailable: "+eventFailure.getClass().getSimpleName());}if(explain)p.sendMessage("Imperial Codex received. Right-click to open DuneRealms.");}catch(Exception unavailable){if(explain)p.sendMessage("The Imperial Codex item is temporarily unavailable. /drgui still opens your console.");getLogger().warning("Imperial Codex item could not be built: "+unavailable.getClass().getSimpleName());} + } + private void removeOldNavigators(Player p){ + var inventory=p.getInventory();for(int slot=0;slot{String house=selection(data);if(house==null){p.sendMessage("Choose and confirm your House before Guild passage.");select(p,data,null);return;}travelMenu(p,data);});} + private static GuildBookings.Permit permit(JsonObject data){String house=selection(data);if(house==null||!data.has("keyId")||data.get("keyId").isJsonNull())return null;try{return new GuildBookings.Permit(house,UUID.fromString(data.get("keyId").getAsString()),data.get("version").getAsInt());}catch(RuntimeException invalid){return null;}} + private void travelMenu(Player p,JsonObject data){var q=new JsonObject();q.addProperty("action","quote");guildRequest(p,q,quote->{data.add("guildQuote",quote);renderTravelMenu(p,data);});} + private void guildRequest(Player p,JsonObject input,Consumer done){UUID id=p.getUniqueId(),world=p.getWorld().getUID();if(!boarding.add(id)){p.sendMessage("J.A.R.V.I.S. is processing your passage.");return;}Bukkit.getScheduler().runTaskAsynchronously(this,()->{JsonObject result=null;String failure=null;try{result=bridge.guild(id,input);}catch(Exception e){failure=e.getMessage();}var response=result;String message=failure;if(!isEnabled())return;Bukkit.getScheduler().runTask(this,()->{if(!boarding.remove(id)||!p.isOnline()||!p.getWorld().getUID().equals(world))return;if(response==null){p.sendMessage(message==null?"The central Guild service is unavailable.":message);return;}done.accept(response);});});} + private void renderTravelMenu(Player p,JsonObject data){ + String house=selection(data);var home=GuildRoutes.home(house);if(home==null){select(p,data,null);return;} + String quote="Guild fare: "+String.format(java.util.Locale.ROOT,"%.2f",data.getAsJsonObject("guildQuote").get("fareMinor").getAsInt()/100.0)+" DM from your central personal bank account. Collected after arrival."; + var booked=bookings.get(p.getUniqueId());String detail=quote+"\nTravel opens at :00, :20 and :40 for five minutes."+(booked==null?"":"\nYour passage is already booked."); + if(BedrockForms.isBedrock(p)){List choices=new ArrayList<>();for(var route:GuildRoutes.ALL){boolean allowed=quotedDestinations(data.getAsJsonObject("guildQuote")).contains(route.world());choices.add(new BedrockForms.Choice((allowed?"§6":"§8")+route.name()+(allowed?(route.house().equals(house)?" · Your House":" · Imperial passage"):" · Unavailable"),allowed?detail:"Another House world",allowed?()->bookPassage(p,data,route.world()):()->travelMenu(p,data),"https://www.dunerealms.com/assets/gui/guild-world-"+route.world().replace('_','-')+(allowed?"":"-locked")+"-v1.png"));}choices.add(new BedrockForms.Choice("Cancel booking","No fare has been charged",()->{cancelBooking(p);travelMenu(p,data);}));choices.add(new BedrockForms.Choice("Your Mentat","Return to your House adviser",()->mentat(p,data)));BedrockForms.show(this,p,"Spacing Guild · Imperial passage",detail,choices);return;} + int own=Arrays.asList(IDS).indexOf(house);Screen screen=screen(p,"Spacing Guild · Imperial passage",0xE330+own); + for(int i=0;ibookPassage(p,data,route.world()));}} + button(screen,p,45,"Your Mentat","Return to your House adviser",Material.ARROW,()->mentat(p,data));screen.actions.put(46,screen.actions.get(45)); + button(screen,p,49,"Cancel booking","No fare is taken for a cancelled booking",Material.BARRIER,()->{cancelBooking(p);travelMenu(p,data);});for(int slot:new int[]{48,50})screen.actions.put(slot,screen.actions.get(49)); + if(guild!=null){button(screen,p,53,booked==null?"Book passage":"Review booked passage",detail,Material.EMERALD,()->bookPassage(p,data));screen.actions.put(52,screen.actions.get(53));} + if(MCGUIMenus.show(p,"Spacing Guild · Imperial passage","",screen.inventory,screen.actions,screen.gate))return; + p.openInventory(screen.inventory);expire(screen); + } + private void cancelBooking(Player p){boolean removed=bookings.cancel(p.getUniqueId());removed=boarding.remove(p.getUniqueId())||removed;p.sendMessage(removed?"Guild passage cancelled. No fare was charged.":"You have no pending Guild booking.");} + private static Set quotedDestinations(JsonObject quote){Set worlds=new HashSet<>();if(quote.has("destinations"))for(var value:quote.getAsJsonArray("destinations"))worlds.add(value.getAsString());else worlds.add(quote.get("destination").getAsString());return Set.copyOf(worlds);} + private void bookPassage(Player p,JsonObject shown){var booked=bookings.get(p.getUniqueId());bookPassage(p,shown,booked==null?GuildRoutes.home(selection(shown)).world():booked.world());} + private void bookPassage(Player p,JsonObject shown,String destination){ + if(boarding.contains(p.getUniqueId())){p.sendMessage("Guild boarding is already being confirmed.");return;} + var expected=permit(shown);if(expected==null){p.sendMessage("Confirm your current House key before booking passage.");select(p,shown,selection(shown));return;} + fetch(p,null,0,null,fresh->{var current=permit(fresh);if(current==null||!current.equals(expected)){p.sendMessage("Your House key changed. Review the current passage.");travelMenu(p,fresh);return;} + var q=new JsonObject();q.addProperty("action","quote");guildRequest(p,q,quote->{if(!quote.get("affordable").getAsBoolean()){p.sendMessage("Not enough available Dunemarks in your central personal bank account.");return;}var home=GuildRoutes.ALL.stream().filter(r->r.world().equals(destination)).findFirst().orElseThrow();int fare=quote.get("fareMinor").getAsInt();if(!quotedDestinations(quote).contains(destination)){p.sendMessage("Your House destination changed. Reopen the menu.");return;}var booked=bookings.book(p.getUniqueId(),current,home.world(),fare,Instant.now().getEpochSecond(),quotedDestinations(quote));p.closeInventory();p.sendMessage(Component.text("Passage booked to "+home.name()+". Fare "+String.format(java.util.Locale.ROOT,"%.2f",booked.fare()/100.0)+" DM is reserved at boarding and collected after arrival.",NamedTextColor.GOLD));}); + }); + } + private void board(GuildBookings.Booking booking){ + Player p=Bukkit.getPlayer(booking.player());if(p==null||!p.isOnline()||!lobby(p)||!boarding.add(booking.player()))return; + Bukkit.getScheduler().runTaskAsynchronously(this,()->{JsonObject ticket=null;String failure=null;try{var fresh=bridge.request(booking.player(),null,0,null);var current=permit(fresh);if(current==null||!booking.matches(current,booking.fare(),Instant.now().getEpochSecond())||!bridge.worldOnline(booking.world()))throw new IllegalStateException("Your key, boarding window or destination changed. Please rebook.");var q=new JsonObject();q.addProperty("action","board");q.addProperty("requestId",booking.requestId().toString());q.addProperty("keyId",current.keyId().toString());q.addProperty("version",current.version());q.addProperty("fareMinor",booking.fare());q.addProperty("destination",booking.world());ticket=bridge.guild(booking.player(),q);}catch(Exception e){failure=e.getMessage();}var result=ticket;String message=failure;if(!isEnabled())return;Bukkit.getScheduler().runTask(this,()->{if(!boarding.remove(booking.player())||!p.isOnline()||!lobby(p))return;try{if(result==null){p.sendMessage(message==null?"Passage was not confirmed. Any unused reservation expires automatically.":message);return;}p.closeInventory();bridge.dispatchGuild(p,result);}catch(Exception unavailable){p.sendMessage("The transfer was not sent. Your unused fare reservation will expire automatically.");}});}); + } + private void fetch(Player p,String house,int version,UUID requestId,Consumer callback){ + UUID owner=p.getUniqueId();if(requests.containsKey(owner)){p.sendMessage("The House register is processing your request.");return;} + UUID operation=UUID.randomUUID(),worldId=p.getWorld().getUID();requests.put(owner,operation);p.closeInventory();p.sendMessage(Component.text("Jarvis executing matrix",NamedTextColor.GOLD)); + Bukkit.getScheduler().runTaskAsynchronously(this,()->{ + JsonObject result=null;String error=null; + try{result=bridge.request(owner,house,version,requestId);}catch(Exception unavailable){error=unavailable instanceof java.io.IOException?unavailable.getMessage():"The House register is unavailable. Please retry.";} + JsonObject received=result;String failure=error;if(!isEnabled())return; + Bukkit.getScheduler().runTask(this,()->{if(!operation.equals(requests.get(owner)))return;requests.remove(owner);if(!p.isOnline()||!worldId.equals(p.getWorld().getUID()))return; + if(received==null){p.sendMessage(Component.text(failure,NamedTextColor.RED));return;} + records.put(owner,received);updateSidebar(p,received);callback.accept(received); + }); + }); + } + private void refreshSidebar(Player p){ + UUID owner=p.getUniqueId();if(requests.containsKey(owner))return;UUID operation=UUID.randomUUID();requests.put(owner,operation); + Bukkit.getScheduler().runTaskAsynchronously(this,()->{JsonObject result=null;try{result=bridge.request(owner,null,0,null);}catch(Exception unavailable){}JsonObject received=result;if(!isEnabled())return; + Bukkit.getScheduler().runTask(this,()->{if(!operation.equals(requests.get(owner)))return;requests.remove(owner);if(!p.isOnline())return; + if(received!=null){records.put(owner,received);updateSidebar(p,received);}else{records.remove(owner);sidebar.update(p,null,null);nameplates.update(p,null,null,null);} + }); + }); + } + private void updateSidebar(Player p,JsonObject data){String house=selection(data),label=house==null?null:houseName(data,house);sidebar.update(p,data,label);nameplates.update(p,data,house,label);} + private void toggleSidebar(Player p){sidebar.toggle(p);p.sendMessage(Component.text(sidebar.enabled(p)?"Personal scoreboard enabled.":"Personal scoreboard hidden.",NamedTextColor.GOLD));if(sidebar.enabled(p)){JsonObject data=records.get(p.getUniqueId());if(data!=null)updateSidebar(p,data);refreshSidebar(p);}} + @EventHandler public void scoreboardCommand(PlayerCommandPreprocessEvent e){String command=e.getMessage().trim();if(command.equalsIgnoreCase("/scoreboard")){e.setCancelled(true);toggleSidebar(e.getPlayer());}} + @EventHandler(priority=EventPriority.HIGHEST) public void oldNavigator(PlayerInteractEvent e){if(e.getHand()!=EquipmentSlot.HAND||e.getItem()==null||!e.getItem().hasItemMeta()||!e.getAction().isRightClick())return;var data=e.getItem().getItemMeta().getPersistentDataContainer();for(var key:data.getKeys())if(data.has(key,PersistentDataType.STRING)&&"menu_opener".equals(data.get(key,PersistentDataType.STRING))){e.setCancelled(true);organisations.console(e.getPlayer());return;}} + @EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=true) public void legacyTravel(PlayerCommandPreprocessEvent e){String[] args=e.getMessage().substring(1).trim().toLowerCase(Locale.ROOT).split("\\s+");String label=args[0].replaceFirst("^[^:]+:","");if(label.equals("balance")||label.equals("bal")||label.equals("money")){e.setCancelled(true);if(!sidebar.enabled(e.getPlayer()))sidebar.toggle(e.getPlayer());refreshSidebar(e.getPlayer());return;}if(label.equals("exchange")){e.setCancelled(true);exchange.open(e.getPlayer());return;}if(label.equals("server")||label.equals("duneess")&&args.length>1&&args[1].equals("travel")){e.setCancelled(true);openGuild(e.getPlayer(),null);}} + private void offerGuiPack(Player p){ + if(!lobby(p)){p.sendMessage("Visit Spacing Guild lobby to update your DuneRealms artwork.");return;} + guiPackLoaded.remove(p.getUniqueId()); + var pack=guiPack();p.addResourcePack(pack.id(),pack.url(),java.util.HexFormat.of().parseHex(pack.hash()),"DuneRealms menus and item artwork",true); + MCGUIMenus.offerPack(p); + ecologyArtwork.offer(p); + } + @EventHandler public void join(PlayerJoinEvent e){Bukkit.getScheduler().runTaskLater(this,()->{ + Player p=e.getPlayer();if(!p.isOnline())return; + // Offer once in the play phase too: configuration-phase pack loading may finish + // before the ordinary Bukkit player status event is available. The hash reuses cache. + if(lobby(p)&&!BedrockForms.isBedrock(p)){if(!guiPackLoaded.contains(p.getUniqueId()))offerGuiPack(p);else ecologyArtwork.offer(p);} + giveCodex(p,false); + if(sidebar.enabled(p))refreshSidebar(p); + },40L);} + @EventHandler public void packStatus(PlayerResourcePackStatusEvent e){ + if(!guiPack().id().equals(e.getID()))return; + getLogger().info("GUI pack status for "+e.getPlayer().getName()+": "+e.getStatus()); + if(e.getStatus()==PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED){guiPackLoaded.add(e.getPlayer().getUniqueId());e.getPlayer().sendMessage(Component.text("DuneRealms artwork loaded. Reopen your menu.",NamedTextColor.GREEN));return;} + guiPackLoaded.remove(e.getPlayer().getUniqueId()); + } + @EventHandler public void world(PlayerChangedWorldEvent e){bookings.cancel(e.getPlayer().getUniqueId());boarding.remove(e.getPlayer().getUniqueId());sidebar.hide(e.getPlayer());records.remove(e.getPlayer().getUniqueId());if(sidebar.enabled(e.getPlayer()))refreshSidebar(e.getPlayer());} + static String selection(JsonObject data){if(!data.has("selection")||data.get("selection").isJsonNull())return null;String value=data.get("selection").getAsString();return HOUSE_IDS.contains(value)?value:null;} + private String houseName(JsonObject data,String id){for(var entry:data.getAsJsonArray("choices")){var h=entry.getAsJsonObject();if(h.get("id").getAsString().equals(id))return h.get("name").getAsString();}throw new IllegalArgumentException("Unknown House");} + private void select(Player p,JsonObject data,String picked){ + String current=selection(data),chosen=picked!=null?picked:current; + if(BedrockForms.isBedrock(p)){ + List choices=new ArrayList<>(); + for(var entry:data.getAsJsonArray("choices")){var house=entry.getAsJsonObject();String id=house.get("id").getAsString();if(!HOUSE_IDS.contains(id))continue; + choices.add(new BedrockForms.Choice(house.get("name").getAsString()+(id.equals(current)?" · Your House":""),"Review and confirm allegiance",()->confirmForm(p,data,id),"https://www.dunerealms.com/assets/seals/"+house.get("seal").getAsString())); + } + choices.add(new BedrockForms.Choice(sidebar.enabled(p)?"Hide scoreboard":"Show scoreboard","Personal briefing display",()->{toggleSidebar(p);select(p,data,picked);})); + BedrockForms.show(this,p,"Choose your House","Declare your allegiance. Review a House before confirming.",choices);return; + } + Screen screen=screen(p,"Choose your House",0xE300+(chosen==null?0:Arrays.asList(IDS).indexOf(chosen)+1)); + for(int i=0;iselect(p,data,id));} + } + button(screen,p,45,"Close","Return to the lobby",Material.ARROW,p::closeInventory); + button(screen,p,49,sidebar.enabled(p)?"Hide scoreboard":"Show scoreboard","Toggle your personal briefing",Material.LEVER,()->{toggleSidebar(p);select(p,data,chosen);}); + for(int slot:new int[]{48,50})screen.actions.put(slot,screen.actions.get(49)); + if(chosen!=null)button(screen,p,53,"Confirm "+houseName(data,chosen),"Write your confirmed House key",Material.LIME_DYE,()->confirm(p,data,chosen)); + screen.actions.put(46,screen.actions.get(45));if(chosen!=null)screen.actions.put(52,screen.actions.get(53)); + if(MCGUIMenus.show(p,"Choose your House","",screen.inventory,screen.actions,screen.gate))return; + p.openInventory(screen.inventory);expire(screen); + } + private void confirmForm(Player p,JsonObject data,String id){BedrockForms.show(this,p,"Confirm House · "+houseName(data,id),"Confirm your allegiance to "+houseName(data,id)+". This initial selection does not grant an elected office.",List.of(new BedrockForms.Choice("Confirm House","Save through J.A.R.V.I.S.",()->confirm(p,data,id)),new BedrockForms.Choice("Back","Review all five Houses",()->select(p,data,id))));} + private void confirm(Player p,JsonObject data,String id){ + if(id.equals(selection(data))&&data.has("keyId")&&!data.get("keyId").isJsonNull()){mentat(p,data);return;} + fetch(p,id,data.get("version").getAsInt(),UUID.randomUUID(),saved->{p.sendMessage(Component.text("House allegiance confirmed in J.A.R.V.I.S.",NamedTextColor.GREEN));mentat(p,saved);}); + } + private void mentat(Player p,JsonObject data){ + String house=selection(data);if(house==null){select(p,data,null);return;} + JsonObject mentor=data.getAsJsonObject("mentat");String name=mentor.get("name").getAsString();int index=Arrays.asList(IDS).indexOf(house); + if(BedrockForms.isBedrock(p)){BedrockForms.show(this,p,"Your Mentat · "+name,houseName(data,house)+"\nYour House briefing is ready.",List.of(new BedrockForms.Choice("Open Mentat Report","Open your website mission journal",()->quests.open(p),"https://www.dunerealms.com/assets/gui/mentat-"+house+"-v1.png"),new BedrockForms.Choice(sidebar.enabled(p)?"Hide scoreboard":"Show scoreboard","Personal briefing display",()->{toggleSidebar(p);mentat(p,data);}),new BedrockForms.Choice("Spacing Guild travel","Book passage to your House world",()->openGuild(p,null))));return;} + Screen screen=screen(p,"Your Mentat · "+name,0xE310+index); + var portrait=icon(p,name,houseName(data,house),"drgui_transparent",Material.PLAYER_HEAD);menuArt(portrait,"mentat_"+house);screen.inventory.setItem(13,portrait); + button(screen,p,38,"Open Mentat Report","Personal level, Reputation and active quests",Material.WRITABLE_BOOK,()->quests.open(p)); + button(screen,p,42,"Spacing Guild travel","Book passage to your House world",Material.COMPASS,()->openGuild(p,null)); + button(screen,p,45,"Your House",houseName(data,house),Material.ARROW,()->select(p,data,house)); + button(screen,p,49,sidebar.enabled(p)?"Hide scoreboard":"Show scoreboard","Toggle your personal briefing",Material.LEVER,()->{toggleSidebar(p);mentat(p,data);});for(int slot:new int[]{48,50})screen.actions.put(slot,screen.actions.get(49)); + for(int slot:new int[]{37,39})screen.actions.put(slot,screen.actions.get(38));for(int slot:new int[]{41,43})screen.actions.put(slot,screen.actions.get(42));screen.actions.put(46,screen.actions.get(45)); + if(MCGUIMenus.show(p,"Your Mentat · "+name,"",screen.inventory,screen.actions,screen.gate))return; + p.openInventory(screen.inventory);expire(screen); + } + private static void menuArt(ItemStack item,String artwork){var meta=item.getItemMeta();meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","menu_art"),PersistentDataType.STRING,artwork);item.setItemMeta(meta);} + private void report(Player p){p.closeInventory();p.sendMessage(Component.text("Open your Mentat Report →",NamedTextColor.GOLD).clickEvent(net.kyori.adventure.text.event.ClickEvent.openUrl("https://clans.dunerealms.com/#quests/quests")));} + private Screen screen(Player p,String title,int glyph){Screen s=new Screen(p);Component heading=guiPackLoaded.contains(p.getUniqueId())?Component.text(GuiArtwork.background(glyph),NamedTextColor.WHITE).font(Key.key("dunerealms:house_selector")):Component.text(title,NamedTextColor.GOLD);s.inventory=Bukkit.createInventory(s,54,heading);return s;} + private ItemStack icon(Player p,String title,String description,String model,Material fallback){ItemStack item=new ItemStack(guiPackLoaded.contains(p.getUniqueId())?Material.PAPER:fallback);var meta=item.getItemMeta();meta.displayName(Component.text(title,NamedTextColor.GOLD));meta.lore(List.of(Component.text(description,NamedTextColor.GRAY)));if(guiPackLoaded.contains(p.getUniqueId()))meta.setItemModel(new NamespacedKey("dunerealms",model));item.setItemMeta(meta);return item;} + private void button(Screen s,Player p,int slot,String title,String description,Material material,Runnable action){s.inventory.setItem(slot,icon(p,title,description,"drgui_transparent",material));s.actions.put(slot,action);} + private void expire(Screen screen){Bukkit.getScheduler().runTaskLater(this,screen.gate::expire,2400L);} + @EventHandler public void click(InventoryClickEvent event){if(!(event.getView().getTopInventory().getHolder() instanceof Screen s))return;event.setCancelled(true); + if(!(event.getWhoClicked() instanceof Player p)||!p.getUniqueId().equals(s.owner)||event.getClickedInventory()!=s.inventory||event.getClick()!=ClickType.LEFT)return; + Runnable action=s.actions.get(event.getRawSlot());if(action==null||!s.gate.claim(p.getUniqueId()))return; + Bukkit.getScheduler().runTask(this,()->{if(p.isOnline()&&s.worldId.equals(p.getWorld().getUID())&&p.getOpenInventory().getTopInventory()==s.inventory)action.run();}); + } + @EventHandler public void drag(InventoryDragEvent e){if(e.getView().getTopInventory().getHolder() instanceof Screen)e.setCancelled(true);} + @EventHandler public void close(InventoryCloseEvent e){if(e.getInventory().getHolder() instanceof Screen s)s.gate.expire();} + @EventHandler public void quit(PlayerQuitEvent e){guiPackLoaded.remove(e.getPlayer().getUniqueId());bookings.cancel(e.getPlayer().getUniqueId());boarding.remove(e.getPlayer().getUniqueId());requests.remove(e.getPlayer().getUniqueId());records.remove(e.getPlayer().getUniqueId());sidebar.hide(e.getPlayer());departure.removePlayer(e.getPlayer());} + private void ensureRegistrar(){World world=Bukkit.getWorld("guild_lobby");if(world==null)return;Location at=world.getSpawnLocation().clone().add(2,0,0);at.getChunk().load(); + for(Entity entity:world.getEntities())if(entity.getPersistentDataContainer().has(registrar,PersistentDataType.BYTE))return; + Villager npc=world.spawn(at,Villager.class);npc.setAI(false);npc.setInvulnerable(true);npc.setPersistent(true);npc.setSilent(true);npc.setCollidable(false);npc.setProfession(Villager.Profession.LIBRARIAN);npc.customName(Component.text("House Registrar · Choose your House",NamedTextColor.GOLD));npc.setCustomNameVisible(true);npc.getPersistentDataContainer().set(registrar,PersistentDataType.BYTE,(byte)1); + } + @EventHandler public void npc(PlayerInteractEntityEvent e){if(!e.getRightClicked().getPersistentDataContainer().has(registrar,PersistentDataType.BYTE))return;e.setCancelled(true);if(e.getHand()!=EquipmentSlot.HAND||!lobby(e.getPlayer()))return;fetch(e.getPlayer(),null,0,null,data->{if(selection(data)!=null)mentat(e.getPlayer(),data);else select(e.getPlayer(),data,null);});} + private void tick(){ + long seconds=Instant.now().getEpochSecond(),remaining=DepartureWindow.remaining(seconds);var phase=DepartureWindow.phase(seconds);departure.setTitle("Spacing Guild · "+switch(phase){case BOARDING->"Travel open · closes in ";case LAUNCHING->"Launching · ";case WAITING->"Boarding opens in ";}+String.format(Locale.ROOT,"%02d:%02d",remaining/60,remaining%60));departure.setColor(phase==DepartureWindow.Phase.BOARDING?BarColor.GREEN:BarColor.YELLOW);departure.setProgress(DepartureWindow.progress(seconds)); + long now=Instant.now().getEpochSecond();for(var booking:bookings.due(now))board(booking); + if(((phase==DepartureWindow.Phase.BOARDING&&remaining==300)||(phase==DepartureWindow.Phase.WAITING&&(remaining==300||remaining==60||remaining==10)))&&lastDepartureNotice!=now){lastDepartureNotice=now;for(Player p:Bukkit.getOnlinePlayers())if(lobby(p))p.sendMessage(Component.text(phase==DepartureWindow.Phase.BOARDING?"Spacing Guild · travel is open for five minutes.":"Spacing Guild · boarding opens in "+(remaining>=60?remaining/60+" minute(s).":remaining+" seconds."),NamedTextColor.GOLD));} + for(World world:Bukkit.getWorlds())if(world.getName().equals("guild_lobby")){var battle=world.getEnderDragonBattle();if(battle!=null){if(battle.getBossBar()!=null){battle.getBossBar().setVisible(false);battle.getBossBar().removeAll();} + if(!detached.containsKey(world.getUID()))try{Object handle=world.getClass().getMethod("getHandle").invoke(world);detached.put(world.getUID(),DragonController.detach(handle));getLogger().info("Lobby dragon controller detached; native bossbar disabled.");}catch(ReflectiveOperationException|RuntimeException unsupported){if(dragonWarnings.add(world.getUID()))getLogger().warning("Lobby dragon controller could not be detached; native bossbar fallback active.");} + }} + for(Player p:Bukkit.getOnlinePlayers())if(lobby(p)){if(!departure.getPlayers().contains(p))departure.addPlayer(p);}else departure.removePlayer(p); + } +} diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/PlanetMaterialPolicy.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/PlanetMaterialPolicy.java index 08734af1..5a935750 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/PlanetMaterialPolicy.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/PlanetMaterialPolicy.java @@ -1,14 +1,14 @@ -package com.dunerealms.gui; - -import java.util.Locale; -import java.util.Map; - -final class PlanetMaterialPolicy { - private PlanetMaterialPolicy(){} - static String profile(String world,Map aliases){return aliases.get(world.toLowerCase(Locale.ROOT));} - static void validate(String key,String url,String hash){ - if(!key.matches("guild|arrakis|caladan|giedi_prime|kaitain|sigma_draconis_iv")|| - !url.matches("https://www\\.dunerealms\\.com/downloads/DuneRealms-Materials-"+key+"-v[1-9][0-9]*\\.zip")|| - !hash.matches("[0-9a-f]{40}"))throw new IllegalArgumentException("Invalid material pack pin"); - } -} +package com.dunerealms.gui; + +import java.util.Locale; +import java.util.Map; + +final class PlanetMaterialPolicy { + private PlanetMaterialPolicy(){} + static String profile(String world,Map aliases){return aliases.get(world.toLowerCase(Locale.ROOT));} + static void validate(String key,String url,String hash){ + if(!key.matches("guild|arrakis|caladan|giedi_prime|kaitain|sigma_draconis_iv")|| + !url.matches("https://www\\.dunerealms\\.com/downloads/DuneRealms-Materials-"+key+"-v[1-9][0-9]*\\.zip")|| + !hash.matches("[0-9a-f]{40}"))throw new IllegalArgumentException("Invalid material pack pin"); + } +} diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/PlanetTexturePacks.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/PlanetTexturePacks.java index d01b30f5..d8b8e6ec 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/PlanetTexturePacks.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/PlanetTexturePacks.java @@ -1,85 +1,85 @@ -package com.dunerealms.gui; - -import java.io.File; -import java.util.HashMap; -import java.util.HexFormat; -import java.util.Locale; -import java.util.Map; -import java.util.UUID; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -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.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerResourcePackStatusEvent; -import org.bukkit.plugin.java.JavaPlugin; - -/** One replaceable vanilla-material layer. Never clears GUI or Dune artwork packs. */ -final class PlanetTexturePacks implements Listener { - static final UUID PACK_ID=UUID.fromString("59f34b30-6a86-5e58-a813-6e776f726c64"); - private final JavaPlugin plugin; - private final Map packs=new HashMap<>(); - private final Map worlds=new HashMap<>(); - private final Map offered=new HashMap<>(); - private final boolean enabled; - record Pack(String url,String hash,String name){} - - PlanetTexturePacks(JavaPlugin plugin){ - this.plugin=plugin; - File file=new File(plugin.getDataFolder(),"planet-textures.yml"); - if(!file.exists())plugin.saveResource("planet-textures.yml",false); - var config=YamlConfiguration.loadConfiguration(file); - boolean valid=true; - try{ - var section=config.getConfigurationSection("packs"); - if(section==null)throw new IllegalArgumentException("Missing packs"); - for(String key:section.getKeys(false)){ - String url=section.getString(key+".url",""),hash=section.getString(key+".sha1",""),name=section.getString(key+".name",key); - PlanetMaterialPolicy.validate(key,url,hash); - packs.put(key,new Pack(url,hash,name)); - for(String alias:section.getStringList(key+".worlds")){ - String previous=worlds.put(alias.toLowerCase(Locale.ROOT),key); - if(previous!=null&&!previous.equals(key))throw new IllegalArgumentException("Duplicate world alias"); - } - } - // Exact per-server names can be configured without changing the planet catalogue. - var aliases=config.getConfigurationSection("worlds"); - if(aliases!=null)for(String name:aliases.getKeys(false)){ - String key=aliases.getString(name,"");if(!packs.containsKey(key))throw new IllegalArgumentException("Unknown planet alias"); - worlds.put(name.toLowerCase(Locale.ROOT),key); - } - }catch(IllegalArgumentException invalid){valid=false;plugin.getLogger().warning("Planet material packs disabled: invalid planet-textures.yml");} - enabled=valid&&config.getBoolean("enabled",false); - Bukkit.getPluginManager().registerEvents(this,plugin); - Bukkit.getScheduler().runTaskLater(plugin,()->Bukkit.getOnlinePlayers().forEach(this::offer),40L); - } - - private void offer(Player player){ - if(!player.isOnline()||BedrockForms.isBedrock(player))return; - String profile=enabled?PlanetMaterialPolicy.profile(player.getWorld().getName(),worlds):null; - String desired=profile==null?"none":profile; - if(desired.equals(offered.get(player.getUniqueId())))return; - player.removeResourcePack(PACK_ID); - if(profile!=null){ - Pack pack=packs.get(profile); - player.addResourcePack(PACK_ID,pack.url(),HexFormat.of().parseHex(pack.hash()),"DuneRealms · "+pack.name()+" materials",false); - } - offered.put(player.getUniqueId(),desired); - } - @EventHandler public void join(PlayerJoinEvent event){ - Player player=event.getPlayer(); - Bukkit.getScheduler().runTaskLater(plugin,()->offer(player),40L); - } - @EventHandler public void world(PlayerChangedWorldEvent event){offer(event.getPlayer());} - @EventHandler public void quit(PlayerQuitEvent event){offered.remove(event.getPlayer().getUniqueId());} - @EventHandler public void status(PlayerResourcePackStatusEvent event){ - if(!PACK_ID.equals(event.getID()))return; - if(event.getStatus()==PlayerResourcePackStatusEvent.Status.FAILED_DOWNLOAD||event.getStatus()==PlayerResourcePackStatusEvent.Status.FAILED_RELOAD||event.getStatus()==PlayerResourcePackStatusEvent.Status.INVALID_URL){ - offered.remove(event.getPlayer().getUniqueId()); - plugin.getLogger().warning("Planet material pack failed for "+event.getPlayer().getUniqueId()+": "+event.getStatus()); - } - } -} +package com.dunerealms.gui; + +import java.io.File; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +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.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerResourcePackStatusEvent; +import org.bukkit.plugin.java.JavaPlugin; + +/** One replaceable vanilla-material layer. Never clears GUI or Dune artwork packs. */ +final class PlanetTexturePacks implements Listener { + static final UUID PACK_ID=UUID.fromString("59f34b30-6a86-5e58-a813-6e776f726c64"); + private final JavaPlugin plugin; + private final Map packs=new HashMap<>(); + private final Map worlds=new HashMap<>(); + private final Map offered=new HashMap<>(); + private final boolean enabled; + record Pack(String url,String hash,String name){} + + PlanetTexturePacks(JavaPlugin plugin){ + this.plugin=plugin; + File file=new File(plugin.getDataFolder(),"planet-textures.yml"); + if(!file.exists())plugin.saveResource("planet-textures.yml",false); + var config=YamlConfiguration.loadConfiguration(file); + boolean valid=true; + try{ + var section=config.getConfigurationSection("packs"); + if(section==null)throw new IllegalArgumentException("Missing packs"); + for(String key:section.getKeys(false)){ + String url=section.getString(key+".url",""),hash=section.getString(key+".sha1",""),name=section.getString(key+".name",key); + PlanetMaterialPolicy.validate(key,url,hash); + packs.put(key,new Pack(url,hash,name)); + for(String alias:section.getStringList(key+".worlds")){ + String previous=worlds.put(alias.toLowerCase(Locale.ROOT),key); + if(previous!=null&&!previous.equals(key))throw new IllegalArgumentException("Duplicate world alias"); + } + } + // Exact per-server names can be configured without changing the planet catalogue. + var aliases=config.getConfigurationSection("worlds"); + if(aliases!=null)for(String name:aliases.getKeys(false)){ + String key=aliases.getString(name,"");if(!packs.containsKey(key))throw new IllegalArgumentException("Unknown planet alias"); + worlds.put(name.toLowerCase(Locale.ROOT),key); + } + }catch(IllegalArgumentException invalid){valid=false;plugin.getLogger().warning("Planet material packs disabled: invalid planet-textures.yml");} + enabled=valid&&config.getBoolean("enabled",false); + Bukkit.getPluginManager().registerEvents(this,plugin); + Bukkit.getScheduler().runTaskLater(plugin,()->Bukkit.getOnlinePlayers().forEach(this::offer),40L); + } + + private void offer(Player player){ + if(!player.isOnline()||BedrockForms.isBedrock(player))return; + String profile=enabled?PlanetMaterialPolicy.profile(player.getWorld().getName(),worlds):null; + String desired=profile==null?"none":profile; + if(desired.equals(offered.get(player.getUniqueId())))return; + player.removeResourcePack(PACK_ID); + if(profile!=null){ + Pack pack=packs.get(profile); + player.addResourcePack(PACK_ID,pack.url(),HexFormat.of().parseHex(pack.hash()),"DuneRealms · "+pack.name()+" materials",false); + } + offered.put(player.getUniqueId(),desired); + } + @EventHandler public void join(PlayerJoinEvent event){ + Player player=event.getPlayer(); + Bukkit.getScheduler().runTaskLater(plugin,()->offer(player),40L); + } + @EventHandler public void world(PlayerChangedWorldEvent event){offer(event.getPlayer());} + @EventHandler public void quit(PlayerQuitEvent event){offered.remove(event.getPlayer().getUniqueId());} + @EventHandler public void status(PlayerResourcePackStatusEvent event){ + if(!PACK_ID.equals(event.getID()))return; + if(event.getStatus()==PlayerResourcePackStatusEvent.Status.FAILED_DOWNLOAD||event.getStatus()==PlayerResourcePackStatusEvent.Status.FAILED_RELOAD||event.getStatus()==PlayerResourcePackStatusEvent.Status.INVALID_URL){ + offered.remove(event.getPlayer().getUniqueId()); + plugin.getLogger().warning("Planet material pack failed for "+event.getPlayer().getUniqueId()+": "+event.getStatus()); + } + } +} diff --git a/DuneRealmsGUI/src/main/resources/planet-textures.yml b/DuneRealmsGUI/src/main/resources/planet-textures.yml index a45b80f8..012f2992 100644 --- a/DuneRealmsGUI/src/main/resources/planet-textures.yml +++ b/DuneRealmsGUI/src/main/resources/planet-textures.yml @@ -1,38 +1,38 @@ -# Enable after publishing every pinned ZIP from planet-artwork/release-v1/. -# Java material layer only. Geyser/Bedrock requires its own converted pack. -enabled: false - -# Optional exact world-name mappings, e.g. world: arrakis -worlds: {} - -packs: - guild: - name: "Vaerkring" - url: https://www.dunerealms.com/downloads/DuneRealms-Materials-guild-v1.zip - sha1: 958b0bc07e49c33427d262a2621b1b154f9c9fa5 - worlds: ["guild_lobby"] - arrakis: - name: "Arrakduin" - url: https://www.dunerealms.com/downloads/DuneRealms-Materials-arrakis-v1.zip - sha1: c85b84125bad0e913f795b4aeb8364a7caab8d8d - worlds: ["arrakis","arrakduin"] - caladan: - name: "Kaladam" - url: https://www.dunerealms.com/downloads/DuneRealms-Materials-caladan-v1.zip - sha1: b21aafb4263c2f499540c28f382d1c8984786313 - worlds: ["caladan","kaladam"] - giedi_prime: - name: "Giedermark" - url: https://www.dunerealms.com/downloads/DuneRealms-Materials-giedi_prime-v1.zip - sha1: 5e0b691fda32ad0f8f3bc00bd477cdc5c538cdef - worlds: ["giedi_prime","giedermark"] - kaitain: - name: "Kaiterhof" - url: https://www.dunerealms.com/downloads/DuneRealms-Materials-kaitain-v1.zip - sha1: 95f77e0e32c8e9920d45b6dff0115a45b0198cb1 - worlds: ["kaitain","kaiterhof"] - sigma_draconis_iv: - name: "Sigmadraken IV" - url: https://www.dunerealms.com/downloads/DuneRealms-Materials-sigma_draconis_iv-v1.zip - sha1: 2631a5dee656d5f12f936b2e5dea665137817b84 - worlds: ["sigma_draconis_iv","sigmadraken_iv","sigmadraken iv"] +# Enable after publishing every pinned ZIP from planet-artwork/release-v1/. +# Java material layer only. Geyser/Bedrock requires its own converted pack. +enabled: false + +# Optional exact world-name mappings, e.g. world: arrakis +worlds: {} + +packs: + guild: + name: "Vaerkring" + url: https://www.dunerealms.com/downloads/DuneRealms-Materials-guild-v1.zip + sha1: 958b0bc07e49c33427d262a2621b1b154f9c9fa5 + worlds: ["guild_lobby"] + arrakis: + name: "Arrakduin" + url: https://www.dunerealms.com/downloads/DuneRealms-Materials-arrakis-v1.zip + sha1: c85b84125bad0e913f795b4aeb8364a7caab8d8d + worlds: ["arrakis","arrakduin"] + caladan: + name: "Kaladam" + url: https://www.dunerealms.com/downloads/DuneRealms-Materials-caladan-v1.zip + sha1: b21aafb4263c2f499540c28f382d1c8984786313 + worlds: ["caladan","kaladam"] + giedi_prime: + name: "Giedermark" + url: https://www.dunerealms.com/downloads/DuneRealms-Materials-giedi_prime-v1.zip + sha1: 5e0b691fda32ad0f8f3bc00bd477cdc5c538cdef + worlds: ["giedi_prime","giedermark"] + kaitain: + name: "Kaiterhof" + url: https://www.dunerealms.com/downloads/DuneRealms-Materials-kaitain-v1.zip + sha1: 95f77e0e32c8e9920d45b6dff0115a45b0198cb1 + worlds: ["kaitain","kaiterhof"] + sigma_draconis_iv: + name: "Sigmadraken IV" + url: https://www.dunerealms.com/downloads/DuneRealms-Materials-sigma_draconis_iv-v1.zip + sha1: 2631a5dee656d5f12f936b2e5dea665137817b84 + worlds: ["sigma_draconis_iv","sigmadraken_iv","sigmadraken iv"] diff --git a/DuneRealmsGUI/src/test/java/com/dunerealms/gui/PlanetMaterialPolicyTest.java b/DuneRealmsGUI/src/test/java/com/dunerealms/gui/PlanetMaterialPolicyTest.java index 20ba82eb..d0aa20b6 100644 --- a/DuneRealmsGUI/src/test/java/com/dunerealms/gui/PlanetMaterialPolicyTest.java +++ b/DuneRealmsGUI/src/test/java/com/dunerealms/gui/PlanetMaterialPolicyTest.java @@ -1,25 +1,25 @@ -package com.dunerealms.gui; -import java.util.Map; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -class PlanetMaterialPolicyTest { - @Test void exactWorldAliasesDoNotLeakPlanetTexturesIntoNetherOrUnknownWorlds(){ - var aliases=Map.of("arrakduin","arrakis","guild_lobby","guild","world","caladan"); - assertEquals("arrakis",PlanetMaterialPolicy.profile("Arrakduin",aliases)); - assertEquals("guild",PlanetMaterialPolicy.profile("guild_lobby",aliases)); - assertEquals("caladan",PlanetMaterialPolicy.profile("world",aliases)); - assertNull(PlanetMaterialPolicy.profile("Arrakduin_nether",aliases)); - assertNull(PlanetMaterialPolicy.profile("world_the_end",aliases)); - assertNull(PlanetMaterialPolicy.profile("somewhere_else",aliases)); - } - @Test void onlyMatchingImmutableHostedPacksAndRealSha1PinsAreAccepted(){ - String url="https://www.dunerealms.com/downloads/DuneRealms-Materials-arrakis-v1.zip",hash="0123456789abcdef0123456789abcdef01234567"; - assertDoesNotThrow(()->PlanetMaterialPolicy.validate("arrakis",url,hash)); - assertThrows(IllegalArgumentException.class,()->PlanetMaterialPolicy.validate("caladan",url,hash)); - assertThrows(IllegalArgumentException.class,()->PlanetMaterialPolicy.validate("arrakis",url.replace("https:","http:"),hash)); - assertThrows(IllegalArgumentException.class,()->PlanetMaterialPolicy.validate("arrakis",url.replace("www.dunerealms.com","evil.example"),hash)); - assertThrows(IllegalArgumentException.class,()->PlanetMaterialPolicy.validate("arrakis",url+"?changed=true",hash)); - assertThrows(IllegalArgumentException.class,()->PlanetMaterialPolicy.validate("arrakis",url,"not-a-sha1")); - } -} +package com.dunerealms.gui; +import java.util.Map; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class PlanetMaterialPolicyTest { + @Test void exactWorldAliasesDoNotLeakPlanetTexturesIntoNetherOrUnknownWorlds(){ + var aliases=Map.of("arrakduin","arrakis","guild_lobby","guild","world","caladan"); + assertEquals("arrakis",PlanetMaterialPolicy.profile("Arrakduin",aliases)); + assertEquals("guild",PlanetMaterialPolicy.profile("guild_lobby",aliases)); + assertEquals("caladan",PlanetMaterialPolicy.profile("world",aliases)); + assertNull(PlanetMaterialPolicy.profile("Arrakduin_nether",aliases)); + assertNull(PlanetMaterialPolicy.profile("world_the_end",aliases)); + assertNull(PlanetMaterialPolicy.profile("somewhere_else",aliases)); + } + @Test void onlyMatchingImmutableHostedPacksAndRealSha1PinsAreAccepted(){ + String url="https://www.dunerealms.com/downloads/DuneRealms-Materials-arrakis-v1.zip",hash="0123456789abcdef0123456789abcdef01234567"; + assertDoesNotThrow(()->PlanetMaterialPolicy.validate("arrakis",url,hash)); + assertThrows(IllegalArgumentException.class,()->PlanetMaterialPolicy.validate("caladan",url,hash)); + assertThrows(IllegalArgumentException.class,()->PlanetMaterialPolicy.validate("arrakis",url.replace("https:","http:"),hash)); + assertThrows(IllegalArgumentException.class,()->PlanetMaterialPolicy.validate("arrakis",url.replace("www.dunerealms.com","evil.example"),hash)); + assertThrows(IllegalArgumentException.class,()->PlanetMaterialPolicy.validate("arrakis",url+"?changed=true",hash)); + assertThrows(IllegalArgumentException.class,()->PlanetMaterialPolicy.validate("arrakis",url,"not-a-sha1")); + } +} diff --git a/tools/build-planet-texture-packs.mjs b/tools/build-planet-texture-packs.mjs index 80497d1a..d19b4bea 100644 --- a/tools/build-planet-texture-packs.mjs +++ b/tools/build-planet-texture-packs.mjs @@ -1,74 +1,74 @@ -/** Deterministic vanilla-material layers; no GUI, models, entities or Dune namespace. */ -import fs from 'node:fs'; -import path from 'node:path'; -import {fileURLToPath} from 'node:url'; -import {createHash} from 'node:crypto'; -import {deflateRawSync} from 'node:zlib'; - -const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); -const art=path.join(root,'DuneRealmsGUI/planet-artwork'); -const source=path.join(art,'pixel-perfection-ce'); -export const profiles=JSON.parse(fs.readFileSync(path.join(art,'profiles.json'),'utf8')); -const prefix='assets/minecraft/textures/'; -// The pinned Network Artwork v1 uses these vanilla carrier faces for spice. -export const protectedTextures=new Set(['dried_kelp_bottom','dried_kelp_side','dried_kelp_top']); -const table=Array.from({length:256},(_,n)=>{for(let i=0;i<8;i++)n=(n&1)?0xedb88320^(n>>>1):n>>>1;return n>>>0;}); -const crc32=bytes=>{let n=0xffffffff;for(const b of bytes)n=table[(n^b)&255]^(n>>>8);return (n^0xffffffff)>>>0;}; -const digest=(algorithm,bytes)=>createHash(algorithm).update(bytes).digest('hex'); - -export function zip(entries){ - const locals=[],directory=[];let offset=0; - for(const [name,data] of [...entries].sort(([a],[b])=>ab?1:0)){ - if(!/^[a-zA-Z0-9_./-]+$/.test(name)||name.startsWith('/')||name.split('/').includes('..'))throw Error('Unsafe ZIP path'); - const key=Buffer.from(name),body=deflateRawSync(data,{level:9}),crc=crc32(data); - const local=Buffer.alloc(30);local.writeUInt32LE(0x04034b50);local.writeUInt16LE(20,4);local.writeUInt16LE(8,8);local.writeUInt16LE(0x5d77,12);local.writeUInt32LE(crc,14);local.writeUInt32LE(body.length,18);local.writeUInt32LE(data.length,22);local.writeUInt16LE(key.length,26); - locals.push(local,key,body); - const central=Buffer.alloc(46);central.writeUInt32LE(0x02014b50);central.writeUInt16LE(20,4);central.writeUInt16LE(20,6);central.writeUInt16LE(8,10);central.writeUInt16LE(0x5d77,14);central.writeUInt32LE(crc,16);central.writeUInt32LE(body.length,20);central.writeUInt32LE(data.length,24);central.writeUInt16LE(key.length,28);central.writeUInt32LE(offset,42);directory.push(central,key); - offset+=local.length+key.length+body.length; - } - const central=Buffer.concat(directory),end=Buffer.alloc(22);end.writeUInt32LE(0x06054b50);end.writeUInt16LE(entries.size,8);end.writeUInt16LE(entries.size,10);end.writeUInt32LE(central.length,12);end.writeUInt32LE(offset,16); - return Buffer.concat([...locals,central,end]); -} - -export function textureEntries(planet){ - const profile=profiles[planet];if(!profile)throw Error('Unknown planet'); - const entries=new Map(); - for(const kind of ['block','item'])for(const name of fs.readdirSync(path.join(source,kind)).sort()){ - if(kind==='block'&&protectedTextures.has(name.replace(/\.png(?:\.mcmeta)?$/,'')))continue; - if(!/^[a-z0-9_-]+\.png(?:\.mcmeta)?$/.test(name))throw Error('Unexpected upstream file: '+name); - const bytes=fs.readFileSync(path.join(source,kind,name)); - if(name.endsWith('.mcmeta')){JSON.parse(bytes);if(!fs.existsSync(path.join(source,kind,name.slice(0,-7))))continue;} - else if(bytes.subarray(0,8).toString('hex')!=='89504e470d0a1a0a')throw Error('Invalid PNG'); - entries.set(prefix+kind+'/'+name,bytes); - } - for(const [target,original] of Object.entries(profile.blocks)){ - if(protectedTextures.has(target))throw Error('Cannot replace a Dune carrier texture'); - const key=prefix+'block/'+target+'.png',src=path.join(source,'block',original+'.png'); - entries.set(key,fs.readFileSync(src));entries.delete(key+'.mcmeta'); - if(fs.existsSync(src+'.mcmeta'))entries.set(key+'.mcmeta',fs.readFileSync(src+'.mcmeta')); - } - entries.set('pack.mcmeta',Buffer.from(JSON.stringify({pack:{pack_format:64,supported_formats:[64,97],min_format:64,max_format:97,description:'DuneRealms '+profile.name+' · '+profile.feel}}))); - entries.set('LICENSE-Pixel-Perfection-CE.md',fs.readFileSync(path.join(source,'LICENSE.md'))); - entries.set('CREDITS.txt',Buffer.from('Pixel Perfection CE by XSSheep and community contributors (Athemis, StonePendant, freejusticehere, Stingraych, Nova_Wostra, lazerl0rd).\nhttps://github.com/Athemis/PixelPerfectionCE\nSource commit: 28e38cab7c1f03f86364ef704f705bebcc13cb3d\nTextures and DuneRealms material remappings: CC-BY-SA-4.0. https://creativecommons.org/licenses/by-sa/4.0/\nDuneRealms changes: block/item-only extraction, modern pack metadata, named material remappings; original pixels preserved. No endorsement implied.\n')); - return entries; -} - -export function build(output){ - fs.mkdirSync(output,{recursive:true});const manifest={version:1,sourceCommit:'28e38cab7c1f03f86364ef704f705bebcc13cb3d',license:'CC-BY-SA-4.0',packId:'59f34b30-6a86-5e58-a813-6e776f726c64',packs:{}}; - for(const [planet,profile] of Object.entries(profiles)){ - const entries=textureEntries(planet),bytes=zip(entries),filename=`DuneRealms-Materials-${planet}-v1.zip`; - fs.writeFileSync(path.join(output,filename),bytes); - manifest.packs[planet]={name:profile.name,filename,url:'https://www.dunerealms.com/downloads/'+filename,sha1:digest('sha1',bytes),sha256:digest('sha256',bytes),bytes:bytes.length,entries:entries.size,aliases:profile.aliases}; - } - fs.writeFileSync(path.join(output,'manifest.json'),JSON.stringify(manifest,null,2)+'\n'); - const yaml=['# Enable after publishing every pinned ZIP from planet-artwork/release-v1/.', - '# Java material layer only. Geyser/Bedrock requires its own converted pack.', - 'enabled: false','', '# Optional exact world-name mappings, e.g. world: arrakis','worlds: {}','','packs:']; - for(const [planet,p] of Object.entries(manifest.packs))yaml.push(` ${planet}:`,` name: ${JSON.stringify(p.name)}`,` url: ${p.url}`,` sha1: ${p.sha1}`,` worlds: ${JSON.stringify(p.aliases)}`); - fs.writeFileSync(path.join(output,'planet-textures.yml'),yaml.join('\n')+'\n'); - return manifest; -} -if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){ - const output=path.resolve(process.argv[2]||path.join(art,'release-v1')); - console.log(JSON.stringify(build(output),null,2)); -} +/** Deterministic vanilla-material layers; no GUI, models, entities or Dune namespace. */ +import fs from 'node:fs'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {createHash} from 'node:crypto'; +import {deflateRawSync} from 'node:zlib'; + +const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); +const art=path.join(root,'DuneRealmsGUI/planet-artwork'); +const source=path.join(art,'pixel-perfection-ce'); +export const profiles=JSON.parse(fs.readFileSync(path.join(art,'profiles.json'),'utf8')); +const prefix='assets/minecraft/textures/'; +// The pinned Network Artwork v1 uses these vanilla carrier faces for spice. +export const protectedTextures=new Set(['dried_kelp_bottom','dried_kelp_side','dried_kelp_top']); +const table=Array.from({length:256},(_,n)=>{for(let i=0;i<8;i++)n=(n&1)?0xedb88320^(n>>>1):n>>>1;return n>>>0;}); +const crc32=bytes=>{let n=0xffffffff;for(const b of bytes)n=table[(n^b)&255]^(n>>>8);return (n^0xffffffff)>>>0;}; +const digest=(algorithm,bytes)=>createHash(algorithm).update(bytes).digest('hex'); + +export function zip(entries){ + const locals=[],directory=[];let offset=0; + for(const [name,data] of [...entries].sort(([a],[b])=>ab?1:0)){ + if(!/^[a-zA-Z0-9_./-]+$/.test(name)||name.startsWith('/')||name.split('/').includes('..'))throw Error('Unsafe ZIP path'); + const key=Buffer.from(name),body=deflateRawSync(data,{level:9}),crc=crc32(data); + const local=Buffer.alloc(30);local.writeUInt32LE(0x04034b50);local.writeUInt16LE(20,4);local.writeUInt16LE(8,8);local.writeUInt16LE(0x5d77,12);local.writeUInt32LE(crc,14);local.writeUInt32LE(body.length,18);local.writeUInt32LE(data.length,22);local.writeUInt16LE(key.length,26); + locals.push(local,key,body); + const central=Buffer.alloc(46);central.writeUInt32LE(0x02014b50);central.writeUInt16LE(20,4);central.writeUInt16LE(20,6);central.writeUInt16LE(8,10);central.writeUInt16LE(0x5d77,14);central.writeUInt32LE(crc,16);central.writeUInt32LE(body.length,20);central.writeUInt32LE(data.length,24);central.writeUInt16LE(key.length,28);central.writeUInt32LE(offset,42);directory.push(central,key); + offset+=local.length+key.length+body.length; + } + const central=Buffer.concat(directory),end=Buffer.alloc(22);end.writeUInt32LE(0x06054b50);end.writeUInt16LE(entries.size,8);end.writeUInt16LE(entries.size,10);end.writeUInt32LE(central.length,12);end.writeUInt32LE(offset,16); + return Buffer.concat([...locals,central,end]); +} + +export function textureEntries(planet){ + const profile=profiles[planet];if(!profile)throw Error('Unknown planet'); + const entries=new Map(); + for(const kind of ['block','item'])for(const name of fs.readdirSync(path.join(source,kind)).sort()){ + if(kind==='block'&&protectedTextures.has(name.replace(/\.png(?:\.mcmeta)?$/,'')))continue; + if(!/^[a-z0-9_-]+\.png(?:\.mcmeta)?$/.test(name))throw Error('Unexpected upstream file: '+name); + const bytes=fs.readFileSync(path.join(source,kind,name)); + if(name.endsWith('.mcmeta')){JSON.parse(bytes);if(!fs.existsSync(path.join(source,kind,name.slice(0,-7))))continue;} + else if(bytes.subarray(0,8).toString('hex')!=='89504e470d0a1a0a')throw Error('Invalid PNG'); + entries.set(prefix+kind+'/'+name,bytes); + } + for(const [target,original] of Object.entries(profile.blocks)){ + if(protectedTextures.has(target))throw Error('Cannot replace a Dune carrier texture'); + const key=prefix+'block/'+target+'.png',src=path.join(source,'block',original+'.png'); + entries.set(key,fs.readFileSync(src));entries.delete(key+'.mcmeta'); + if(fs.existsSync(src+'.mcmeta'))entries.set(key+'.mcmeta',fs.readFileSync(src+'.mcmeta')); + } + entries.set('pack.mcmeta',Buffer.from(JSON.stringify({pack:{pack_format:64,supported_formats:[64,97],min_format:64,max_format:97,description:'DuneRealms '+profile.name+' · '+profile.feel}}))); + entries.set('LICENSE-Pixel-Perfection-CE.md',fs.readFileSync(path.join(source,'LICENSE.md'))); + entries.set('CREDITS.txt',Buffer.from('Pixel Perfection CE by XSSheep and community contributors (Athemis, StonePendant, freejusticehere, Stingraych, Nova_Wostra, lazerl0rd).\nhttps://github.com/Athemis/PixelPerfectionCE\nSource commit: 28e38cab7c1f03f86364ef704f705bebcc13cb3d\nTextures and DuneRealms material remappings: CC-BY-SA-4.0. https://creativecommons.org/licenses/by-sa/4.0/\nDuneRealms changes: block/item-only extraction, modern pack metadata, named material remappings; original pixels preserved. No endorsement implied.\n')); + return entries; +} + +export function build(output){ + fs.mkdirSync(output,{recursive:true});const manifest={version:1,sourceCommit:'28e38cab7c1f03f86364ef704f705bebcc13cb3d',license:'CC-BY-SA-4.0',packId:'59f34b30-6a86-5e58-a813-6e776f726c64',packs:{}}; + for(const [planet,profile] of Object.entries(profiles)){ + const entries=textureEntries(planet),bytes=zip(entries),filename=`DuneRealms-Materials-${planet}-v1.zip`; + fs.writeFileSync(path.join(output,filename),bytes); + manifest.packs[planet]={name:profile.name,filename,url:'https://www.dunerealms.com/downloads/'+filename,sha1:digest('sha1',bytes),sha256:digest('sha256',bytes),bytes:bytes.length,entries:entries.size,aliases:profile.aliases}; + } + fs.writeFileSync(path.join(output,'manifest.json'),JSON.stringify(manifest,null,2)+'\n'); + const yaml=['# Enable after publishing every pinned ZIP from planet-artwork/release-v1/.', + '# Java material layer only. Geyser/Bedrock requires its own converted pack.', + 'enabled: false','', '# Optional exact world-name mappings, e.g. world: arrakis','worlds: {}','','packs:']; + for(const [planet,p] of Object.entries(manifest.packs))yaml.push(` ${planet}:`,` name: ${JSON.stringify(p.name)}`,` url: ${p.url}`,` sha1: ${p.sha1}`,` worlds: ${JSON.stringify(p.aliases)}`); + fs.writeFileSync(path.join(output,'planet-textures.yml'),yaml.join('\n')+'\n'); + return manifest; +} +if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){ + const output=path.resolve(process.argv[2]||path.join(art,'release-v1')); + console.log(JSON.stringify(build(output),null,2)); +} diff --git a/tools/build-planet-texture-packs.test.mjs b/tools/build-planet-texture-packs.test.mjs index d0bab0db..f4503c23 100644 --- a/tools/build-planet-texture-packs.test.mjs +++ b/tools/build-planet-texture-packs.test.mjs @@ -1,50 +1,50 @@ -import {test} from 'node:test'; -import assert from 'node:assert/strict'; -import {inflateRawSync,crc32} from 'node:zlib'; -import {createHash} from 'node:crypto'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import {build,profiles,textureEntries,protectedTextures} from './build-planet-texture-packs.mjs'; - -function readZip(bytes){ - const result=new Map();let offset=0; - while(bytes.readUInt32LE(offset)===0x04034b50){ - const length=bytes.readUInt32LE(offset+18),raw=bytes.readUInt32LE(offset+22),nameLength=bytes.readUInt16LE(offset+26),extra=bytes.readUInt16LE(offset+28); - const name=bytes.subarray(offset+30,offset+30+nameLength).toString(),start=offset+30+nameLength+extra; - assert.equal(result.has(name),false,'Duplicate archive entry'); - const data=inflateRawSync(bytes.subarray(start,start+length));assert.equal(data.length,raw);assert.equal(crc32(data),bytes.readUInt32LE(offset+14));result.set(name,data);offset=start+length; - } - assert.equal(bytes.readUInt32LE(offset),0x02014b50); - assert.equal(bytes.readUInt32LE(bytes.length-22),0x06054b50); - assert.equal(bytes.readUInt16LE(bytes.length-12),result.size); - return result; -} -test('each planet has distinct stone, readable ordinary items, and no custom-art overrides',()=>{ - const stones=[]; - for(const key of Object.keys(profiles)){ - const entries=textureEntries(key); - for(const name of entries.keys())if(name.startsWith('assets/'))assert.match(name,/^assets\/minecraft\/textures\/(block|item)\/[a-z0-9_.-]+$/); - assert(entries.has('assets/minecraft/textures/item/diamond_sword.png')); - for(const name of protectedTextures)assert.equal(entries.has('assets/minecraft/textures/block/'+name+'.png'),false,'Dune spice carrier must remain unchanged'); - assert(entries.has('LICENSE-Pixel-Perfection-CE.md')); - assert.match(entries.get('CREDITS.txt').toString(),/28e38cab7c1f03f86364ef704f705bebcc13cb3d/); - if(key!=='guild')stones.push(createHash('sha256').update(entries.get('assets/minecraft/textures/block/stone.png')).digest('hex')); - for(const name of entries.keys())if(name.endsWith('.mcmeta')&&name!=='pack.mcmeta')assert(entries.has(name.slice(0,-7))); - } - assert.equal(new Set(stones).size,5,'All five planets must have visibly distinct stone textures'); -}); -test('release archives round-trip, rebuild identically, and match client download pins',()=>{ - const dir=fs.mkdtempSync(path.join(os.tmpdir(),'dune-materials-')); - try{ - const a=build(path.join(dir,'a')),b=build(path.join(dir,'b'));assert.deepEqual(a,b); - for(const p of Object.values(a.packs)){ - const bytes=fs.readFileSync(path.join(dir,'a',p.filename)),entries=readZip(bytes); - assert.equal(entries.size,p.entries);assert.equal(createHash('sha1').update(bytes).digest('hex'),p.sha1); - assert.equal(createHash('sha256').update(bytes).digest('hex'),p.sha256); - assert.deepEqual(bytes,fs.readFileSync(path.join(dir,'b',p.filename))); - const meta=JSON.parse(entries.get('pack.mcmeta'));assert.equal(meta.pack.pack_format,64);assert.equal(meta.pack.max_format,97); - assert(fs.readFileSync(path.join(dir,'a','planet-textures.yml'),'utf8').includes(p.sha1)); - } - }finally{fs.rmSync(dir,{recursive:true,force:true});} -}); +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {inflateRawSync,crc32} from 'node:zlib'; +import {createHash} from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {build,profiles,textureEntries,protectedTextures} from './build-planet-texture-packs.mjs'; + +function readZip(bytes){ + const result=new Map();let offset=0; + while(bytes.readUInt32LE(offset)===0x04034b50){ + const length=bytes.readUInt32LE(offset+18),raw=bytes.readUInt32LE(offset+22),nameLength=bytes.readUInt16LE(offset+26),extra=bytes.readUInt16LE(offset+28); + const name=bytes.subarray(offset+30,offset+30+nameLength).toString(),start=offset+30+nameLength+extra; + assert.equal(result.has(name),false,'Duplicate archive entry'); + const data=inflateRawSync(bytes.subarray(start,start+length));assert.equal(data.length,raw);assert.equal(crc32(data),bytes.readUInt32LE(offset+14));result.set(name,data);offset=start+length; + } + assert.equal(bytes.readUInt32LE(offset),0x02014b50); + assert.equal(bytes.readUInt32LE(bytes.length-22),0x06054b50); + assert.equal(bytes.readUInt16LE(bytes.length-12),result.size); + return result; +} +test('each planet has distinct stone, readable ordinary items, and no custom-art overrides',()=>{ + const stones=[]; + for(const key of Object.keys(profiles)){ + const entries=textureEntries(key); + for(const name of entries.keys())if(name.startsWith('assets/'))assert.match(name,/^assets\/minecraft\/textures\/(block|item)\/[a-z0-9_.-]+$/); + assert(entries.has('assets/minecraft/textures/item/diamond_sword.png')); + for(const name of protectedTextures)assert.equal(entries.has('assets/minecraft/textures/block/'+name+'.png'),false,'Dune spice carrier must remain unchanged'); + assert(entries.has('LICENSE-Pixel-Perfection-CE.md')); + assert.match(entries.get('CREDITS.txt').toString(),/28e38cab7c1f03f86364ef704f705bebcc13cb3d/); + if(key!=='guild')stones.push(createHash('sha256').update(entries.get('assets/minecraft/textures/block/stone.png')).digest('hex')); + for(const name of entries.keys())if(name.endsWith('.mcmeta')&&name!=='pack.mcmeta')assert(entries.has(name.slice(0,-7))); + } + assert.equal(new Set(stones).size,5,'All five planets must have visibly distinct stone textures'); +}); +test('release archives round-trip, rebuild identically, and match client download pins',()=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'dune-materials-')); + try{ + const a=build(path.join(dir,'a')),b=build(path.join(dir,'b'));assert.deepEqual(a,b); + for(const p of Object.values(a.packs)){ + const bytes=fs.readFileSync(path.join(dir,'a',p.filename)),entries=readZip(bytes); + assert.equal(entries.size,p.entries);assert.equal(createHash('sha1').update(bytes).digest('hex'),p.sha1); + assert.equal(createHash('sha256').update(bytes).digest('hex'),p.sha256); + assert.deepEqual(bytes,fs.readFileSync(path.join(dir,'b',p.filename))); + const meta=JSON.parse(entries.get('pack.mcmeta'));assert.equal(meta.pack.pack_format,64);assert.equal(meta.pack.max_format,97); + assert(fs.readFileSync(path.join(dir,'a','planet-textures.yml'),'utf8').includes(p.sha1)); + } + }finally{fs.rmSync(dir,{recursive:true,force:true});} +});