Integrate Wild Update quests and Citizens contacts
This commit is contained in:
parent
018d776874
commit
f46b26d956
1 changed files with 919 additions and 81 deletions
|
|
@ -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);}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff