package com.dunerealms.gui; import java.io.File; import java.nio.file.*; import java.util.*; import java.util.function.BiConsumer; import org.bukkit.*; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.*; import org.bukkit.event.*; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.persistence.PersistentDataType; import org.bukkit.plugin.java.JavaPlugin; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; 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 branches,int offset){} private static final String DELIVERY_CONTACT="staban_tuek"; private static final List ROLES=List.of( new Role("war_marshal","War Marshal","caladan","*",Set.of(),-18), new Role("war_marshal","War Marshal","giedi_prime","*",Set.of(),-12), new Role("war_marshal","War Marshal","kaitain","*",Set.of(),-15), new Role("war_marshal","War Marshal","sigma_draconis_iv","*",Set.of(),-9), new Role("war_marshal","War Marshal","arrakis","*",Set.of(),-24), new Role("war_marshal","War Marshal","guild_lobby","*",Set.of(),-27), new Role("thufir_hawat","Thufir Hawat","caladan","atreides",Set.of("atreides"),-3), new Role("duncan_idaho","Duncan Idaho","caladan","*",Set.of("clan"),-6), new Role("piter_de_vries","Piter de Vries","giedi_prime","harkonnen",Set.of("harkonnen"),-3), new Role("glossu_rabban","Glossu Rabban","giedi_prime","harkonnen",Set.of(),-6), new Role("hasimir_fenring","Count Hasimir Fenring","kaitain","corrino",Set.of("corrino"),-3), new Role("imperial_attendant","Imperial audience · Representation","kaitain","corrino",Set.of("imperial"),-6), new Role("irulan_corrino","Princess Irulan Corrino","kaitain","corrino",Set.of(),-9), new Role("roma_atani","Roma Atani","sigma_draconis_iv","ordos",Set.of("ordos","company"),-3), new Role("stilgar","Stilgar","arrakis","fremen",Set.of("fremen"),-3), new Role("shadout_mapes","Shadout Mapes · Provisioner","arrakis","fremen",Set.of("fremen-husbandry"),-6), new Role("chani","Chani · Desert survival","arrakis","fremen",Set.of("fremen-husbandry"),-9), new Role("liet_kynes","Liet-Kynes · Ecology","arrakis","fremen",Set.of("fremen-husbandry"),-12), new Role("jessica_atreides","Lady Jessica Atreides","caladan","*",Set.of("bene"),-9), new Role("gaius_helen_mohiam","Gaius Helen Mohiam","caladan","*",Set.of("faith-sisterhood"),-12), new Role("alia_atreides","Alia Atreides","arrakis","*",Set.of("faith-church"),-15), new Role("thufir_hawat","Thufir Hawat · House introduction","guild_lobby","atreides",Set.of("prologue"),-9), new Role("piter_de_vries","Piter de Vries · House introduction","guild_lobby","harkonnen",Set.of("prologue"),-12), new Role("hasimir_fenring","Count Hasimir Fenring · House introduction","guild_lobby","corrino",Set.of("prologue"),-15), new Role("roma_atani","Roma Atani · House introduction","guild_lobby","ordos",Set.of("prologue"),-18), 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 open;private final File file;private final YamlConfiguration positions; private UUID imperialUuid;private String imperialName,imperialTerm;private long imperialRetry; PolQuestNpc(JavaPlugin plugin,BiConsumer open){this.plugin=plugin;this.open=open;file=new File(plugin.getDataFolder(),"quest-npc-positions.yml");positions=YamlConfiguration.loadConfiguration(file);Bukkit.getPluginManager().registerEvents(this,plugin);Bukkit.getScheduler().runTaskLater(plugin,()->Bukkit.getWorlds().forEach(this::ensure),100);} private static List roles(JavaPlugin plugin,World world){var all=new ArrayList<>(ROLES);all.addAll(LetoQuestContacts.roles(plugin,world));return all;} private static Role role(JavaPlugin plugin,String id,World world){return roles(plugin,world).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",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 tabr=LetoQuestContacts.tabrLocation(role.key(),world);if(tabr!=null){for(int dy:new int[]{0,1,-1,2,-2})for(int dx:new int[]{0,1,-1,2,-2})for(int dz:new int[]{0,1,-1,2,-2}){Location at=tabr.clone().add(dx,dy,dz);if(usable(at)&&!at.getBlock().isLiquid()&&!at.clone().add(0,1,0).getBlock().isLiquid())return at;}return null;}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());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);} 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(plugin,"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(plugin,world)){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&&role.key().startsWith("leto_")&&LetoQuestContacts.tabrLocation(role.key(),world)==null)at=findSurfaceContact(world,world.getSpawnLocation(),new int[]{8,12,16,24,32});} }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(){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. */}});}); } /** 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(plugin,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(plugin,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(plugin,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(plugin,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(plugin,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);} }