Integrate Wild Update quests and Citizens contacts

This commit is contained in:
unimatrixgit 2026-12-03 21:42:17 +01:00
commit f46b26d956
38 changed files with 919 additions and 81 deletions

View file

@ -93,12 +93,8 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec
}
private void npc(String role,String name,int x,int y,int z,Villager.Profession profession) {
for(LivingEntity entity:lobby.getEntitiesByClass(LivingEntity.class)) if(role.equals(entity.getPersistentDataContainer().get(roleKey,PersistentDataType.STRING))) return;
lobby.spawn(new Location(lobby,x+.5,y,z+.5,180,0),Villager.class,v->{
v.setCustomName(ChatColor.GOLD+name); v.setCustomNameVisible(true); v.setAI(false); v.setSilent(true);
v.setInvulnerable(true); v.setPersistent(true); v.setRemoveWhenFarAway(false); v.setProfession(profession);
v.setVillagerType(role.equals("water")||role.equals("spice")?Villager.Type.SWAMP:Villager.Type.DESERT);
v.getPersistentDataContainer().set(roleKey,PersistentDataType.STRING,role); v.setRecipes(List.of());
});
if(!com.dunerealms.npc.CitizensBridge.ready()||com.dunerealms.npc.CitizensBridge.exists(this,lobby,roleKey,role))return;
com.dunerealms.npc.CitizensBridge.spawnContact(this,new Location(lobby,x+.5,y,z+.5,180,0),ChatColor.GOLD+name,roleKey,role,true);
}
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) {
if(command.getName().equals("lobby")) {

View file

@ -3,7 +3,7 @@ version: 1.1.0
main: com.example.dunelobby.DuneLobby
api-version: '1.21.8'
load: POSTWORLD
softdepend: [Citizens, Citizens, floodgate, ViaVersion, ImageFrame, DuneEss, DuneCore]
softdepend: [Citizens, floodgate, ViaVersion, ImageFrame, DuneEss, DuneCore]
commands:
lobby:
description: Return to the Vaerkring lobby

View file

@ -395,7 +395,10 @@ final class JarvisBackend implements Backend, Listener {
if (unavailable!=null && unavailable.isBlank()) unavailable="Passage unavailable";
String name=offer!=null&&!text(offer,"name").isBlank()?text(offer,"name"):route.getValue();
long fare=offer!=null&&offer.has("fareMinor")?offer.get("fareMinor").getAsLong():quote.get("fareMinor").getAsLong();
worlds.add(new World(id, name, unavailable == null ? "Imperial Guild passage" : unavailable,
String tagline = unavailable != null ? unavailable
: offer != null && offer.has("bountyMinor") ? "Unsanctioned arrival: " + Ui.dm(offer.get("bountyMinor").getAsLong()) + " bounty" + (yes(offer,"reduced") ? " (clan/company discount)" : "")
: offer != null && yes(offer,"free") ? "Free passage" : "Imperial Guild passage";
worlds.add(new World(id, name, tagline,
Material.COMPASS, -1, unavailable == null, fare, key, version));
}
return List.copyOf(worlds);

View file

@ -34,7 +34,7 @@ final class TravelMenu extends Menu {
var w = worlds.get(i);
String fare = w.fareMinor() > 0 ? "<gray>Fare: <gold>" + Ui.dm(w.fareMinor()) : w.fareMinor() == 0 ? "<green>Free passage" : "";
var icon = Ui.item(w.up() ? w.icon() : Material.GRAY_DYE, (w.up() ? "<gold><b>" : "<gray>") + w.name(),
"<gray>" + w.tagline(), w.online() < 0 ? "" : "<gray>Players: <white>" + w.online(), w.up() ? fare : "", "",
(w.tagline().startsWith("Unsanctioned") ? "<red>" : "<gray>") + w.tagline(), w.online() < 0 ? "" : "<gray>Players: <white>" + w.online(), w.up() ? fare : "", "",
w.up() ? "<yellow>Click to travel" : "");
if (w.up()) put(STARS[i], icon, t -> { end(); book(w); });
else put(STARS[i], icon);

View file

@ -93,12 +93,8 @@ public final class DuneNPC extends JavaPlugin implements Listener, CommandExecut
}
}
private void spawnNavigator(Location location) {
location.getWorld().spawn(location, Villager.class, villager -> {
villager.setCustomName(ChatColor.LIGHT_PURPLE + "Vaerkring Navigator");
villager.setCustomNameVisible(true); villager.setProfession(Villager.Profession.CLERIC);
villager.setAI(false); villager.setInvulnerable(true); villager.setSilent(true); villager.setPersistent(true);
villager.getPersistentDataContainer().set(guildKey, PersistentDataType.BYTE, (byte) 1);
});
if (!com.dunerealms.npc.CitizensBridge.ready() || com.dunerealms.npc.CitizensBridge.exists(this, location.getWorld(), guildKey, "1")) return;
com.dunerealms.npc.CitizensBridge.spawnContact(this, location, ChatColor.LIGHT_PURPLE + "Vaerkring Navigator", guildKey, "1", true);
}
@EventHandler public void navigator(PlayerInteractEntityEvent event) {
if (!event.getRightClicked().getPersistentDataContainer().has(guildKey, PersistentDataType.BYTE)) return;
@ -115,7 +111,7 @@ public final class DuneNPC extends JavaPlugin implements Listener, CommandExecut
if (!player.isOp()) { player.sendMessage(ChatColor.RED + "Operators only. Right-click an Arrakis Smuggler for missions."); return true; }
if (args.length == 0 || args[0].equalsIgnoreCase("admin")) { openAdmin(player); return true; }
if (args[0].equalsIgnoreCase("smuggler")) {
if (!getConfig().getBoolean("smugglers.enabled", true)) { player.sendMessage("Smugglers are disabled in DuneNPC/config.yml."); return true; }
if (getConfig().getBoolean("smugglers.fixed-contracts.enabled", false) || !getConfig().getBoolean("smugglers.enabled", true)) { player.sendMessage("Smugglers are disabled in DuneNPC/config.yml."); return true; }
if (!player.getWorld().getName().equalsIgnoreCase("arrakis")) { player.sendMessage("Spawn smugglers on Arrakis."); return true; }
smugglers.spawnAt(player.getLocation()); player.sendMessage("Arrakis Smuggler placed."); return true;
}
@ -168,7 +164,7 @@ public final class DuneNPC extends JavaPlugin implements Listener, CommandExecut
@Override public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 1) return (sender.isOp() ? List.of("admin", "guildnpc", "smuggler", "status", "smuggle") : List.of("smuggle"))
.stream().filter(item -> item.startsWith(args[0].toLowerCase(Locale.ROOT))).toList();
if (args.length == 2 && args[0].equalsIgnoreCase("smuggle")) return List.of("status", "cancel").stream()
if (args.length == 2 && args[0].equalsIgnoreCase("smuggle")) return List.of("status", "contract", "cancel").stream()
.filter(item -> item.startsWith(args[1].toLowerCase(Locale.ROOT))).toList();
return List.of();
}

View file

@ -65,6 +65,46 @@ final class Smugglers implements Listener {
Bukkit.getScheduler().runTaskTimer(plugin, this::populate, 100L, 1200L);
Bukkit.getScheduler().runTaskTimer(plugin, this::updateCamps, 1L, 20L);
}
private static final NamespacedKey QUEST_CONTACT = new NamespacedKey("dunerealms", "quest_character");
private static final String ESMAR = "esmar_tuek", STABAN = "staban_tuek";
private boolean fixedContracts() {
return plugin.getConfig().getBoolean("smugglers.fixed-contracts.enabled", false);
}
private boolean roamingEnabled() {
return !fixedContracts() && plugin.getConfig().getBoolean("smugglers.enabled", true);
}
private String fixedRole(Entity entity) {
if (!entity.getWorld().getName().equals("arrakis")) return null;
String role = entity.getPersistentDataContainer().get(QUEST_CONTACT, PersistentDataType.STRING);
if (!ESMAR.equals(role) && !STABAN.equals(role)) return null;
var contact = com.dunerealms.npc.CitizensBridge.contact(entity.getWorld(), QUEST_CONTACT, role);
return contact != null && contact.id().equals(com.dunerealms.npc.CitizensBridge.identity(entity)) ? role : null;
}
private boolean contractContact(Entity entity) {
if (!fixedContracts()) return roamingEnabled() && tagged(entity);
String role = fixedRole(entity);
return ESMAR.equals(role) || STABAN.equals(role);
}
private LivingEntity fixedContact(World world, String role) {
if (!world.getName().equals("arrakis")) return null;
LivingEntity contact = null;
for (LivingEntity candidate : world.getEntitiesByClass(LivingEntity.class)) {
if (!candidate.isValid() || !role.equals(fixedRole(candidate))) continue;
if (contact != null) return null;
contact = candidate;
}
return contact;
}
private boolean fixedPairReady(Entity esmar) {
if (!ESMAR.equals(fixedRole(esmar)) || fixedContact(esmar.getWorld(), ESMAR) != esmar) return false;
var staban = com.dunerealms.npc.CitizensBridge.contact(esmar.getWorld(), QUEST_CONTACT, STABAN);
if (staban == null || staban.id().equals(com.dunerealms.npc.CitizensBridge.identity(esmar))) return false;
Location source = esmar.getLocation();
Location destination = staban.location();
return Math.hypot(source.getX() - destination.getX(), source.getZ() - destination.getZ()) >= 64;
}
private Set<UUID> activeSources() {
Set<UUID> ids = new HashSet<>();
for (Contract contract : contracts.values()) ids.add(contract.source());
@ -72,9 +112,9 @@ final class Smugglers implements Listener {
}
private void updateCamps() {
expireContracts();
Set<UUID> active = plugin.getConfig().getBoolean("smugglers.enabled", true) ? activeSources() : Set.of();
Set<UUID> active = roamingEnabled() ? activeSources() : Set.of();
camps.sync(active);
if (!plugin.getConfig().getBoolean("smugglers.enabled", true)) return;
if (!roamingEnabled()) return;
World world = Bukkit.getWorld("arrakis");
if (world == null) return;
for (LivingEntity trader : world.getEntitiesByClass(LivingEntity.class)) if (tagged(trader)) {
@ -110,7 +150,7 @@ final class Smugglers implements Listener {
}
int activeCount() { expireContracts(); return contracts.size(); }
void spawnAt(Location location) {
if (!plugin.getConfig().getBoolean("smugglers.enabled", true)) return;
if (!roamingEnabled()) return;
com.dunerealms.npc.CitizensBridge.spawnContact(plugin,location,"Arrakis Smuggler",traderKey);
}
private boolean tagged(Entity entity) {
@ -129,7 +169,7 @@ final class Smugglers implements Listener {
if(event.getEntity() instanceof WanderingTrader && event.getEntity().getWorld().getName().equalsIgnoreCase("arrakis")) event.setCancelled(true);
}
private void populate() {
if (!plugin.getConfig().getBoolean("smugglers.enabled", true)) return;
if (!roamingEnabled()) return;
World world = Bukkit.getWorld("arrakis");
if (world == null || world.getPlayers().isEmpty()) return;
int count = 0;
@ -173,16 +213,20 @@ final class Smugglers implements Listener {
}
@EventHandler(ignoreCancelled = false) public void interact(PlayerInteractEntityEvent event) {
if (!tagged(event.getRightClicked())) return;
Entity contact = event.getRightClicked();
if (!contractContact(contact) || fixedContracts() && ESMAR.equals(fixedRole(contact))) return;
event.setCancelled(true);
if (!plugin.getConfig().getBoolean("smugglers.enabled", true)) return;
if (event.getHand() != EquipmentSlot.HAND) return;
Player player = event.getPlayer();
if (sanctioned(player)) {
player.sendMessage(ChatColor.GOLD + "Smuggler: 'The Emperor's seal is on your house. I won't risk my routes for an Imperial agent. Sell through your charter: /duneess sell pays +33% before the Trust levy.'");
return;
}
open(player, event.getRightClicked());
if(fixedContracts() && !contracts.containsKey(player.getUniqueId())){
player.sendMessage("Start a delivery contract with Esmar Tuek first.");
return;
}
open(player, contact);
}
private ItemStack icon(Material type, String title, String... lines) {
ItemStack item = new ItemStack(type);
@ -235,16 +279,19 @@ final class Smugglers implements Listener {
if (!player.isOnline()) return;
player.closeInventory();
expireContracts();
if (!plugin.getConfig().getBoolean("smugglers.enabled", true)) return;
if (sanctioned(player)) { player.sendMessage(ChatColor.RED + "Imperial sanction: smuggling contracts are unavailable."); return; }
Entity trader = com.dunerealms.npc.CitizensBridge.resolve(menu.trader);
if (trader == null || !trader.isValid() || !tagged(trader)
if (trader == null || !trader.isValid() || !contractContact(trader)
|| !trader.getWorld().getName().equalsIgnoreCase("arrakis") || player.getWorld() != trader.getWorld()
|| player.getLocation().distanceSquared(trader.getLocation()) > 64) {
player.sendMessage(ChatColor.RED + "Return to the smuggler to trade."); return;
}
Contract active = contracts.get(player.getUniqueId());
if (active == null && (slot == 11 || slot == 15)) {
if(fixedContracts() && !fixedPairReady(trader)) {
player.sendMessage("Both fixed delivery contacts must be available before starting a contract.");
return;
}
contracts.put(player.getUniqueId(), offer(slot == 11 ? "spice" : "water", trader));
if (!save()) { contracts.remove(player.getUniqueId()); player.sendMessage("Contract could not be saved. Try again."); return; }
updateCamps();
@ -253,7 +300,7 @@ final class Smugglers implements Listener {
? "Smuggler: 'The melange must vanish from the Imperial ledger. My distant contact will pay for your silence.'"
: "Smuggler: 'The hidden sietch has no water to spare. Reach my distant contact, and its people will remember.'"));
player.sendMessage("Carry the cargo to another smuggler 64+ blocks from here. /dune smuggle status shows your contract.");
player.sendMessage("You have 30 real minutes, including offline time. Your contact will wait at this lit camp until the contract ends.");
player.sendMessage(fixedContracts()?"You have 30 real minutes. Deliver to Staban Tuek.":"You have 30 real minutes, including offline time. Your contact will wait at this lit camp until the contract ends.");
} else if (active != null && slot == 22) {
contracts.remove(player.getUniqueId());
if (!save()) contracts.put(player.getUniqueId(), active);
@ -316,8 +363,16 @@ final class Smugglers implements Listener {
}
void command(Player player, String[] args) {
expireContracts();
if(args.length>1&&args[1].equalsIgnoreCase("contract")){
LivingEntity esmar=fixedContracts()?fixedContact(player.getWorld(),ESMAR):null;
if(esmar==null||player.getLocation().distanceSquared(esmar.getLocation())>64){player.sendMessage("Meet Esmar Tuek on Arrakis to open fixed delivery contracts.");return;}
if(sanctioned(player)){player.sendMessage("Imperial sanction: smuggling contracts are unavailable.");return;}
if(!fixedPairReady(esmar)&&!contracts.containsKey(player.getUniqueId())){player.sendMessage("Both fixed contacts must be available first.");return;}
open(player,esmar);
return;
}
Contract contract = contracts.get(player.getUniqueId());
if (contract == null) { player.sendMessage("No smuggling contract. Seek a roaming Arrakis Smuggler."); return; }
if (contract == null) { player.sendMessage(fixedContracts()?"No smuggling contract. Meet Esmar Tuek on Arrakis.":"No smuggling contract. Seek a roaming Arrakis Smuggler."); return; }
if (args.length > 1 && args[1].equalsIgnoreCase("cancel")) {
contracts.remove(player.getUniqueId());
if (!save()) contracts.put(player.getUniqueId(), contract);

View file

@ -1,6 +1,8 @@
guild-npc:
enabled: true
smugglers:
fixed-contracts:
enabled: false
enabled: true
max-traders: 6
spice-amount: 64

View file

@ -3,7 +3,7 @@ version: 1.0.0
main: com.example.dunenpc.DuneNPC
api-version: '1.21'
depend: [DuneCore, DuneEss, Vault]
softdepend: [Citizens, Citizens, DuneTerrain]
softdepend: [Citizens, DuneTerrain]
description: Guild Navigators, roaming smugglers, timed missions and quest camps
commands:
dunenpc:

View file

@ -15,6 +15,13 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class CitizensBridgeTest {
@Test void fixedQuestRoleMatchesMetadataEvenWithLegacySmugglerMarker() throws Exception {
var marker = new NamespacedKey("dunerealms", "quest_character");
String stored = "dunecore\\:smuggler=b:1\n" + "dunerealms\\:quest_character=s:esmar_tuek\n";
assertEquals(true, CitizensBridge.matchesMarker(stored, marker, "esmar_tuek"));
assertEquals(false, CitizensBridge.matchesMarker(stored, marker, "staban_tuek"));
}
@Test void conversionPersistsExistingBackendMarkersBeforeRetiringOldBody() throws Exception {
conversion(true);
}

View file

@ -0,0 +1,9 @@
package com.dunerealms.gui;
/** Turns an offset into words a player can follow. North is -Z, east is +X. */
final class Bearing {
private static final String[] POINTS={"north","north-east","east","south-east","south","south-west","west","north-west"};
private Bearing(){}
static String direction(double dx,double dz){double degrees=Math.toDegrees(Math.atan2(dx,-dz));if(degrees<0)degrees+=360;return POINTS[(int)Math.round(degrees/45.0)%8];}
static String describe(double dx,double dz){int blocks=(int)Math.round(Math.hypot(dx,dz));return blocks<6?"right beside you":blocks+" blocks "+direction(dx,dz);}
}

View file

@ -140,8 +140,8 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
var passage = data.getAsJsonObject("guildQuote");
var eligible = quotedDestinations(passage);
var catalog = GuildRoutes.catalog(passage);
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."+(data.getAsJsonObject("guildQuote").has("subsidyMinor")?" Guild subsidy: "+String.format(java.util.Locale.ROOT,"%.2f",data.getAsJsonObject("guildQuote").get("subsidyMinor").getAsInt()/100.0)+" DM.":"");
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.");
var booked=bookings.get(p.getUniqueId());
String detail="Travel opens at :00, :20 and :40 for five minutes."+(booked==null?"":"\nYour passage is already booked.");
if(BedrockForms.isBedrock(p)){
List<BedrockForms.Choice> choices=new ArrayList<>();
for(var route:GuildRoutes.ALL){
@ -149,7 +149,7 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
String reason=offer==null?guildUnavailable(passage,eligible,route.world()):offer.available()?null:offer.reason();
String name=offer==null?route.name():offer.name();
choices.add(new BedrockForms.Choice((reason==null?"§6":"§8")+name+(reason==null?"":" · "+reason),
reason==null?detail:reason,reason==null?()->bookPassage(p,data,route.world()):()->{p.sendMessage(reason);renderTravelMenu(p,data);},
reason==null?guildQuoteText(passage,offer)+"\n"+detail:reason,reason==null?()->bookPassage(p,data,route.world()):()->{p.sendMessage(reason);renderTravelMenu(p,data);},
"https://www.dunerealms.com/assets/gui/guild-world-"+route.world().replace('_','-')+(reason==null?"":"-locked")+"-v1.png"));
}
choices.add(new BedrockForms.Choice("Cancel booking","No fare has been charged",()->{cancelBooking(p);travelMenu(p,data);}));
@ -163,7 +163,7 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
String reason=offer==null?guildUnavailable(passage,eligible,route.world()):offer.available()?null:offer.reason();
String name=offer==null?route.name():offer.name();
int centre=CENTRES[i];
var item=icon(p,name,reason==null?detail:reason,"drgui_transparent",reason==null?Material.ENDER_PEARL:Material.GRAY_DYE);
var item=icon(p,name,reason==null?guildQuoteText(passage,offer)+"\n"+detail:reason,"drgui_transparent",reason==null?Material.ENDER_PEARL:Material.GRAY_DYE);
if(reason!=null){
item.setType(Material.GRAY_DYE);
var meta=item.getItemMeta();meta.setItemModel(null);meta.displayName(Component.text(name,NamedTextColor.GRAY));item.setItemMeta(meta);
@ -177,6 +177,13 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
if(MCGUIMenus.show(p,"Spacing Guild · Imperial passage","",screen.inventory,screen.actions,screen.gate))return;
p.openInventory(screen.inventory);expire(screen);
}
private static String guildQuoteText(JsonObject quote,GuildRoutes.Offer offer){
long fare=offer==null?quote.get("fareMinor").getAsLong():offer.fareMinor();
if(fare==0)return "Free passage";
String terms=String.format(Locale.ROOT,"Fare %.2f DM, collected after arrival.",fare/100.0);
if(offer!=null&&offer.bountyMinor()>0)terms+=String.format(Locale.ROOT,"\nArrival bounty %.2f DM",offer.bountyMinor()/100.0)+(offer.reduced()?" · Home Block discount":"");
return terms;
}
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 String guildUnavailable(JsonObject quote,Set<String> eligible,String world){
if(quote.has("prologueRequired")&&quote.get("prologueRequired").getAsBoolean())return "Complete your House Prologue.";
@ -190,7 +197,17 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
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));});
var q=new JsonObject();q.addProperty("action","quote");guildRequest(p,q,quote->{var available=quotedDestinations(quote);var offer=GuildRoutes.catalog(quote).get(destination);
String reason=offer==null?guildUnavailable(quote,available,destination):offer.available()?null:offer.reason();
if(reason!=null||!available.contains(destination)){p.sendMessage(reason==null||reason.isBlank()?"That route is no longer available.":reason);return;}
var home=GuildRoutes.ALL.stream().filter(r->r.world().equals(destination)).findFirst().orElseThrow();
int fare=offer==null?quote.get("fareMinor").getAsInt():Math.toIntExact(offer.fareMinor());
var shownQuote=shown.getAsJsonObject("guildQuote");
var shownOffer=GuildRoutes.catalog(shownQuote).get(destination);
if(!guildQuoteText(shownQuote,shownOffer).equals(guildQuoteText(quote,offer))){
p.sendMessage("The Guild changed this fare or arrival bounty. Review the current passage.");
fresh.add("guildQuote",quote);renderTravelMenu(p,fresh);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){
@ -233,7 +250,6 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
// 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.
offerGuiPack(p,false);
giveCodex(p,false);
if(sidebar.enabled(p))refreshSidebar(p);
},40L);}
@EventHandler public void packStatus(PlayerResourcePackStatusEvent e){
@ -329,7 +345,8 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
@EventHandler public void quit(PlayerQuitEvent e){MCGUIMenus.forget(e.getPlayer().getUniqueId());guiPackLoaded.remove(e.getPlayer().getUniqueId());offeredGuiPacks.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);
if(!com.dunerealms.npc.CitizensBridge.ready()||com.dunerealms.npc.CitizensBridge.exists(this,world,registrar,"1"))return;
com.dunerealms.npc.CitizensBridge.spawnContact(this,at,"§6House Registrar · Choose your House",registrar,"1",true);
}
@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(){

View file

@ -14,8 +14,9 @@ final class GuildRoutes {
);
static Route home(String house){return ALL.stream().filter(r->r.house().equals(house)).findFirst().orElse(null);}
static boolean allowed(String house,String world){Route route=home(house);return route!=null&&route.world().equals(world);}
static boolean candidate(String house,String world){return home(house)!=null&&(allowed(house,world)||"arrakis".equals(world));}
record Offer(String server,String name,boolean available,String reason,long fareMinor){}
/** Open travel: every House may book any trade world. Fare, sanction and bounty are decided centrally by JARVIS. */
static boolean candidate(String house,String world){return home(house)!=null&&ALL.stream().anyMatch(route->route.world().equals(world));}
record Offer(String server,String name,boolean available,String reason,long fareMinor,long bountyMinor,boolean reduced){}
static Map<String,Offer> catalog(JsonObject quote){
Map<String,Offer> result=new LinkedHashMap<>();
@ -27,7 +28,9 @@ final class GuildRoutes {
String server=row.get("server").getAsString();
if(ALL.stream().noneMatch(route->route.world().equals(server)))continue;
String reason=row.has("reason")&&!row.get("reason").isJsonNull()?row.get("reason").getAsString():"Passage unavailable";
result.putIfAbsent(server,new Offer(server,row.get("name").getAsString(),row.get("available").getAsBoolean(),reason,row.get("fareMinor").getAsLong()));
result.putIfAbsent(server,new Offer(server,row.get("name").getAsString(),row.get("available").getAsBoolean(),reason,row.get("fareMinor").getAsLong(),
row.has("bountyMinor")?row.get("bountyMinor").getAsLong():0,
row.has("reduced")&&row.get("reduced").getAsBoolean()));
}
return result;
}

View file

@ -0,0 +1,125 @@
package com.dunerealms.gui;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.math.BigDecimal;
import java.util.*;
/** Pure view-model of the mission journal: story arcs, mission status, bars. The server decides everything; nothing here grants anything. */
final class JournalModel {
private JournalModel(){}
static final String DONE="done",READY="ready",ACTIVE="active",AVAILABLE="available",LOCKED="locked";
record Mission(String id,String title,String arc,String status,String objective,long progress,long target,boolean canClaim,boolean canStart,
int revision,long xp,boolean rewardConfigured,boolean money,String lockedBy,List<String> requires,boolean webOnly){
int percent(){return target<=0?0:(int)Math.min(100,Math.floor(Math.min(progress,target)*100.0/target));}
boolean finished(){return DONE.equals(status);}
}
record Arc(String id,String title,List<Mission> missions){
int done(){int n=0;for(var m:missions)if(m.finished())n++;return n;}
boolean complete(){return !missions.isEmpty()&&done()==missions.size();}
}
private static String text(JsonObject o,String key,String fallback){return o.has(key)&&!o.get(key).isJsonNull()?o.get(key).getAsString():fallback;}
private static long number(JsonObject o,String key,long fallback){try{return o.has(key)&&!o.get(key).isJsonNull()?o.get(key).getAsLong():fallback;}catch(RuntimeException e){return fallback;}}
private static boolean yes(JsonObject o,String key){return o.has(key)&&!o.get(key).isJsonNull()&&o.get(key).getAsBoolean();}
private static List<String> strings(JsonObject o,String key){var out=new ArrayList<String>();if(o.has(key)&&o.get(key).isJsonArray())for(JsonElement e:o.getAsJsonArray(key))if(!e.isJsonNull())out.add(e.getAsString());return out;}
/** A website-only objective cannot be started or claimed in game. */
static boolean webOnly(JsonObject q){
if(!q.has("executionRequirements")||!q.get("executionRequirements").isJsonObject())return false;
var channel=q.getAsJsonObject("executionRequirements");return yes(channel,"website")&&!yes(channel,"minecraft");
}
static String status(JsonObject q){
String state=text(q,"state","not-started");
if("claimed".equals(state))return DONE;
if(yes(q,"canClaim")&&number(q,"progress",0)>=number(q,"target",1))return READY;
if("completed".equals(state))return READY;
if("active".equals(state))return ACTIVE;
return yes(q,"canStart")?AVAILABLE:LOCKED;
}
static String label(String status){return switch(status){case DONE->"Done";case READY->"Ready to claim";case ACTIVE->"Active";case AVAILABLE->"Available";default->"Locked";};}
/** Orders an arc so a mission never precedes the missions it requires; survives cycles. */
static List<JsonObject> order(List<JsonObject> quests){
var byId=new LinkedHashMap<String,JsonObject>();for(var q:quests)byId.put(text(q,"id",""),q);
var placed=new HashSet<String>();var out=new ArrayList<JsonObject>();
for(var q:quests)place(q,byId,placed,out);return out;
}
private static void place(JsonObject q,Map<String,JsonObject> byId,Set<String> placed,List<JsonObject> out){
String id=text(q,"id","");if(!placed.add(id))return;
var parents=new ArrayList<>(strings(q,"requires"));parents.addAll(strings(q,"requiresAny"));
for(String parent:parents){var p=byId.get(parent);if(p!=null)place(p,byId,placed,out);}
out.add(q);
}
static List<Arc> arcs(JsonObject data){
var quests=new ArrayList<JsonObject>();if(data.has("quests")&&data.get("quests").isJsonArray())for(JsonElement e:data.getAsJsonArray("quests"))if(e.isJsonObject())quests.add(e.getAsJsonObject());
var groups=new LinkedHashMap<String,List<JsonObject>>();for(var q:quests)groups.computeIfAbsent(text(q,"branch","missions"),k->new ArrayList<>()).add(q);
var titles=new HashMap<String,String>();if(data.has("branches")&&data.get("branches").isJsonArray())for(JsonElement e:data.getAsJsonArray("branches"))if(e.isJsonObject())titles.put(text(e.getAsJsonObject(),"id",""),text(e.getAsJsonObject(),"title",""));
var names=new HashMap<String,String>();var states=new HashMap<String,String>();for(var q:quests){names.put(text(q,"id",""),text(q,"title",""));states.put(text(q,"id",""),text(q,"state",""));}
var arcs=new ArrayList<Arc>();
for(var group:groups.entrySet()){
var missions=new ArrayList<Mission>();
for(var q:order(group.getValue())){
String status=status(q),lockedBy=null;
if(LOCKED.equals(status))for(String r:strings(q,"requires"))if(names.containsKey(r)&&!"claimed".equals(states.get(r))){lockedBy="Complete "+names.get(r)+" first.";break;}
missions.add(new Mission(text(q,"id",""),text(q,"title","Mission"),group.getKey(),status,text(q,"objective",""),Math.max(0,number(q,"progress",0)),Math.max(1,number(q,"target",1)),
yes(q,"canClaim"),yes(q,"canStart"),(int)number(q,"revision",0),number(q,"xp",-1),yes(q,"rewardConfigured"),text(q,"metric","").endsWith("-minor"),lockedBy,strings(q,"requires"),webOnly(q)));
}
String title=titles.getOrDefault(group.getKey(),"");arcs.add(new Arc(group.getKey(),title.isBlank()?group.getKey().toUpperCase(Locale.ROOT):title,List.copyOf(missions)));
}
return arcs;
}
static List<Mission> all(List<Arc> arcs){var out=new ArrayList<Mission>();for(var a:arcs)out.addAll(a.missions());return out;}
static Mission find(List<Arc> arcs,String id){if(id==null)return null;for(var m:all(arcs))if(m.id().equals(id))return m;return null;}
/** The player's pick, else the tracked mission, else whatever needs attention first. */
static String pick(List<Arc> arcs,String preferred,String tracked){
if(find(arcs,preferred)!=null)return preferred;if(find(arcs,tracked)!=null)return tracked;
for(String status:new String[]{READY,ACTIVE,AVAILABLE})for(var m:all(arcs))if(m.status().equals(status))return m.id();
var every=all(arcs);return every.isEmpty()?null:every.get(0).id();
}
/** Next unfinished mission in the same arc after the given one, or null. */
static String nextInArc(List<Arc> arcs,String id){
for(var arc:arcs){
int index=-1;for(int i=0;i<arc.missions().size();i++)if(arc.missions().get(i).id().equals(id))index=i;
if(index<0)continue;
for(int i=index+1;i<arc.missions().size();i++)if(!arc.missions().get(i).finished())return arc.missions().get(i).id();
for(var m:arc.missions())if(!m.finished()&&!m.id().equals(id))return m.id();
return null;
}
return null;
}
static Mission current(List<Arc> arcs,String tracked){
var t=find(arcs,tracked);if(t!=null&&!t.finished())return t;
for(String status:new String[]{ACTIVE,READY})for(var m:all(arcs))if(m.status().equals(status))return m;
return null;
}
static Map<String,String> statuses(List<Arc> arcs){var map=new HashMap<String,String>();for(var m:all(arcs))map.put(m.id(),m.status());return map;}
/** Missions that became ready or done since the previous snapshot. A first snapshot never announces anything. */
static List<Mission> completions(Map<String,String> before,List<Arc> arcs){
var out=new ArrayList<Mission>();if(before==null)return out;
for(var m:all(arcs)){String was=before.get(m.id());if(was!=null&&!READY.equals(was)&&!DONE.equals(was)&&(READY.equals(m.status())||DONE.equals(m.status())))out.add(m);}
return out;
}
static String briefing(String objective,int limit){
String clean=objective==null?"":objective.replaceAll("\\s+"," ").trim();if(clean.isEmpty())return "Follow the objective below.";
int end=-1;for(int i=0;i<clean.length();i++){char c=clean.charAt(i);if((c=='.'||c=='!'||c=='?')&&(i+1==clean.length()||clean.charAt(i+1)==' ')){end=i+1;break;}}
String sentence=end>0?clean.substring(0,end):clean;
return sentence.length()>limit?sentence.substring(0,limit-1).stripTrailing()+"…":sentence;
}
static String bar(long progress,long target,int width){
long safe=Math.max(1,target);int filled=(int)Math.round(width*(double)Math.min(Math.max(0,progress),safe)/safe);filled=Math.max(0,Math.min(width,filled));
return "▰".repeat(filled)+"▱".repeat(width-filled);
}
static String amount(Mission m,long value){return m.money()?BigDecimal.valueOf(value,2).toPlainString()+" DM":String.valueOf(value);}
static String progressText(Mission m){long shown=Math.min(m.progress(),m.target());return amount(m,shown)+" / "+amount(m,m.target());}
/** Greedy word wrap for inventory lore. */
static List<String> wrap(String text,int width){
var lines=new ArrayList<String>();var line=new StringBuilder();
for(String word:(text==null?"":text).trim().split("\\s+")){if(word.isEmpty())continue;if(line.length()>0&&line.length()+1+word.length()>width){lines.add(line.toString());line.setLength(0);}if(line.length()>0)line.append(' ');line.append(word);}
if(line.length()>0)lines.add(line.toString());return lines;
}
}

View file

@ -0,0 +1,89 @@
package com.dunerealms.gui;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.IOException;
import java.util.*;
import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.title.Title;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
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.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
/** Tracks one mission per journal, shows it as a boss bar, and announces completions. Reads only; the server pays. */
final class MissionTracker implements Listener {
private static final List<String> KINDS=List.of("personal","pol");
private final JavaPlugin plugin;private final HouseBridge bridge;private final File file;private final YamlConfiguration data;
private final Map<String,BossBar> bars=new HashMap<>();private final Map<String,Map<String,String>> last=new HashMap<>();
MissionTracker(JavaPlugin plugin,HouseBridge bridge){
this.plugin=plugin;this.bridge=bridge;file=new File(plugin.getDataFolder(),"tracked-missions.yml");data=YamlConfiguration.loadConfiguration(file);
Bukkit.getPluginManager().registerEvents(this,plugin);
Bukkit.getScheduler().runTaskTimer(plugin,this::poll,1200L,1200L);
}
String tracked(UUID player,String kind){return data.getString(player+"."+kind,null);}
void track(UUID player,String kind,String missionId){data.set(player+"."+kind,missionId);save();}
private void save(){try{file.getParentFile().mkdirs();data.save(file);}catch(IOException failure){plugin.getLogger().warning("Cannot save tracked missions: "+failure.getMessage());}}
/** Main thread. Announces missions that just became ready or done, advances a finished tracked mission, refreshes the bar. */
void observe(Player p,String kind,List<JournalModel.Arc> arcs){
UUID id=p.getUniqueId();String key=id+":"+kind;
for(var mission:JournalModel.completions(last.get(key),arcs))announce(p,mission);
last.put(key,JournalModel.statuses(arcs));
String tracked=tracked(id,kind);
if(tracked!=null){
var mission=JournalModel.find(arcs,tracked);
if(mission==null)track(id,kind,null);
else if(mission.finished()){String next=JournalModel.nextInArc(arcs,tracked);track(id,kind,next);}
}
refreshBar(p,kind,arcs);
}
private void announce(Player p,JournalModel.Mission mission){
boolean paid=mission.finished();
p.showTitle(Title.title(Component.text(paid?"MISSION COMPLETE":"OBJECTIVE COMPLETE",NamedTextColor.GOLD),Component.text(mission.title(),NamedTextColor.YELLOW)));
p.sendMessage(Component.text((paid?"Mission complete: ":"Objective complete: ")+mission.title()+(paid?"":" — open your journal to claim."),NamedTextColor.GOLD));
p.playSound(p.getLocation(),Sound.UI_TOAST_CHALLENGE_COMPLETE,1f,1f);
}
private void refreshBar(Player p,String kind,List<JournalModel.Arc> arcs){
String key=p.getUniqueId()+":"+kind;var current=JournalModel.current(arcs,tracked(p.getUniqueId(),kind));
var bar=bars.get(key);
if(tracked(p.getUniqueId(),kind)==null||current==null){if(bar!=null){p.hideBossBar(bar);bars.remove(key);}return;}
Component name=Component.text((kind.equals("pol")?"Reputation: ":"Mission: ")+current.title()+" — "+JournalModel.progressText(current)+(current.status().equals(JournalModel.READY)?" · ready to claim":""));
float progress=Math.max(0f,Math.min(1f,current.percent()/100f));
if(bar==null){bar=BossBar.bossBar(name,progress,kind.equals("pol")?BossBar.Color.PURPLE:BossBar.Color.YELLOW,BossBar.Overlay.PROGRESS);bars.put(key,bar);p.showBossBar(bar);}
else{bar.name(name);bar.progress(progress);}
}
private void poll(){for(Player p:Bukkit.getOnlinePlayers())for(String kind:KINDS)if(tracked(p.getUniqueId(),kind)!=null)fetch(p.getUniqueId(),kind);}
private void fetch(UUID id,String kind){
var input=new JsonObject();input.addProperty("action","read");input.addProperty("kind",kind);
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{
JsonObject result=null;try{result=bridge.quests(id,input);}catch(Exception ignored){}
var data=result;if(!plugin.isEnabled())return;
Bukkit.getScheduler().runTask(plugin,()->{
Player now=Bukkit.getPlayer(id);
if(now==null||data==null||!data.has("state")||data.get("state").isJsonNull()||!"active".equals(data.get("state").getAsString()))return;
observe(now,kind,JournalModel.arcs(data));
});
});
}
@EventHandler public void join(PlayerJoinEvent e){
UUID id=e.getPlayer().getUniqueId();
Bukkit.getScheduler().runTaskLater(plugin,()->{for(String kind:KINDS)if(tracked(id,kind)!=null)fetch(id,kind);},200L);
}
@EventHandler public void quit(PlayerQuitEvent e){
UUID id=e.getPlayer().getUniqueId();
for(String kind:KINDS){String key=id+":"+kind;bars.remove(key);last.remove(key);}
}
void close(){
for(Player p:Bukkit.getOnlinePlayers())for(String kind:KINDS){var bar=bars.get(p.getUniqueId()+":"+kind);if(bar!=null)p.hideBossBar(bar);}
bars.clear();last.clear();
}
}

View file

@ -20,6 +20,7 @@ import net.kyori.adventure.key.Key;
/** One persistent named quest contact per role/world; existing service NPCs are not replaced. */
final class PolQuestNpc implements Listener {
record Role(String key,String name,String world,String faction,Set<String> branches,int offset){}
private static final String DELIVERY_CONTACT="staban_tuek";
private static final List<Role> ROLES=List.of(
new Role("war_marshal","War Marshal","caladan","*",Set.of(),-18),
new Role("war_marshal","War Marshal","giedi_prime","*",Set.of(),-12),
@ -49,6 +50,7 @@ final class PolQuestNpc implements Listener {
new Role("stilgar","Stilgar · House introduction","guild_lobby","fremen",Set.of("prologue"),-21),
new Role("edric","Edric · Guild logistics","guild_lobby","*",Set.of("guild"),-3),
new Role("esmar_tuek","Esmar Tuek · Smuggler contact","arrakis","*",Set.of("smugglers","spice-upgrading","elytra"),-18),
new Role(DELIVERY_CONTACT,"Staban Tuek · Smuggler delivery contact","arrakis","*",Set.of(),80),
new Role("esmar_tuek","Esmar Tuek · Smuggler contact","guild_lobby","*",Set.of("smugglers"),-6));
static final NamespacedKey KEY=new NamespacedKey("dunerealms","quest_character");
private final JavaPlugin plugin;private final BiConsumer<Player,Role> open;private final File file;private final YamlConfiguration positions;
@ -57,22 +59,65 @@ final class PolQuestNpc implements Listener {
private static Role role(String id,World world){return ROLES.stream().filter(r->r.key().equals(id)&&r.world().equals(world.getName())).findFirst().orElse(null);}
private String base(Role role){return role.world()+"."+role.key();}
private Location saved(Role role,World world){String b=base(role);return positions.contains(b+".x")?new Location(world,positions.getDouble(b+".x"),positions.getDouble(b+".y"),positions.getDouble(b+".z"),(float)positions.getDouble(b+".yaw"),(float)positions.getDouble(b+".pitch")):null;}
private void save(Role role,LivingEntity npc){Location l=npc.getLocation();String b=base(role);positions.set(b+".entity",npc.getUniqueId().toString());positions.set(b+".x",l.getX());positions.set(b+".y",l.getY());positions.set(b+".z",l.getZ());positions.set(b+".yaw",l.getYaw());positions.set(b+".pitch",l.getPitch());try{Path target=file.toPath(),directory=target.getParent();Files.createDirectories(directory);Path temporary=Files.createTempFile(directory,"quest-npc-positions-",".yml");try{positions.save(temporary.toFile());try{Files.move(temporary,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}catch(AtomicMoveNotSupportedException unsupported){Files.move(temporary,target,StandardCopyOption.REPLACE_EXISTING);}}finally{Files.deleteIfExists(temporary);}}catch(java.io.IOException failure){plugin.getLogger().warning("Quest NPC position could not be saved: "+role.key());}}
private LivingEntity existing(Role role,World world){String id=positions.getString(base(role)+".entity");if(id!=null)try{Entity e=Bukkit.getEntity(UUID.fromString(id));if(e instanceof LivingEntity living&&role.key().equals(e.getPersistentDataContainer().get(KEY,PersistentDataType.STRING)))return living;}catch(IllegalArgumentException ignored){}return world.getEntitiesByClass(LivingEntity.class).stream().filter(e->role.key().equals(e.getPersistentDataContainer().get(KEY,PersistentDataType.STRING))).findFirst().orElse(null);}
private void save(Role role,LivingEntity npc){Location l=npc.getLocation();String b=base(role);positions.set(b+".entity",com.dunerealms.npc.CitizensBridge.identity(npc).toString());positions.set(b+".x",l.getX());positions.set(b+".y",l.getY());positions.set(b+".z",l.getZ());positions.set(b+".yaw",l.getYaw());positions.set(b+".pitch",l.getPitch());try{Path target=file.toPath(),directory=target.getParent();Files.createDirectories(directory);Path temporary=Files.createTempFile(directory,"quest-npc-positions-",".yml");try{positions.save(temporary.toFile());try{Files.move(temporary,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}catch(AtomicMoveNotSupportedException unsupported){Files.move(temporary,target,StandardCopyOption.REPLACE_EXISTING);}}finally{Files.deleteIfExists(temporary);}}catch(java.io.IOException failure){plugin.getLogger().warning("Quest NPC position could not be saved: "+role.key());}}
private LivingEntity existing(Role role,World world){String id=positions.getString(base(role)+".entity");if(id!=null)try{Entity e=com.dunerealms.npc.CitizensBridge.resolve(UUID.fromString(id));if(e instanceof LivingEntity living&&role.key().equals(e.getPersistentDataContainer().get(KEY,PersistentDataType.STRING)))return living;}catch(IllegalArgumentException ignored){}return world.getEntitiesByClass(LivingEntity.class).stream().filter(e->role.key().equals(e.getPersistentDataContainer().get(KEY,PersistentDataType.STRING))).findFirst().orElse(null);}
private static boolean usable(Location at){return at.getBlock().isPassable()&&at.clone().add(0,1,0).getBlock().isPassable()&&at.clone().add(0,-1,0).getBlock().getType().isSolid();}
private static Location initial(Role role,World world){Location spawn=world.getSpawnLocation();for(int distance:new int[]{role.offset(),-role.offset(),role.offset()-2,role.offset()+2}){Location at=spawn.clone().add(distance,0,0);if(usable(at))return at;}return null;}
private void configure(Role role,LivingEntity npc){npc.setInvulnerable(true);npc.setPersistent(true);npc.setRemoveWhenFarAway(false);npc.setSilent(true);npc.setCollidable(false);if(npc instanceof Mob mob)mob.setAI(false);npc.customName(Component.text((role.key().equals("war_marshal")?"⚔ ":"✦ ")+role.name(),role.key().equals("war_marshal")?NamedTextColor.GOLD:NamedTextColor.AQUA));npc.setCustomNameVisible(true);npc.getPersistentDataContainer().set(KEY,PersistentDataType.STRING,role.key());if(role.key().equals("esmar_tuek")&&role.world().equals("arrakis"))npc.getPersistentDataContainer().set(new NamespacedKey("dunecore","smuggler"),PersistentDataType.BYTE,(byte)1);try{npc.getClass().getMethod("setImmovable",boolean.class).invoke(npc,true);}catch(ReflectiveOperationException ignored){}}
private void configure(Role role,LivingEntity npc){npc.setInvulnerable(true);npc.setPersistent(true);npc.setRemoveWhenFarAway(false);npc.setSilent(true);npc.setCollidable(false);if(npc instanceof Mob mob)mob.setAI(false);npc.customName(Component.text((role.key().equals("war_marshal")?"⚔ ":"✦ ")+role.name(),role.key().equals("war_marshal")?NamedTextColor.GOLD:NamedTextColor.AQUA));npc.setCustomNameVisible(true);npc.getPersistentDataContainer().set(KEY,PersistentDataType.STRING,role.key());try{npc.getClass().getMethod("setImmovable",boolean.class).invoke(npc,true);}catch(ReflectiveOperationException ignored){}}
private static Class<?> profileType()throws ClassNotFoundException{return Class.forName("io.papermc.paper.datacomponent.item.ResolvableProfile");}
private static Object skin(String role)throws ReflectiveOperationException{Class<?> profile=profileType(),builder=Class.forName(profile.getName()+"$Builder"),patch=Class.forName(profile.getName()+"$SkinPatch"),patchBuilder=Class.forName(profile.getName()+"$SkinPatchBuilder");Object b=profile.getMethod("resolvableProfile").invoke(null),p=patch.getMethod("skinPatch").invoke(null);patchBuilder.getMethod("body",Key.class).invoke(p,Key.key("dunerealms","textures/entity/npc/"+role+".png"));patchBuilder.getMethod("model",org.bukkit.profile.PlayerTextures.SkinModel.class).invoke(p,org.bukkit.profile.PlayerTextures.SkinModel.CLASSIC);Object built=patchBuilder.getMethod("build").invoke(p);builder.getMethod("name",String.class).invoke(b,"DRQuestContact");builder.getMethod("skinPatch",patch).invoke(b,built);return builder.getMethod("build").invoke(b);}
private static void profile(LivingEntity npc,Object value)throws ReflectiveOperationException{Class.forName("org.bukkit.entity.Mannequin").getMethod("setProfile",profileType()).invoke(npc,value);}
@SuppressWarnings("unchecked") private LivingEntity spawn(Role role,Location at){try{Class<? extends LivingEntity> type=(Class<? extends LivingEntity>)Class.forName("org.bukkit.entity.Mannequin");Object appearance=skin(role.key().equals("war_marshal")?"duncan_idaho":role.key());LivingEntity npc=at.getWorld().spawn(at,type,e->configure(role,e));try{profile(npc,appearance);return npc;}catch(ReflectiveOperationException failure){npc.remove();throw failure;}}catch(ReflectiveOperationException|LinkageError|IllegalArgumentException unavailable){plugin.getLogger().warning("Character appearance is unavailable for "+role.key()+"; using neutral stationary fallback.");return at.getWorld().spawn(at,Villager.class,v->{v.setProfession(Villager.Profession.LIBRARIAN);configure(role,v);});}}
private void ensure(World world){for(Role role:ROLES){if(!role.world().equals(world.getName()))continue;Location at=saved(role,world);if(at==null)at=initial(role,world);if(at==null){plugin.getLogger().warning("No safe spawn-space for quest NPC "+role.key());continue;}at.getChunk().load();LivingEntity npc=existing(role,world);if(npc==null){if(!usable(at)){plugin.getLogger().warning("Saved quest NPC location obstructed: "+role.key());continue;}npc=spawn(role,at);}configure(role,npc);save(role,npc);if(role.key().equals("imperial_attendant"))applyImperial(npc);}}
private LivingEntity spawn(Role role,Location at){
LivingEntity npc=com.dunerealms.npc.CitizensBridge.spawnContact(plugin,at,"§b✦ "+role.name(),KEY,role.key(),true);
String skin=plugin.getConfig().getString("quest-npc-skins."+role.key());
if(npc!=null&&skin!=null&&!skin.isBlank())com.dunerealms.npc.CitizensBridge.skin(npc,skin);
return npc;
}
private Location initialDelivery(World world){
Location origin=saved(role("esmar_tuek",world),world);
return origin==null?null:findSurfaceContact(world,origin,new int[]{80,96,112});
}
private static Location findSurfaceContact(World world,Location origin,int[] radii){
for(int radius:radii){
for(int[] direction:new int[][]{{-1,0},{1,0},{0,1},{0,-1}}){
int x=origin.getBlockX()+radius*direction[0],z=origin.getBlockZ()+radius*direction[1];
if(!world.isChunkGenerated(x>>4,z>>4))continue;
int y=world.getHighestBlockYAt(x,z,HeightMap.MOTION_BLOCKING_NO_LEAVES)+1;
if(y>=world.getMaxHeight()-1)continue;
var at=new Location(world,x+.5,y,z+.5);
var floor=at.clone().add(0,-1,0).getBlock().getType();
if(world.getWorldBorder().isInside(at)&&usable(at)&&!at.getBlock().isLiquid()&&!at.clone().add(0,1,0).getBlock().isLiquid()
&&!Set.of(Material.CACTUS,Material.MAGMA_BLOCK,Material.CAMPFIRE,Material.SOUL_CAMPFIRE).contains(floor))return at;
}
}
return null;
}
private static boolean fixedSmuggler(String role){return role.equals("esmar_tuek")||role.equals(DELIVERY_CONTACT);}
static boolean deliverySeparation(Location from,Location to){
double dx=from.getX()-to.getX(),dz=from.getZ()-to.getZ();
return dx*dx+dz*dz>=64*64;
}
private void ensure(World world){for(Role role:ROLES){if(!role.world().equals(world.getName()))continue;Location at=saved(role,world);if(at==null){
if(role.key().equals(DELIVERY_CONTACT))at=initialDelivery(world);
else if(role.key().equals("esmar_tuek")&&role.world().equals("arrakis"))at=findSurfaceContact(world,world.getSpawnLocation(),new int[]{18,24,32});
else at=initial(role,world);
}if(at==null){plugin.getLogger().warning("No safe spawn-space for quest NPC "+role.key());continue;}at.getChunk().load();LivingEntity npc=existing(role,world);if(npc==null){if(!com.dunerealms.npc.CitizensBridge.ready()||com.dunerealms.npc.CitizensBridge.exists(plugin,world,KEY,role.key()))continue;if(!usable(at)){plugin.getLogger().warning("Saved quest NPC location obstructed: "+role.key());continue;}npc=spawn(role,at);if(npc==null)continue;}configure(role,npc);save(role,npc);if(role.key().equals("imperial_attendant"))applyImperial(npc);}}
void imperialAppearance(UUID uuid,String name,String term){boolean changed=!Objects.equals(imperialTerm,term)||!Objects.equals(imperialUuid,uuid);imperialUuid=uuid;imperialName=name;imperialTerm=term;if(!changed&&System.currentTimeMillis()<imperialRetry)return;World world=Bukkit.getWorld("kaitain");if(world==null)return;Role role=role("imperial_attendant",world);Location at=saved(role,world);if(at!=null)at.getChunk().load();LivingEntity e=existing(role,world);if(e!=null)applyImperial(e);}
private void applyImperial(LivingEntity npc){String term=imperialTerm;UUID uuid=imperialUuid;String name=imperialName;imperialRetry=System.currentTimeMillis()+600000;try{profile(npc,skin("imperial_attendant"));}catch(ReflectiveOperationException ignored){}npc.customName(Component.text("✦ Imperial attendant",NamedTextColor.AQUA));if(uuid==null||name==null)return; com.dunerealms.npc.CitizensBridge.skin(npc,name);
private void applyImperial(LivingEntity npc){String term=imperialTerm;UUID uuid=imperialUuid;String name=imperialName;imperialRetry=System.currentTimeMillis()+600000;
if(npc instanceof Player){
String skin=uuid==null||name==null?plugin.getConfig().getString("quest-npc-skins.imperial_attendant","Steve"):name;
com.dunerealms.npc.CitizensBridge.rename(npc,uuid==null||name==null?"§b✦ Imperial attendant":"§b✦ Imperial audience · "+name+" (representation)");
com.dunerealms.npc.CitizensBridge.skin(npc,skin);
return;
}
try{profile(npc,skin("imperial_attendant"));}catch(ReflectiveOperationException ignored){}npc.customName(Component.text("✦ Imperial attendant",NamedTextColor.AQUA));if(uuid==null||name==null)return; com.dunerealms.npc.CitizensBridge.skin(npc,name);
Bukkit.createProfile(uuid).update().whenComplete((publicProfile,error)->{if(!plugin.isEnabled())return;Bukkit.getScheduler().runTask(plugin,()->{if(error!=null||publicProfile==null||!publicProfile.hasTextures()||!npc.isValid()||!Objects.equals(term,imperialTerm)||!Objects.equals(uuid,imperialUuid))return;try{Class<?> pp=Class.forName("com.destroystokyo.paper.profile.PlayerProfile");Object resolved=profileType().getMethod("resolvableProfile",pp).invoke(null,publicProfile);profile(npc,resolved);npc.customName(Component.text("✦ Imperial audience · "+name+" (representation)",NamedTextColor.AQUA));}catch(ReflectiveOperationException ignored){/* Keep the neutral attendant. */}});});
}
boolean move(Player player,String key){if(!player.hasPermission("dune.admin")){player.sendMessage("Current NPC administration permission required.");return false;}Role role=role(key,player.getWorld());if(role==null){player.sendMessage("Choose a quest character assigned to this world.");return false;}Location at=player.getLocation();if(!usable(at)){player.sendMessage("Choose a clear standing space for the NPC.");return false;}Location old=saved(role,player.getWorld());if(old!=null)old.getChunk().load();LivingEntity npc=existing(role,player.getWorld());if(npc==null){player.sendMessage("The original quest NPC is unavailable; no duplicate was created.");return false;}if(!com.dunerealms.npc.CitizensBridge.teleport(npc,at))return false;save(role,npc);player.sendMessage("Moved "+role.name()+"; its original identity was retained.");return true;}
/** Read-only: where this quest character stands (or will first be placed) in the world, or null when unassigned. */
static Location where(JavaPlugin plugin,String key,World world){Role role=role(key,world);if(role==null)return null;var saved=YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(),"quest-npc-positions.yml"));String at=world.getName()+"."+key;if(saved.contains(at+".x"))return new Location(world,saved.getDouble(at+".x"),saved.getDouble(at+".y"),saved.getDouble(at+".z"));return role.world().equals("arrakis")&&fixedSmuggler(key)?null:initial(role,world);}
boolean move(Player player,String key){if(!player.hasPermission("dune.admin")){player.sendMessage("Current NPC administration permission required.");return false;}Role role=role(key,player.getWorld());if(role==null){player.sendMessage("Choose a quest character assigned to this world.");return false;}Location at=player.getLocation();if(fixedSmuggler(key)&&role.world().equals("arrakis")){String other=key.equals(DELIVERY_CONTACT)?"esmar_tuek":DELIVERY_CONTACT;Location station=saved(role(other,player.getWorld()),player.getWorld());if(station!=null&&!deliverySeparation(station,at)){player.sendMessage("The two fixed smuggler contacts must stay at least 64 blocks apart.");return false;}}if(!usable(at)){player.sendMessage("Choose a clear standing space for the NPC.");return false;}Location old=saved(role,player.getWorld());if(old!=null)old.getChunk().load();LivingEntity npc=existing(role,player.getWorld());if(npc==null){player.sendMessage("The original quest NPC is unavailable; no duplicate was created.");return false;}if(!com.dunerealms.npc.CitizensBridge.teleport(npc,at))return false;save(role,npc);player.sendMessage("Moved "+role.name()+"; its original identity was retained.");return true;}
@EventHandler public void world(WorldLoadEvent e){Bukkit.getScheduler().runTaskLater(plugin,()->ensure(e.getWorld()),100);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=false) public void interact(PlayerInteractEntityEvent e){String id=e.getRightClicked().getPersistentDataContainer().get(KEY,PersistentDataType.STRING);if(id==null)return;Role role=role(id,e.getPlayer().getWorld());if(role==null)return;if(id.equals("esmar_tuek")&&role.world().equals("arrakis")&&!e.getPlayer().isSneaking()){e.setCancelled(true);if(e.getHand()==EquipmentSlot.HAND)e.getPlayer().performCommand("spice");return;}e.setCancelled(true);if(e.getHand()==EquipmentSlot.HAND)open.accept(e.getPlayer(),role);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=false) public void interact(PlayerInteractEntityEvent e){String id=e.getRightClicked().getPersistentDataContainer().get(KEY,PersistentDataType.STRING);if(id==null)return;Role role=role(id,e.getPlayer().getWorld());if(role==null)return;if(id.equals(DELIVERY_CONTACT)){e.setCancelled(true);if(e.getHand()==EquipmentSlot.HAND){var nativeNpc=Bukkit.getPluginManager().getPlugin("DuneNPC");if(!(nativeNpc instanceof JavaPlugin npc)||!npc.isEnabled()||!npc.getConfig().getBoolean("smugglers.fixed-contracts.enabled",false))e.getPlayer().sendMessage("Delivery contracts are currently unavailable.");}return;}if(id.equals("esmar_tuek")&&role.world().equals("arrakis")&&!e.getPlayer().isSneaking()){e.setCancelled(true);if(e.getHand()==EquipmentSlot.HAND)e.getPlayer().performCommand("spice");return;}e.setCancelled(true);if(e.getHand()==EquipmentSlot.HAND)open.accept(e.getPlayer(),role);}
void nativeContact(Player p,String id){Role r=role(id,p.getWorld());if(r==null&&id.equals("guild_navigator"))r=new Role(id,"Guild Navigator",p.getWorld().getName(),"*",Set.of("guild","spice-harvesting"),0);if(r==null&&id.equals("gurney_halleck"))r=new Role(id,"Gurney Halleck · Bounty jobs",p.getWorld().getName(),"*",Set.of("bounty-jobs","war-service","repeatables"),0);if(r!=null)open.accept(p,r);}
}

View file

@ -10,7 +10,7 @@ final class QuartermasterNpc implements Listener{
if(world.getEnvironment()!=World.Environment.NORMAL&&!world.getName().equals("guild_lobby"))return;
var spawn=world.getSpawnLocation();spawn.getChunk().load();if(world.getEntitiesByClass(LivingEntity.class).stream().anyMatch(e->e.getPersistentDataContainer().has(key,PersistentDataType.BYTE)))return;
var at=spawn.clone().add(3,0,0);if(!at.getBlock().isPassable()||!at.clone().add(0,1,0).getBlock().isPassable()||!at.clone().add(0,-1,0).getBlock().getType().isSolid())at=spawn.clone();
Villager npc=world.spawn(at,Villager.class);npc.setAI(false);npc.setInvulnerable(true);npc.setPersistent(true);npc.setRemoveWhenFarAway(false);npc.setSilent(true);npc.setCollidable(false);npc.setProfession(Villager.Profession.ARMORER);npc.customName(Component.text("Gurney Halleck · Quartermaster",NamedTextColor.GOLD));npc.setCustomNameVisible(true);npc.getPersistentDataContainer().set(key,PersistentDataType.BYTE,(byte)1);
if(!com.dunerealms.npc.CitizensBridge.ready()||com.dunerealms.npc.CitizensBridge.exists(plugin,world,key,"1"))return;com.dunerealms.npc.CitizensBridge.spawnContact(plugin,at,"§6Gurney Halleck · Quartermaster",key,"1",true);
}
@EventHandler public void world(WorldLoadEvent e){Bukkit.getScheduler().runTaskLater(plugin,()->ensure(e.getWorld()),60);}
@EventHandler public void interact(PlayerInteractEntityEvent e){if(!e.getRightClicked().getPersistentDataContainer().has(key,PersistentDataType.BYTE))return;e.setCancelled(true);if(e.getHand()==EquipmentSlot.HAND)open.accept(e.getPlayer());}

View file

@ -18,13 +18,17 @@ import net.kyori.adventure.text.event.ClickEvent;
final class QuestMenus implements Listener {
private final JavaPlugin plugin;private final HouseBridge bridge;private final Consumer<Player> back;
private final Map<UUID,UUID> pending=new HashMap<>();
private final MissionTracker tracker;
private final Map<UUID,JournalView> journals=new HashMap<>();
private static final int PAGE=20;
private static final class JournalView{final String kind;final List<JournalModel.Arc> arcs;final JsonObject data;int arc,page;String selected;JournalView(String kind,List<JournalModel.Arc> arcs,JsonObject data){this.kind=kind;this.arcs=arcs;this.data=data;}}
private final Map<UUID,PolQuestNpc.Role> roleScope=new HashMap<>();
private static final class Panel implements InventoryHolder {
final UUID owner;final GuiSession gate;final Map<Integer,Runnable> actions=new HashMap<>();final List<BedrockForms.Choice> choices=new ArrayList<>();final Inventory inventory;final String title;String description="Your current J.A.R.V.I.S. mission journal";
Panel(Player p,String title){owner=p.getUniqueId();gate=new GuiSession(owner);this.title=title;inventory=Bukkit.createInventory(this,54,Component.text(title,NamedTextColor.GOLD));}
public Inventory getInventory(){return inventory;}
}
QuestMenus(JavaPlugin plugin,HouseBridge bridge,Consumer<Player> back){this.plugin=plugin;this.bridge=bridge;this.back=back;Bukkit.getPluginManager().registerEvents(this,plugin);}
QuestMenus(JavaPlugin plugin,HouseBridge bridge,Consumer<Player> back){this.plugin=plugin;this.bridge=bridge;this.back=back;tracker=new MissionTracker(plugin,bridge);Bukkit.getPluginManager().registerEvents(this,plugin);}
void quartermaster(Player p,Runnable exchange,Runnable kits){var s=panel(p,"Gurney · Quartermaster");put(s,20,"Exchange","Buy and sell individual items",Material.EMERALD,exchange);put(s,22,"Missions & turn-ins","Collect your House T0 kit or repair its original armour.\nPrepare four parts: one iron ingot, leather, copper ingot and quartz.\nOther missions and rewards use your current central journal.",Material.WRITABLE_BOOK,()->open(p));put(s,24,"Stillsuit kits","Published clan, company and office kits",Material.NETHERITE_CHESTPLATE,kits);put(s,31,"Organisation workshop","Upgrade your held original with researched MK and rarity templates",Material.NETHERITE_UPGRADE_SMITHING_TEMPLATE,()->workshop(p,0));put(s,34,"Gurney\u0027s missions","Current bounty, campaign and ongoing duty missions",Material.BOOK,()->openRole(p,new PolQuestNpc.Role("gurney_halleck","Gurney Halleck",p.getWorld().getName(),"*",Set.of("bounty-jobs","war-service","repeatables","rd"),0)));put(s,49,"Close","Return to the world",Material.ARROW,p::closeInventory);show(p,s);}
private static String text(JsonObject row,String key,String fallback){return row.has(key)&&!row.get(key).isJsonNull()?row.get(key).getAsString():fallback;}
private static String dialogue(JsonObject row,String field,String fallback){return row.has("dialogue")&&row.get("dialogue").isJsonObject()?text(row.getAsJsonObject("dialogue"),field,fallback):fallback;}
@ -37,8 +41,8 @@ final class QuestMenus implements Listener {
if(action!=null){panel.actions.put(slot,action);panel.choices.add(new BedrockForms.Choice(title,description,action));}
}
private void show(Player p,Panel screen){if(BedrockForms.isBedrock(p)){BedrockForms.show(plugin,p,screen.title,screen.description,List.copyOf(screen.choices));return;}if(MCGUIMenus.show(p,screen.title,screen.description,screen.inventory,screen.actions,screen.gate))return;p.openInventory(screen.inventory);Bukkit.getScheduler().runTaskLater(plugin,screen.gate::expire,2400L);}
void close(){pending.clear();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Panel)p.closeInventory();}
void open(Player p){roleScope.remove(p.getUniqueId());var screen=panel(p,"Mission journal");put(screen,20,"Personal Experience","Your personal mission branches",Material.BOOK,()->load(p,"personal",null,null,0));put(screen,24,"Reputation","Your Reputation mission branches",Material.ENCHANTED_BOOK,()->load(p,"pol",null,null,0));put(screen,45,"Website Mentat Report","Open your full online journal",Material.MAP,()->website(p));put(screen,49,"Back","Imperial Codex",Material.ARROW,()->back.accept(p));show(p,screen);}
void close(){tracker.close();journals.clear();pending.clear();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Panel)p.closeInventory();}
void open(Player p){roleScope.remove(p.getUniqueId());journals.remove(p.getUniqueId());var screen=panel(p,"Mission journal");put(screen,20,"Personal Experience","Your personal mission branches",Material.BOOK,()->load(p,"personal",null,null,0));put(screen,24,"Reputation","Your Reputation mission branches",Material.ENCHANTED_BOOK,()->load(p,"pol",null,null,0));put(screen,45,"Website Mentat Report","Open your full online journal",Material.MAP,()->website(p));put(screen,49,"Back","Imperial Codex",Material.ARROW,()->back.accept(p));show(p,screen);}
void starterJournal(Player p){roleScope.remove(p.getUniqueId());load(p,"personal","h",null,0);}
void openRole(Player p,PolQuestNpc.Role role){roleScope.put(p.getUniqueId(),role);if(role.branches().contains("prologue")){housePrologue(p,role);return;}load(p,"pol",null,null,0);}
private void housePrologue(Player p,PolQuestNpc.Role role){var input=new JsonObject();input.addProperty("action","read");input.addProperty("kind","personal");input.addProperty("npcRole",role.key());request(p,input,data->{var screen=panel(p,"NPC turn-in · "+role.name());roleAvatar(screen,data,role);var state=data.has("housePrologue")&&data.get("housePrologue").isJsonObject()?data.getAsJsonObject("housePrologue"):new JsonObject();screen.description=text(state,"dialogue","");if(!yes(state,"required")){put(screen,13,"Welcome back","Your established preparation is retained. Use the existing Guild Navigator for passage.",Material.COMPASS,null);}else if(!role.key().equals(text(state,"mentor",""))){put(screen,13,"Choose your House","Meet the adviser of your current House. Visit the existing account and House selection flow.",Material.BOOK,null);put(screen,31,"Open account and House selection","Complete your account and select a House before returning.",Material.MAP,()->{p.closeInventory();p.sendMessage(Component.text("Open your account and House selection →",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl("https://cp.dunerealms.com/")));});}else{put(screen,13,"House Prologue","Account setup: "+(yes(state,"onboarding")?"Verified":"Pending")+"\nProfile: "+(yes(state,"profile")?"Verified":"Pending")+"\nMentat introduction: "+(yes(state,"introduced")?"Verified":"Pending")+"\nStarter equipment: "+(yes(state,"kit")?"Verified":"Pending"),Material.WRITABLE_BOOK,null);if(!yes(state,"introduced"))put(screen,31,"Acknowledge House introduction","Record this matching Mentat interaction. Rewards are issued automatically on verification.",Material.LIME_DYE,()->{try{bridge.houseMentorIntroduction(p,role.key());p.sendMessage("Introduction recorded. Reopen this contact to refresh your verified progress.");}catch(Exception error){p.sendMessage("Return to your matching House Mentat.");}});else if(!yes(state,"kit"))put(screen,31,"Your starter equipment","Open the existing starter objective; retain your original shovel and kit.",Material.WOODEN_SHOVEL,()->{p.closeInventory();p.performCommand("start");});else if(yes(state,"ready"))put(screen,31,"Your first passage is unlocked","Use the existing Guild Navigator to travel to your native world.",Material.COMPASS,null);else put(screen,31,"Finish account preparation","Complete the existing website profile and first sign-in requirements.",Material.MAP,()->{p.closeInventory();p.sendMessage(Component.text("Open your account →",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl("https://cp.dunerealms.com/")));});}put(screen,49,"Refresh","Check your actual progress and automatically recorded rewards",Material.ARROW,()->housePrologue(p,role));show(p,screen);});}
@ -52,11 +56,95 @@ final class QuestMenus implements Listener {
if(ordered.isEmpty())put(screen,13,"No eligible missions","Read the website journal for the full record.",Material.MAP,null);
if(role.key().equals("esmar_tuek")){
put(screen,47,"Smuggler Navigator","Review personal passage to another world.",Material.COMPASS,()->smugglerMenu(p,data,role));
if(role.world().equals("arrakis"))put(screen,48,"Smuggling contracts","Start a delivery with Esmar Tuek",Material.CHEST,()->p.performCommand("dunenpc smuggle contract"));
if(!role.world().equals("guild_lobby"))put(screen,46,"Smuggler return","Return to the recorded origin of your confirmed passage.",
Material.ENDER_PEARL,()->{try{bridge.returnSmuggler(p);}catch(Exception failure){p.sendMessage("Meet Esmar Tuek to confirm your return.");}});
}
if(Set.of("thufir_hawat","piter_de_vries","hasimir_fenring","roma_atani","imperial_attendant","stilgar","jessica_atreides","gaius_helen_mohiam","alia_atreides","edric","guild_navigator","duncan_idaho").contains(role.key()))put(screen,48,"POL decisions","See only current executable political decisions",Material.BOOK,()->roleDecisionDashboard(p,data,role));put(screen,49,"Website journal","Full mission choices and history",Material.MAP,()->website(p));show(p,screen);
}
/** Points the compass at Esmar Tuek and says where he and the roaming smugglers are. */
private void findSmuggler(Player p){
World world=p.getWorld();Location at=world.getName().equals("arrakis")||world.getName().equals("guild_lobby")?PolQuestNpc.where(plugin,"esmar_tuek",world):null;
if(at==null){p.sendMessage("Esmar Tuek can be found near the Arrakis spawn and in the Guild Lobby.");return;}
p.setCompassTarget(at);Location here=p.getLocation();
p.sendMessage("Esmar Tuek: "+Bearing.describe(at.getX()-here.getX(),at.getZ()-here.getZ())+" (X "+at.getBlockX()+" / Z "+at.getBlockZ()+"). Your compass now points to him.");
}
// ---- Mission journal: story arcs on the left, one mission on the right. Browsing never calls the server. ----
private static Material material(String status){return switch(status){case JournalModel.DONE->Material.LIME_DYE;case JournalModel.READY->Material.EMERALD;case JournalModel.ACTIVE->Material.YELLOW_DYE;case JournalModel.AVAILABLE->Material.WRITABLE_BOOK;default->Material.GRAY_DYE;};}
private void divider(Panel screen,int slot){var item=new ItemStack(Material.BLACK_STAINED_GLASS_PANE);var meta=item.getItemMeta();meta.displayName(Component.empty());item.setItemMeta(meta);screen.inventory.setItem(slot,item);}
private void openJournal(Player p,String kind,JsonObject data,String preferred){
var arcs=JournalModel.arcs(data);var view=new JournalView(kind,arcs,data);
view.selected=JournalModel.pick(arcs,preferred,tracker.tracked(p.getUniqueId(),kind));focus(view);
journals.put(p.getUniqueId(),view);tracker.observe(p,kind,arcs);renderJournal(p,view);
}
private void focus(JournalView view){
for(int a=0;a<view.arcs.size();a++){var list=view.arcs.get(a).missions();for(int i=0;i<list.size();i++)if(list.get(i).id().equals(view.selected)){view.arc=a;view.page=i/PAGE;return;}}
view.arc=0;view.page=0;
}
private void renderJournal(Player p,JournalView view){
var screen=panel(p,(view.kind.equals("pol")?"Reputation":"Personal")+" missions");
if(view.arcs.isEmpty()){put(screen,22,"No missions yet","Your journal fills as the season opens.",Material.BARRIER,null);put(screen,49,"Back","Mission journal",Material.ARROW,()->open(p));show(p,screen);return;}
var arc=view.arcs.get(view.arc);var missions=arc.missions();int pages=Math.max(1,(missions.size()+PAGE-1)/PAGE);view.page=Math.max(0,Math.min(view.page,pages-1));
String tracked=tracker.tracked(p.getUniqueId(),view.kind);
for(int row=0;row<5;row++)divider(screen,row*9+4);
for(int i=0;i<PAGE;i++){
int index=view.page*PAGE+i;if(index>=missions.size())break;var m=missions.get(index);int slot=(i/4)*9+(i%4);
String lore=JournalModel.label(m.status())+(m.id().equals(tracked)&&!m.finished()?" · Tracked":"")+(m.finished()?"":"\n"+JournalModel.bar(m.progress(),m.target(),10)+" "+m.percent()+"%");
put(screen,slot,(m.id().equals(view.selected)?"▶ ":"")+m.title(),lore,material(m.status()),()->{view.selected=m.id();renderJournal(p,view);});
}
final var sel=JournalModel.find(view.arcs,view.selected);
if(sel!=null){
String brief=String.join("\n",JournalModel.wrap(JournalModel.briefing(sel.objective(),220),36));
put(screen,5,sel.title(),JournalModel.label(sel.status())+(sel.lockedBy()!=null?"\n"+sel.lockedBy():"")+"\n\n"+brief,material(sel.status()),null);
String goal=String.join("\n",JournalModel.wrap(sel.objective().isBlank()?sel.title():JournalModel.briefing(sel.objective(),120),36))+"\n"+JournalModel.bar(sel.progress(),sel.target(),16)+"\n"+JournalModel.progressText(sel)+" ("+sel.percent()+"%)";
put(screen,14,"Objectives",goal,Material.BOOK,null);
String reward=sel.xp()>=0?(view.kind.equals("pol")?"Reputation: ":"Experience: ")+sel.xp()+" XP":"Reward amount unavailable";
if(!sel.rewardConfigured())reward+="\nReward not configured yet";
put(screen,23,"Rewards",reward,Material.CHEST,null);
boolean isTracked=sel.id().equals(tracked);
if(!sel.finished()&&!JournalModel.LOCKED.equals(sel.status()))put(screen,41,isTracked?"Tracking":"Track",isTracked?"Shown on your boss bar.":"Show this mission on your boss bar.",Material.COMPASS,isTracked?null:()->{tracker.track(p.getUniqueId(),view.kind,sel.id());tracker.observe(p,view.kind,view.arcs);renderJournal(p,view);});
if(!sel.finished()&&!JournalModel.LOCKED.equals(sel.status())&&!sel.webOnly())put(screen,33,"Mission steps","Briefings, turn-ins and special steps\nfor this mission.",Material.BELL,()->{
JsonObject row=null;for(var entry:view.data.getAsJsonArray("quests"))if(sel.id().equals(text(entry.getAsJsonObject(),"id","")))row=entry.getAsJsonObject();
if(row!=null)details(p,view.kind,view.data,text(row,"branch",""),0,row);});
if(sel.webOnly()&&!sel.finished())put(screen,43,"Open website journal","This objective belongs to the website.",Material.MAP,()->website(p));
else{
if(JournalModel.READY.equals(sel.status())&&sel.canClaim())put(screen,42,"Claim reward","Pay out this mission now.",Material.EMERALD,()->journalAct(p,view.kind,sel,"claim"));
if(JournalModel.AVAILABLE.equals(sel.status())&&sel.canStart())put(screen,43,"Start mission","Accept this mission.",Material.LIME_DYE,()->journalAct(p,view.kind,sel,"start"));
}
}
int arcCount=view.arcs.size();
if(arcCount>1){
put(screen,45,"Previous arc",view.arcs.get((view.arc-1+arcCount)%arcCount).title(),Material.ARROW,()->{view.arc=(view.arc-1+arcCount)%arcCount;view.page=0;view.selected=JournalModel.pick(List.of(view.arcs.get(view.arc)),null,null);renderJournal(p,view);});
put(screen,47,"Next arc",view.arcs.get((view.arc+1)%arcCount).title(),Material.ARROW,()->{view.arc=(view.arc+1)%arcCount;view.page=0;view.selected=JournalModel.pick(List.of(view.arcs.get(view.arc)),null,null);renderJournal(p,view);});
}
put(screen,46,arc.title(),arc.done()+" of "+arc.missions().size()+" done"+(arc.complete()?" · arc complete":""),Material.PAPER,null);
if(pages>1){
if(view.page>0)put(screen,50,"Previous page","Page "+view.page+" of "+pages,Material.PAPER,()->{view.page--;renderJournal(p,view);});
if(view.page<pages-1)put(screen,51,"Next page","Page "+(view.page+2)+" of "+pages,Material.PAPER,()->{view.page++;renderJournal(p,view);});
}
put(screen,49,"Back","Mission journal",Material.ARROW,()->open(p));put(screen,53,"Website journal","Open your full online journal",Material.MAP,()->website(p));
show(p,screen);
}
private void journalAct(Player p,String kind,JournalModel.Mission m,String action){
var input=new JsonObject();input.addProperty("action",action);input.addProperty("kind",kind);input.addProperty("definitionId",m.id());input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("confirmed",true);
if(action.equals("claim"))input.addProperty("revision",m.revision());
request(p,input,result->{
p.sendMessage(Component.text(action.equals("claim")?"Verified quest reward recorded.":"Mission accepted.",NamedTextColor.GREEN));
if(action.equals("claim")&&m.id().equals("S1-H-02"))try{bridge.refreshKits(p);}catch(Exception unavailable){p.sendMessage("Your intact replacement remains queued for delivery.");}
String next=action.equals("claim")&&result.has("nextQuestId")&&!result.get("nextQuestId").isJsonNull()?result.get("nextQuestId").getAsString():null;
journalReload(p,kind,next!=null?next:m.id(),m.id(),action.equals("claim"));
});
}
private void journalReload(Player p,String kind,String preferred,String fromId,boolean advance){
var read=new JsonObject();read.addProperty("action","read");read.addProperty("kind",kind);
request(p,read,data->{
if(!"active".equals(text(data,"state",""))){open(p);return;}
var arcs=JournalModel.arcs(data);String pick=preferred;
if(advance&&(preferred==null||preferred.equals(fromId))){String next=JournalModel.nextInArc(arcs,fromId);if(next!=null)pick=next;}
openJournal(p,kind,data,pick);
});
}
private void smugglerRequest(Player p,JsonObject input,Consumer<JsonObject> callback){try{bridge.questCharacterNpc(p,"esmar_tuek");}catch(Exception unavailable){p.sendMessage("Meet Esmar Tuek first.");return;}UUID id=p.getUniqueId(),world=p.getWorld().getUID(),operation=UUID.randomUUID();if(pending.putIfAbsent(id,operation)!=null)return;p.closeInventory();Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject result=null;String error=null;try{if(text(input,"action","").equals("smuggler_board")&&!bridge.worldOnline(text(input,"destination","")))throw new IllegalStateException("That world is currently unavailable.");result=bridge.guild(id,input);}catch(Exception failure){error=failure.getMessage();}var response=result;String message=error;Bukkit.getScheduler().runTask(plugin,()->{if(!pending.remove(id,operation)||!p.isOnline()||!p.getWorld().getUID().equals(world))return;if(response==null){p.sendMessage(message==null?"The smuggler passage is unavailable.":message);return;}callback.accept(response);});});}
private void smugglerMenu(Player p,JsonObject data,PolQuestNpc.Role role){
var input=new JsonObject();input.addProperty("action","smuggler_quote");
@ -148,7 +236,7 @@ final class QuestMenus implements Listener {
Bukkit.getScheduler().runTask(plugin,()->{if(!operation.equals(pending.get(owner)))return;pending.remove(owner);if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(message!=null){p.sendMessage(message);return;}if(p.getOpenInventory().getType()!=InventoryType.CRAFTING)return;result.accept(received);});
});
}
private void load(Player p,String kind,String branch,String selected,int page){var input=new JsonObject();input.addProperty("action","read");input.addProperty("kind",kind);var contact=roleScope.get(p.getUniqueId());if(contact!=null&&kind.equals("pol"))input.addProperty("npcRole",contact.key());request(p,input,data->{if(!"active".equals(text(data,"state",""))){p.sendMessage("No active quest season is available.");open(p);return;}var role=roleScope.get(p.getUniqueId());if(role!=null&&kind.equals("pol")){roleJournal(p,data,role,selected);return;}if(branch==null)branches(p,kind,data);else if(selected==null)quests(p,kind,data,branch,page);else{JsonObject row=null;for(var entry:data.getAsJsonArray("quests"))if(selected.equals(text(entry.getAsJsonObject(),"id","")))row=entry.getAsJsonObject();if(row==null)quests(p,kind,data,branch,page);else details(p,kind,data,branch,page,row);}});}
private void load(Player p,String kind,String branch,String selected,int page){var input=new JsonObject();input.addProperty("action","read");input.addProperty("kind",kind);var contact=roleScope.get(p.getUniqueId());if(contact!=null&&kind.equals("pol"))input.addProperty("npcRole",contact.key());request(p,input,data->{if(!"active".equals(text(data,"state",""))){p.sendMessage("No active quest season is available.");open(p);return;}var role=roleScope.get(p.getUniqueId());if(role!=null&&kind.equals("pol")){roleJournal(p,data,role,selected);return;}if(branch==null)openJournal(p,kind,data,selected);else if(selected==null)quests(p,kind,data,branch,page);else{JsonObject row=null;for(var entry:data.getAsJsonArray("quests"))if(selected.equals(text(entry.getAsJsonObject(),"id","")))row=entry.getAsJsonObject();if(row==null)quests(p,kind,data,branch,page);else details(p,kind,data,branch,page,row);}});}
private void branches(Player p,String kind,JsonObject data){
var screen=panel(p,kind.equals("pol")?"Reputation branches":"Personal mission branches");var branches=new LinkedHashMap<String,String>();for(var entry:data.getAsJsonArray("quests")){String id=text(entry.getAsJsonObject(),"branch","missions");branches.putIfAbsent(id,id);}
if(data.has("branches"))for(var entry:data.getAsJsonArray("branches")){var branch=entry.getAsJsonObject();String id=text(branch,"id","");if(branches.containsKey(id))branches.put(id,text(branch,"title",id));}
@ -173,7 +261,8 @@ final class QuestMenus implements Listener {
else if(yes(row,"canStart")&&!state.equals("active")&&!state.equals("claimed")&&!state.equals("completed"))put(screen,31,"Start mission","Accept this objective through J.A.R.V.I.S.",Material.LIME_DYE,()->act(p,kind,branch,page,row,"start"));
else put(screen,31,state.equals("claimed")?"Reward claimed":"Awaiting verified progress","No reward can be issued from an unverified objective",Material.GRAY_DYE,null);
if(kind.equals("pol")&&Set.of("POL-ELYTRA-REFINE","POL-ELYTRA-CONTAMINATE","POL-SPICE-UPGRADE-REFINE","POL-SPICE-UPGRADE-CONTAMINATE").contains(text(row,"id",""))&&(yes(row,"canStart")||Set.of("active","completed","claimed").contains(state)))put(screen,33,"Refine at NPC","Stand near an Arrakis Smuggler.\nTurn in the ingredients shown in this quest.",Material.ORANGE_DYE,()->refine(p,kind,data,branch,page,row));
if(kind.equals("pol")&&text(row,"id","").equals("POL-SMUGGLERS-01")&&!state.equals("claimed")&&(yes(row,"canStart")||state.equals("active")))put(screen,33,"Meet the underground network","Stand near an Arrakis Smuggler.\nAccept Esmar Tuek’s introduction, then claim the quest.",Material.ORANGE_DYE,()->{try{bridge.smugglerIntroduction(p);p.sendMessage("Introduction recorded. Refresh this quest in a few seconds.");}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit an Arrakis Smuggler first.":failure.getMessage());}});
if(kind.equals("pol")&&text(row,"id","").equals("POL-SMUGGLERS-01")&&!state.equals("claimed")&&(yes(row,"canStart")||state.equals("active")))put(screen,33,"Meet the underground network","Stand near Esmar Tuek (use Find Esmar Tuek).\nAccept the introduction, then claim the quest.",Material.ORANGE_DYE,()->{try{bridge.smugglerIntroduction(p);p.sendMessage("Introduction recorded. Refresh this quest in a few seconds.");}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit Esmar Tuek first.":failure.getMessage());}});
if(kind.equals("pol")&&text(row,"id","").equals("POL-SMUGGLERS-01")&&!state.equals("claimed"))put(screen,35,"Find Esmar Tuek","Points your compass at Esmar Tuek and tells you the way.",Material.COMPASS,()->findSmuggler(p));
if(kind.equals("pol")&&Set.of("POL-BOUNTY-01","POL-BOUNTY-02").contains(text(row,"id",""))&&!state.equals("claimed"))put(screen,33,"View active bounty jobs","On Arrakis, use the native bounty list and accept a target.",Material.MAP,()->{p.closeInventory();p.performCommand("dune bounty");});
if(kind.equals("pol")&&text(row,"id","").equals("POL-ORDOS-03")&&state.equals("active")&&!yes(row,"canClaim"))put(screen,33,"Open Exchange","Buy one item from another seller. The actual settled central payment will verify this mission.",Material.GOLD_INGOT,()->{p.closeInventory();p.performCommand("exchange");});
if(kind.equals("pol")&&row.has("research")&&!state.equals("claimed")&&(yes(row,"canStart")||state.equals("active")||state.equals("completed")))put(screen,33,"Submit research samples","Stand near Gurney Halleck.\nSurrender the materials shown in this quest.",Material.SMITHING_TABLE,()->research(p,kind,branch,page,row));
@ -186,9 +275,9 @@ final class QuestMenus implements Listener {
if(text(row,"id","").equals("S1-H-02")){put(screen,29,"Prepare four repair parts","Buy, craft with genuine spice or collect native 5% mob drops.\nRepair plate, Binding patch, Tool fitting, Calibration piece.\nOptional: prepare all four from the ordinary materials.",Material.IRON_INGOT,()->starter(p,kind,branch,page,row,"parts"));put(screen,33,"Surrender original kit & parts","Hand in the four original bound armour pieces\nand all four verified repair parts.\nThen claim this quest to receive the intact kit.",Material.ANVIL,()->starter(p,kind,branch,page,row,"repair"));}
}
if(row.has("recipe")&&!row.get("recipe").isJsonNull())put(screen,22,"Revealed recipe","Craft on Arrakis · Very Rare · MK XI\nNetherite | Membrane | Netherite\nIron | Diamond | Iron\nContaminated spice | Membrane | Contaminated spice",Material.ELYTRA,null);
put(screen,45,"Back","Mission selection",Material.ARROW,()->{var currentRole=roleScope.get(p.getUniqueId());if(currentRole!=null&&kind.equals("pol"))roleJournal(p,data,currentRole,null);else quests(p,kind,data,branch,page);});put(screen,49,"Refresh","Read current progress",Material.CLOCK,()->load(p,kind,branch,text(row,"id",""),page));show(p,screen);
put(screen,45,"Back","Mission selection",Material.ARROW,()->{var currentRole=roleScope.get(p.getUniqueId());if(currentRole!=null&&kind.equals("pol"))roleJournal(p,data,currentRole,null);else if(journals.containsKey(p.getUniqueId()))journalReload(p,kind,text(row,"id",""),text(row,"id",""),false);else quests(p,kind,data,branch,page);});if(!journals.containsKey(p.getUniqueId()))put(screen,49,"Refresh","Read current progress",Material.CLOCK,()->load(p,kind,branch,text(row,"id",""),page));show(p,screen);
}
private void refine(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_refine");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.refinerNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.refineSpice(p,permit);p.sendMessage(Component.text("Spice refined. Your quest receipt is queued for confirmation.",NamedTextColor.GREEN));load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Refinement unavailable. Reopen the quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Visit an Arrakis Smuggler first.":failure.getMessage(),NamedTextColor.RED));}}
private void refine(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_refine");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.refinerNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.refineSpice(p,permit);p.sendMessage(Component.text("Spice refined. Your quest receipt is queued for confirmation.",NamedTextColor.GREEN));load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Refinement unavailable. Reopen the quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Visit Esmar Tuek first.":failure.getMessage(),NamedTextColor.RED));}}
private void research(Player p,String kind,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_research");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.starterNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.research(p,permit);load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Research receipt pending. Refresh your quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Visit Gurney Halleck.":failure.getMessage(),NamedTextColor.RED));}}
private void meatTurnin(Player p,String kind,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_husbandry_turnin");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.questCharacterNpc(p,"shadout_mapes").toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.husbandryTurnin(p,permit);load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Meat turn-in not confirmed.":failure.getMessage());}});}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit Shadout Mapes on Arrakis.":failure.getMessage());}}
private void supplyTurnin(Player p,String kind,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_pol_supply");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.questCharacterNpc(p,row.getAsJsonObject("supply").get("role").getAsString()).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.polSupplyTurnin(p,permit);load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Supply turn-in not confirmed.":failure.getMessage());}});}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit the named quest contact.":failure.getMessage());}}

View file

@ -0,0 +1,9 @@
package com.dunerealms.gui;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class BearingTest {
@Test void pointsFollowMinecraftAxes(){assertEquals("north",Bearing.direction(0,-10));assertEquals("east",Bearing.direction(10,0));assertEquals("south",Bearing.direction(0,10));assertEquals("west",Bearing.direction(-10,0));assertEquals("south-east",Bearing.direction(10,10));}
@Test void describesDistanceAndDirection(){assertEquals("100 blocks east",Bearing.describe(100,0));assertEquals("right beside you",Bearing.describe(1,2));}
}

View file

@ -0,0 +1,15 @@
package com.dunerealms.gui;
import org.bukkit.Location;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FixedSmugglerContactTest {
@Test void contactsMustBeAtLeastSixtyFourBlocksApartHorizontally() {
var origin = new Location(null, 10, 64, 10);
assertFalse(PolQuestNpc.deliverySeparation(origin, new Location(null, 73, 180, 10)));
assertTrue(PolQuestNpc.deliverySeparation(origin, new Location(null, 74, 64, 10)));
assertTrue(PolQuestNpc.deliverySeparation(origin, new Location(null, 10, 64, -54)));
}
}

View file

@ -3,10 +3,12 @@ import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.UUID;
class GuildBookingsTest {
@Test void centralQuoteCanAddOnlyArrakisAndDoesNotChangeOrdinaryHouseRoutes(){
@Test void openTravelBooksAnyQuotedWorldButNeverAnUnquotedOne(){
var permit=new GuildBookings.Permit("atreides",UUID.randomUUID(),1);var bookings=new GuildBookings();
var booking=bookings.book(UUID.randomUUID(),permit,"arrakis",100,0,java.util.Set.of("caladan","arrakis"));assertTrue(booking.matches(permit,100,1));assertFalse(GuildRoutes.allowed("atreides","arrakis"));
assertThrows(IllegalArgumentException.class,()->bookings.book(UUID.randomUUID(),permit,"kaitain",100,0,java.util.Set.of("kaitain")));
assertTrue(bookings.book(UUID.randomUUID(),permit,"kaitain",100,0,java.util.Set.of("kaitain")).matches(permit,100,1));
assertThrows(IllegalArgumentException.class,()->bookings.book(UUID.randomUUID(),permit,"kaitain",100,0,java.util.Set.of("caladan")));
assertThrows(IllegalArgumentException.class,()->bookings.book(UUID.randomUUID(),permit,"nowhere",100,0,java.util.Set.of("nowhere")));
}
private final GuildBookings.Permit atreides=new GuildBookings.Permit("atreides",UUID.randomUUID(),1);
@Test void fiveCanonicalHouseRoutesNeverGrantAnotherHouseDestination(){

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