Fresh production baseline [skip ci]

This commit is contained in:
DuneRealms 2026-11-27 23:43:05 +00:00
commit 0a11a18274
20 changed files with 229644 additions and 0 deletions

View file

@ -0,0 +1,114 @@
package com.example.duneterrain;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import org.bukkit.*;
import org.bukkit.attribute.*;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.entity.*;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.block.BlockCookEvent;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.inventory.*;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.*;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
/** Arrakis wildlife only. Native animal AI, growth and breeding remain the engine. */
public final class ArrakisEcology implements Listener {
private static final Map<Plugin,ArrakisEcology> INSTANCES=new WeakHashMap<>();
private static final NamespacedKey PET=new NamespacedKey("dunerealms","tiny_worm_pet"),BOOST=new NamespacedKey("dunerealms","worm_water_until"),DAMAGE=new NamespacedKey("dunerealms","worm_water_damage"),HEALTH=new NamespacedKey("dunerealms","worm_water_health"),EI=new NamespacedKey("executableitems","ei-id");
interface Items {ItemStack build(String id)throws ReflectiveOperationException;}
private final Plugin plugin;private final Items items;private final java.util.function.DoubleSupplier random;private JerboaMobs jerboas;private ChukkaMobs chukkas;
private ArrakisEcology(Plugin plugin){this(plugin,ArrakisEcology::item,()->ThreadLocalRandom.current().nextDouble());}
ArrakisEcology(Plugin plugin,Items items,java.util.function.DoubleSupplier random){this.plugin=plugin;this.items=items;this.random=random;}
public static void start(Plugin plugin){if(INSTANCES.containsKey(plugin))return;var feature=new ArrakisEcology(plugin);INSTANCES.put(plugin,feature);Bukkit.getPluginManager().registerEvents(feature,plugin);feature.jerboas=new JerboaMobs(plugin,feature.items,feature.random);feature.jerboas.start();feature.chukkas=new ChukkaMobs(plugin,feature.items);feature.chukkas.start();Bukkit.getScheduler().runTaskTimer(plugin,feature::maintain,20,20);plugin.getLogger().info("Arrakis ecology registered; native item verification pending");Bukkit.getScheduler().runTaskLater(plugin,feature::verifyDefinitions,20);}
private void verifyDefinitions(){for(String id:List.of("jerboa_raw_meat","jerboa_cooked_meat","jerboa_stew","jerboa_hide","jerboa_water_vial","polluted_refined_spice","worm_memorial_bone"))try{var stack=items.build(id);if(stack==null||!id.equals(itemId(stack)))throw new ReflectiveOperationException("Native item identity mismatch");}catch(ReflectiveOperationException|LinkageError failure){plugin.getLogger().severe("Arrakis ecology item verification failed for "+id+": "+failure.getClass().getSimpleName());return;}plugin.getLogger().info("Arrakis ecology verified all seven native item definitions");}
private static boolean arrakis(Entity e){return e.getWorld().getName().equalsIgnoreCase("arrakis");}
private static boolean pet(Entity e){return e instanceof Wolf&&e.getPersistentDataContainer().has(PET,PersistentDataType.BYTE);}
private static String itemId(ItemStack stack){return stack==null||!stack.hasItemMeta()?null:stack.getItemMeta().getPersistentDataContainer().get(EI,PersistentDataType.STRING);}
private static final int NATURAL_SPECIES_LIMIT=15;
private static boolean natural(CreatureSpawnEvent.SpawnReason reason){return reason==CreatureSpawnEvent.SpawnReason.NATURAL||reason.name().equals("CHUNK_GEN");}
static boolean naturalAllowance(World world,boolean chukka){return world.getLivingEntities().stream().filter(e->chukka?ChukkaMobs.isChukka(e):e instanceof Rabbit||JerboaMobs.isJerboa(e)).limit(NATURAL_SPECIES_LIMIT).count()<NATURAL_SPECIES_LIMIT;}
static boolean retiredSmuggler(Entity e){return arrakis(e)&&e instanceof WanderingTrader&&e.getPersistentDataContainer().has(new NamespacedKey("dunecore","smuggler"),PersistentDataType.BYTE)&&!e.getPersistentDataContainer().has(new NamespacedKey("dunerealms","quest_character"),PersistentDataType.STRING);}
private static boolean questNpc(LivingEntity e){return (e.getType()!=null&&e.getType().name().equals("MANNEQUIN"))||e.getPersistentDataContainer().has(new NamespacedKey("dunerealms","quest_character"),PersistentDataType.STRING);}
private static boolean protectedMob(LivingEntity e){return questNpc(e)||!(e instanceof Mob)||pet(e)||e.customName()!=null||e.hasMetadata("NPC")||!e.getPersistentDataContainer().getKeys().isEmpty()||e instanceof Tameable t&&t.isTamed();}
private static void jerboa(Rabbit rabbit){rabbit.customName(Component.text("Jerboa",NamedTextColor.YELLOW));rabbit.setRabbitType(Rabbit.Type.GOLD);var speed=rabbit.getAttribute(Attribute.MOVEMENT_SPEED);if(speed!=null)speed.setBaseValue(speed.getDefaultValue()*.75);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void spawning(CreatureSpawnEvent event){
var e=event.getEntity();if(!arrakis(e)||questNpc(e))return;
if(e instanceof Rabbit rabbit){
var reason=event.getSpawnReason();
if(natural(reason)){
double roll=random.getAsDouble();
if(roll>=.25){
event.setCancelled(true);
// A small fraction of native desert animal opportunities become Chukka.
if(roll<.40&&chukkas!=null&&naturalAllowance(e.getWorld(),true)&&e.getNearbyEntities(16,8,16).stream().filter(ChukkaMobs::isChukka).count()<4){
Location at=e.getLocation();Bukkit.getScheduler().runTask(plugin,()->{if(at.getWorld()!=null&&naturalAllowance(at.getWorld(),true))chukkas.spawn(at);});
}
return;
}
if(!naturalAllowance(e.getWorld(),false)||e.getNearbyEntities(16,8,16).stream().filter(JerboaMobs::isJerboa).count()>=4){event.setCancelled(true);return;}
}
jerboa(rabbit);return;
}
if(e instanceof Chicken chicken){
var reason=event.getSpawnReason();
if(natural(reason)&&!naturalAllowance(e.getWorld(),true)){event.setCancelled(true);return;}
if(ChukkaMobs.isChukka(chicken)||natural(reason)||reason==CreatureSpawnEvent.SpawnReason.BREEDING||reason==CreatureSpawnEvent.SpawnReason.EGG){ChukkaMobs.prepare(chicken);return;}
}
if(e instanceof Camel){var reason=event.getSpawnReason();if((reason==CreatureSpawnEvent.SpawnReason.NATURAL||reason.name().equals("CHUNK_GEN"))&&!protectedMob(e)&&random.getAsDouble()>=.5)event.setCancelled(true);return;}
if(event.getSpawnReason()!=CreatureSpawnEvent.SpawnReason.CUSTOM&&!protectedMob(e))event.setCancelled(true);
}
@EventHandler(priority=EventPriority.MONITOR) public void loaded(com.destroystokyo.paper.event.entity.EntityAddToWorldEvent event){
if(!(event.getEntity() instanceof LivingEntity e)||e instanceof Player||!arrakis(e)||questNpc(e))return;
if(retiredSmuggler(e)){Bukkit.getScheduler().runTask(plugin,()->{if(e.isValid()&&retiredSmuggler(e))e.remove();});return;}
Bukkit.getScheduler().runTask(plugin,()->{if(!e.isValid()||questNpc(e))return;if(e instanceof Rabbit rabbit)jerboa(rabbit);else if(pet(e))restoreWater((Wolf)e);else if(!(e instanceof Camel)&&!protectedMob(e))e.remove();});
}
private void maintain(){for(var world:Bukkit.getWorlds()){for(var e:world.getEntitiesByClass(Wolf.class))if(pet(e))restoreWater(e);if(world.getName().equalsIgnoreCase("arrakis"))for(var trader:world.getEntitiesByClass(WanderingTrader.class))if(retiredSmuggler(trader))trader.remove();}}
/** Called at the existing bloom announcement; chunk PDC prevents duplicate pets. */
public static void bloom(Plugin plugin,Location location){var instance=INSTANCES.get(plugin);if(instance==null||location==null||location.getWorld()==null||!location.getWorld().getName().equalsIgnoreCase("arrakis"))return;instance.spawnBloomPet(location);}
private void spawnBloomPet(Location location){
var chunk=location.getChunk();var marker=new NamespacedKey(plugin,"worm_bloom_"+location.getBlockX()+"_"+location.getBlockY()+"_"+location.getBlockZ());if(chunk.getPersistentDataContainer().has(marker,PersistentDataType.BYTE))return;
for(int[] offset:new int[][]{{3,0},{-3,0},{0,3},{0,-3},{4,4}}){int x=location.getBlockX()+offset[0],z=location.getBlockZ()+offset[1];World world=location.getWorld();if(!world.isChunkLoaded(x>>4,z>>4))continue;int y=world.getHighestBlockYAt(x,z);var ground=world.getBlockAt(x,y,z);if(!ground.getType().isSolid()||Set.of(Material.MAGMA_BLOCK,Material.CACTUS,Material.CAMPFIRE,Material.SOUL_CAMPFIRE).contains(ground.getType())||!world.getBlockAt(x,y+1,z).isPassable()||!world.getBlockAt(x,y+2,z).isPassable())continue;
world.spawn(new Location(world,x+.5,y+1,z+.5),Wolf.class,w->{w.getPersistentDataContainer().set(PET,PersistentDataType.BYTE,(byte)1);w.setVariant(Wolf.Variant.SNOWY);w.setBaby();w.setRemoveWhenFarAway(false);w.customName(Component.text("Tiny worm",NamedTextColor.GOLD));});chunk.getPersistentDataContainer().set(marker,PersistentDataType.BYTE,(byte)1);return;
}
}
private static void consume(Player p,EquipmentSlot hand){if(p.getGameMode()==GameMode.CREATIVE)return;var inv=p.getInventory();var item=inv.getItem(hand);if(item!=null){item.setAmount(item.getAmount()-1);inv.setItem(hand,item);}}
private static void container(Player player,Material material){if(player.getGameMode()!=GameMode.CREATIVE)for(var rest:player.getInventory().addItem(new ItemStack(material)).values())player.getWorld().dropItemNaturally(player.getLocation(),rest);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void feed(PlayerInteractEntityEvent event){
var player=event.getPlayer();var entity=event.getRightClicked();if(!arrakis(entity))return;var stack=player.getInventory().getItem(event.getHand());String id=itemId(stack);
if(entity instanceof Rabbit rabbit){event.setCancelled(true);if("refined_spice".equals(id)&&rabbit.isAdult()&&rabbit.canBreed()&&rabbit.getLoveModeTicks()==0){rabbit.setLoveModeTicks(600);consume(player,event.getHand());}return;}
if(!(entity instanceof Wolf wolf)||!pet(wolf))return;
if("jerboa_stew".equals(id)){
event.setCancelled(true);boolean newlyTamed=!wolf.isTamed();if(newlyTamed){var tame=new EntityTameEvent(wolf,player);Bukkit.getPluginManager().callEvent(tame);if(tame.isCancelled())return;wolf.setOwner(player);wolf.setSitting(false);wolf.getWorld().spawnParticle(Particle.HEART,wolf.getLocation().add(0,.5,0),7,.3,.3,.3);}
else if(wolf.getHealth()<wolf.getAttribute(Attribute.MAX_HEALTH).getValue())wolf.setHealth(Math.min(wolf.getAttribute(Attribute.MAX_HEALTH).getValue(),wolf.getHealth()+8));
else if(wolf.isAdult()&&wolf.canBreed()&&wolf.getLoveModeTicks()==0)wolf.setLoveModeTicks(600);else return;
consume(player,event.getHand());container(player,Material.BOWL);if(newlyTamed&&player.getUniqueId().equals(wolf.getOwnerUniqueId()))FaunaProof.milestone(player,"husbandry_tiny_worm",wolf.getUniqueId());return;
}
if("jerboa_water_vial".equals(id)&&wolf.isTamed()&&player.getUniqueId().equals(wolf.getOwnerUniqueId())){event.setCancelled(true);water(wolf,System.currentTimeMillis());consume(player,event.getHand());container(player,Material.GLASS_BOTTLE);}
else if(stack!=null&&(stack.getType().isEdible()||stack.getType()==Material.BONE))event.setCancelled(true);
}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void breed(EntityBreedEvent event){
if(!(event.getEntity() instanceof Wolf child)||!arrakis(child)||!pet(event.getMother())||!pet(event.getFather()))return;
var mother=(Wolf)event.getMother();child.getPersistentDataContainer().set(PET,PersistentDataType.BYTE,(byte)1);child.setOwner(mother.getOwner());child.setVariant(Wolf.Variant.SNOWY);child.setBaby();child.setRemoveWhenFarAway(false);child.customName(Component.text("Tiny worm",NamedTextColor.GOLD));
}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void suffocation(EntityDamageEvent event){if(pet(event.getEntity())&&event.getCause()==EntityDamageEvent.DamageCause.SUFFOCATION)event.setCancelled(true);}
private static void modifier(Wolf wolf,Attribute attribute,NamespacedKey key,boolean enabled){var instance=wolf.getAttribute(attribute);if(instance==null)return;var old=instance.getModifier(key);if(enabled&&old==null)instance.addModifier(new AttributeModifier(key,.25,AttributeModifier.Operation.ADD_SCALAR));else if(!enabled&&old!=null)instance.removeModifier(old);}
private static void water(Wolf wolf,long now){boolean fresh=wolf.getPersistentDataContainer().getOrDefault(BOOST,PersistentDataType.LONG,0L)<=now;double before=wolf.getHealth();wolf.getPersistentDataContainer().set(BOOST,PersistentDataType.LONG,now+90000);modifier(wolf,Attribute.ATTACK_DAMAGE,DAMAGE,true);modifier(wolf,Attribute.MAX_HEALTH,HEALTH,true);if(fresh)wolf.setHealth(Math.min(wolf.getAttribute(Attribute.MAX_HEALTH).getValue(),before*1.25));var old=wolf.getPotionEffect(PotionEffectType.REGENERATION);if(old==null||old.getAmplifier()==0)wolf.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION,1800,0));}
private static void restoreWater(Wolf wolf){if(wolf.getVariant()!=Wolf.Variant.SNOWY)wolf.setVariant(Wolf.Variant.SNOWY);long until=wolf.getPersistentDataContainer().getOrDefault(BOOST,PersistentDataType.LONG,0L),remaining=until-System.currentTimeMillis();boolean active=remaining>0;modifier(wolf,Attribute.ATTACK_DAMAGE,DAMAGE,active);modifier(wolf,Attribute.MAX_HEALTH,HEALTH,active);var regen=wolf.getPotionEffect(PotionEffectType.REGENERATION);if(active&&(regen==null||regen.getAmplifier()==0))wolf.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION,(int)Math.min(1800,Math.max(1,(remaining+49)/50)),0),true);if(!active){if(until>0&&regen!=null&&regen.getAmplifier()==0)wolf.removePotionEffect(PotionEffectType.REGENERATION);wolf.getPersistentDataContainer().remove(BOOST);wolf.setHealth(Math.min(wolf.getHealth(),wolf.getAttribute(Attribute.MAX_HEALTH).getValue()));}}
@EventHandler(priority=EventPriority.HIGHEST) public void death(EntityDeathEvent event){
var entity=event.getEntity();if(!arrakis(entity))return;
try{
if(entity instanceof Rabbit){var raw=items.build(entity.getFireTicks()>0?"jerboa_cooked_meat":"jerboa_raw_meat");var hide=items.build("jerboa_hide");FaunaProof.markDrop(hide,entity.getUniqueId());var drops=new ArrayList<ItemStack>();drops.add(raw);drops.add(hide);if(random.getAsDouble()<.2)drops.add(items.build("blood_vial"));if(random.getAsDouble()<.02)drops.add(items.build("jerboa_water_vial"));event.getDrops().clear();event.getDrops().addAll(drops);}
else if(pet(entity)){var bone=items.build("worm_memorial_bone");var meta=bone.getItemMeta();var name=entity.customName()==null?Component.text("Tiny worm"):entity.customName();meta.displayName(name.append(Component.text(" · Memorial bone",NamedTextColor.GOLD)));bone.setItemMeta(meta);var spice=new ItemStack(Material.ORANGE_DYE);var sm=spice.getItemMeta();sm.displayName(Component.text("Melange Spice",NamedTextColor.GOLD));sm.getPersistentDataContainer().set(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING,"spice");sm.getPersistentDataContainer().set(new NamespacedKey("dunerealms","origin_world"),PersistentDataType.STRING,"arrakis");spice.setItemMeta(sm);event.getDrops().clear();event.getDrops().add(spice);event.getDrops().add(bone);}
}catch(ReflectiveOperationException failure){plugin.getLogger().severe("Native Arrakis item definition unavailable: "+failure.getClass().getSimpleName());}
}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void cook(BlockCookEvent event){if(!event.getBlock().getWorld().getName().equalsIgnoreCase("arrakis"))return;String source=itemId(event.getSource());String result="jerboa_raw_meat".equals(source)?"jerboa_cooked_meat":"chukka_raw_meat".equals(source)?"chukka_cooked_meat":null;if(result==null)return;try{event.setResult(items.build(result));}catch(ReflectiveOperationException failure){event.setCancelled(true);plugin.getLogger().warning("Fauna cooking definition unavailable; input retained");}}
private static ItemStack item(String id)throws ReflectiveOperationException{var score=Bukkit.getPluginManager().getPlugin("SCore");if(score==null||!score.isEnabled())throw new ReflectiveOperationException("Native item engine unavailable");var loader=score.getClass().getClassLoader();var api=loader.loadClass("com.ssomar.score.api.executableitems.ExecutableItemsAPI");var manager=api.getMethod("getExecutableItemsManager").invoke(null);var managerAPI=loader.loadClass("com.ssomar.score.api.executableitems.config.ExecutableItemsManagerInterface");var definition=(Optional<?>)managerAPI.getMethod("getExecutableItem",String.class).invoke(manager,id);if(definition.isEmpty())throw new ReflectiveOperationException("Missing native item definition");var itemAPI=loader.loadClass("com.ssomar.score.api.executableitems.config.ExecutableItemInterface");var built=(ItemStack)itemAPI.getMethod("buildItem",int.class,Optional.class,Optional.class).invoke(definition.get(),1,Optional.empty(),Optional.empty());var origin=built.getItemMeta();origin.getPersistentDataContainer().set(new NamespacedKey("dunerealms","origin_world"),PersistentDataType.STRING,"arrakis");built.setItemMeta(origin);var translator=Bukkit.getPluginManager().getPlugin("JarvisTranslator");if(translator!=null&&translator.isEnabled())try{translator.getClass().getMethod("markCreatedItem",ItemStack.class).invoke(translator,built);}catch(NoSuchMethodException olderTranslator){/* Old translators still receive the stable origin field. */}return built;}
@EventHandler public void disable(PluginDisableEvent event){if(event.getPlugin()!=plugin)return;INSTANCES.remove(plugin);if(jerboas!=null)jerboas.close();for(var world:Bukkit.getWorlds())for(var wolf:world.getEntitiesByClass(Wolf.class))if(pet(wolf)){modifier(wolf,Attribute.ATTACK_DAMAGE,DAMAGE,false);modifier(wolf,Attribute.MAX_HEALTH,HEALTH,false);wolf.setHealth(Math.min(wolf.getHealth(),wolf.getAttribute(Attribute.MAX_HEALTH).getValue()));}}
}

View file

@ -0,0 +1,51 @@
package com.example.duneterrain;
import java.util.*;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.entity.*;
import org.bukkit.event.player.PlayerEggThrowEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.Plugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
/** The native chicken remains the carrier: normal growth, walking, laying and hatching. */
final class ChukkaMobs implements Listener {
static final NamespacedKey KIND=new NamespacedKey("dunerealms","chukka");
private static final NamespacedKey EI=new NamespacedKey("executableitems","ei-id");
private final Plugin plugin;private final ArrakisEcology.Items items;
ChukkaMobs(Plugin plugin,ArrakisEcology.Items items){this.plugin=plugin;this.items=items;}
static boolean isChukka(Entity e){return e instanceof Chicken&&e.getPersistentDataContainer().has(KIND,PersistentDataType.BYTE);}
static boolean arrakis(Entity e){return e.getWorld().getName().equalsIgnoreCase("arrakis");}
static void prepare(Chicken c){c.getPersistentDataContainer().set(KIND,PersistentDataType.BYTE,(byte)1);if(c.customName()==null)c.customName(Component.text("Chukka",NamedTextColor.YELLOW));}
static String itemId(ItemStack stack){return stack==null||!stack.hasItemMeta()?null:stack.getItemMeta().getPersistentDataContainer().get(EI,PersistentDataType.STRING);}
void start(){Bukkit.getPluginManager().registerEvents(this,plugin);}
void spawn(Location at){if(at.getWorld()!=null&&at.getChunk().isLoaded())at.getWorld().spawn(at,Chicken.class,ChukkaMobs::prepare);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void laid(EntityDropItemEvent e){
if(!arrakis(e.getEntity())||!isChukka(e.getEntity())||e.getItemDrop().getItemStack().getType()!=Material.EGG)return;
try{var egg=items.build("chukka_egg");FaunaProof.markDrop(egg,e.getItemDrop().getUniqueId());e.getItemDrop().setItemStack(egg);}
catch(ReflectiveOperationException failure){e.setCancelled(true);plugin.getLogger().warning("Chukka egg definition unavailable");}
}
@EventHandler(priority=EventPriority.HIGHEST) public void hatch(PlayerEggThrowEvent e){
if(!arrakis(e.getEgg()))return;
// The old Jerboa Egg identity is now a Weirding Module, never a hatchable egg.
if("jerboa_egg".equals(itemId(e.getEgg().getItem())))e.setHatching(false);
// Chukka eggs keep the vanilla probability, number of chicks and native spawn event.
}
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void breed(EntityBreedEvent e){
if(!arrakis(e.getEntity())||!isChukka(e.getMother())||!isChukka(e.getFather())||!(e.getEntity() instanceof Chicken child))return;
prepare(child);if(e.getBreeder() instanceof Player player)FaunaProof.record(player,"chukka","breed",child);
}
@EventHandler(priority=EventPriority.HIGHEST) public void death(EntityDeathEvent e){
if(!arrakis(e.getEntity())||!isChukka(e.getEntity()))return;
FaunaProof.record(e.getEntity().getKiller(),"chukka","kill",e.getEntity());
try{
var meat=items.build(e.getEntity().getFireTicks()>0?"chukka_cooked_meat":"chukka_raw_meat");
var drops=e.getDrops();int amount=drops.stream().filter(d->d.getType()==Material.CHICKEN||d.getType()==Material.COOKED_CHICKEN).mapToInt(ItemStack::getAmount).sum();drops.removeIf(d->d.getType()==Material.CHICKEN||d.getType()==Material.COOKED_CHICKEN);
if(amount>0){meat.setAmount(amount);drops.add(meat);} // preserve native feather drops, meat quantity and XP.
}catch(ReflectiveOperationException failure){e.getDrops().removeIf(d->d.getType()==Material.CHICKEN||d.getType()==Material.COOKED_CHICKEN);plugin.getLogger().warning("Chukka meat definition unavailable");}
}
}

View file

@ -0,0 +1,68 @@
package com.example.duneterrain;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.Villager;
import org.bukkit.event.*;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.persistence.PersistentDataType;
import java.util.*;
/** Rich deposits are authenticated by a persistent chunk ledger, never by material alone. */
final class DenseSpice implements Listener {
private final DuneTerrain plugin;
private final NamespacedKey ledger = new NamespacedKey("dunerealms", "rich-spice-deposits");
DenseSpice(DuneTerrain plugin) { this.plugin=plugin; }
static long mix(long n) { n=(n^(n>>>30))*0xbf58476d1ce4e5b9L; n=(n^(n>>>27))*0x94d049bb133111ebL; return n^(n>>>31); }
// One 30 x 30 patch per 32-chunk region: configurable village-like spacing, no vanilla structure dependency.
static int[] anchor(long seed, int x, int z, int spacing) {
int cx=Math.floorDiv(x,spacing), cz=Math.floorDiv(z,spacing);
long hash=mix(seed^cx*0x9e3779b97f4a7c15L^cz*0xc2b2ae3d27d4eb4fL^0x44454e5345535049L);
return new int[]{cx*spacing+16+(int)Math.floorMod(hash,spacing-62),cz*spacing+16+(int)Math.floorMod(mix(hash),spacing-62)};
}
static boolean contains(long seed,int x,int z,int spacing) {
int[] a=anchor(seed,x,z,spacing); return x>=a[0]&&x<a[0]+30&&z>=a[1]&&z<a[1]+30;
}
static int encode(Block b) { return (b.getY()+2048)*256+(b.getX()&15)*16+(b.getZ()&15); }
private int[] entries(Chunk c) { return c.getPersistentDataContainer().getOrDefault(ledger,PersistentDataType.INTEGER_ARRAY,new int[0]); }
private boolean marked(Block b) { int key=encode(b); return Arrays.stream(entries(b.getChunk())).anyMatch(v->v==key); }
private void consume(Block b) { int key=encode(b); b.getChunk().getPersistentDataContainer().set(ledger,PersistentDataType.INTEGER_ARRAY,Arrays.stream(entries(b.getChunk())).filter(v->v!=key).toArray()); }
@EventHandler(priority=EventPriority.LOWEST) public void initialize(ChunkLoadEvent e) {
if(!e.isNewChunk()||!e.getWorld().getName().equalsIgnoreCase("arrakis"))return;
Chunk c=e.getChunk(); List<Integer> deposits=new ArrayList<>();
for(int x=0;x<16;x++)for(int z=0;z<16;z++) {
Block b=e.getWorld().getHighestBlockAt(c.getX()*16+x,c.getZ()*16+z);
if(b.getType()==Material.ORANGE_TERRACOTTA)deposits.add(encode(b));
}
c.getPersistentDataContainer().set(ledger,PersistentDataType.INTEGER_ARRAY,deposits.stream().mapToInt(Integer::intValue).toArray());
if(deposits.isEmpty())return;
int spacing=Math.max(128,plugin.getConfig().getInt("dense-spice.spacing",512));
int[] a=anchor(e.getWorld().getSeed(),c.getX()*16+8,c.getZ()*16+8,spacing);
if(Math.floorDiv(a[0]+15,16)!=c.getX()||Math.floorDiv(a[1]+15,16)!=c.getZ())return;
Bukkit.getScheduler().runTask(plugin,()->{
if(!c.isLoaded())return;
Location loc=e.getWorld().getHighestBlockAt(a[0]+15,a[1]+15).getLocation().add(.5,1,.5);
Villager seller=e.getWorld().spawn(loc,Villager.class,v->{
v.setCustomName(ChatColor.GOLD+"Spice Seller · +35%");v.setCustomNameVisible(true);
v.setAI(false);v.setInvulnerable(true);v.setPersistent(true);v.setRemoveWhenFarAway(false);
v.getPersistentDataContainer().set(new NamespacedKey("dunerealms","spice-seller"),PersistentDataType.BYTE,(byte)1);
});
});
}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void harvest(BlockBreakEvent e) {
Block b=e.getBlock(); if(!marked(b))return;
e.setDropItems(false);e.setExpToDrop(0);
}
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void reward(BlockBreakEvent e) {
Block b=e.getBlock();if(!marked(b))return;consume(b);
if(b.getType()==Material.ORANGE_TERRACOTTA && e.getPlayer().getGameMode()!=GameMode.CREATIVE)
b.getWorld().dropItemNaturally(b.getLocation(),DuneTerrain.spiceItem(Math.max(1,Math.min(64,plugin.getConfig().getInt("dense-spice.yield",4)))));
}
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void place(BlockPlaceEvent e) { if(marked(e.getBlock()))consume(e.getBlock()); }
@EventHandler(ignoreCancelled=true) public void push(BlockPistonExtendEvent e) { if(e.getBlocks().stream().anyMatch(this::marked))e.setCancelled(true); }
@EventHandler(ignoreCancelled=true) public void pull(BlockPistonRetractEvent e) { if(e.getBlocks().stream().anyMatch(this::marked))e.setCancelled(true); }
@EventHandler(ignoreCancelled=true) public void explode(EntityExplodeEvent e) { e.blockList().removeIf(this::marked); }
@EventHandler(ignoreCancelled=true) public void explode(BlockExplodeEvent e) { e.blockList().removeIf(this::marked); }
}

View file

@ -0,0 +1,60 @@
package com.example.duneterrain;
import org.bukkit.*;
import org.bukkit.block.Chest;
import org.bukkit.entity.EntityType;
import org.bukkit.generator.*;
import java.util.*;
/** Compact custom sandstone villages: no farm pieces or hay ever enter the palette. */
final class DesertVillages extends BlockPopulator {
private final DuneTerrain plugin;
DesertVillages(DuneTerrain plugin) { this.plugin=plugin; }
@Override public void populate(WorldInfo world,Random random,int cx,int cz,LimitedRegion r) {
if(!world.getName().equalsIgnoreCase("arrakis")||!plugin.getConfig().getBoolean("desert-villages.enabled",true))return;
int spacing=Math.max(192,plugin.getConfig().getInt("desert-villages.spacing",768));
// A complete village fits inside one chunk's population buffer. Only the anchor chunk builds it.
int[] a=DenseSpice.anchor(world.getSeed()^0x56494c4c414745L,cx*16+8,cz*16+8,spacing);
int x=a[0]+15,z=a[1]+15;
if(Math.floorDiv(x,16)!=cx||Math.floorDiv(z,16)!=cz)return;
for(int dx=-16;dx<=16;dx+=8)for(int dz=-16;dz<=16;dz+=8)
if(!r.isInRegion(x+dx,world.getMinHeight()+1,z+dz))return;
int y=r.getHighestBlockYAt(x,z);
if(y+7>=world.getMaxHeight())return;
// Avoid mountains and existing rich fields rather than bulldozing their terrain.
for(int dx=-16;dx<=16;dx+=8)for(int dz=-16;dz<=16;dz+=8)
if(Math.abs(r.getHighestBlockYAt(x+dx,z+dz)-y)>8||r.getType(x+dx,r.getHighestBlockYAt(x+dx,z+dz),z+dz)==Material.ORANGE_TERRACOTTA)return;
for(int dx=-15;dx<=15;dx++)for(int dz=-15;dz<=15;dz++) {
int ground=r.getHighestBlockYAt(x+dx,z+dz);
for(int h=Math.min(ground,y);h<=y;h++)r.setType(x+dx,h,z+dz,Material.SANDSTONE);
for(int h=y+1;h<=Math.max(ground,y+6);h++)r.setType(x+dx,h,z+dz,Material.AIR);
r.setType(x+dx,y,z+dz,Math.abs(dx)<=2||Math.abs(dz)<=2?Material.CUT_SANDSTONE:Material.SAND);
}
for(int ox:new int[]{-12,6})for(int oz:new int[]{-12,6}) {
for(int dx=0;dx<7;dx++)for(int dz=0;dz<7;dz++)for(int dy=1;dy<=5;dy++) {
boolean wall=dx==0||dz==0||dx==6||dz==6;
r.setType(x+ox+dx,y+dy,z+oz+dz,dy==5?Material.SMOOTH_SANDSTONE:wall?Material.SANDSTONE:Material.AIR);
}
r.setType(x+ox+3,y+1,z+oz,Material.AIR);r.setType(x+ox+3,y+2,z+oz,Material.AIR);
r.setType(x+ox+1,y+2,z+oz,Material.GLASS_PANE);
r.setType(x+ox+3,y+4,z+oz+3,Material.LANTERN);
// Beds and non-farming job sites make this a functioning village, not empty scenery.
var foot=(org.bukkit.block.data.type.Bed)Material.RED_BED.createBlockData();
foot.setFacing(org.bukkit.block.BlockFace.SOUTH);foot.setPart(org.bukkit.block.data.type.Bed.Part.FOOT);
var head=(org.bukkit.block.data.type.Bed)foot.clone();head.setPart(org.bukkit.block.data.type.Bed.Part.HEAD);
r.setBlockData(x+ox+2,y+1,z+oz+3,foot);r.setBlockData(x+ox+2,y+1,z+oz+4,head);
r.setType(x+ox+1,y+1,z+oz+4,(ox<0?oz<0?Material.BARREL:Material.FLETCHING_TABLE:oz<0?Material.BLAST_FURNACE:Material.CARTOGRAPHY_TABLE));
int bx=x+ox+4,bz=z+oz+4;
r.setType(bx,y+1,bz,Material.CHEST);
if(r.getBlockState(bx,y+1,bz) instanceof Chest chest) {
var table=Bukkit.getLootTable(new NamespacedKey("dunerealms","chests/desert-village"));
if(table!=null){chest.setLootTable(table);chest.setSeed(DenseSpice.mix(world.getSeed()^bx*31L^bz));}
else { // Safe stock when the optional biome/loot datapack has not yet been installed.
chest.getSnapshotInventory().addItem(new org.bukkit.inventory.ItemStack(Material.BREAD,4),new org.bukkit.inventory.ItemStack(Material.DRIED_KELP,6),new org.bukkit.inventory.ItemStack(Material.RAW_IRON,3));
}
chest.update(true,false);
}
// Quest contacts are owned by JARVIS; terrain generates structures only.
}
}
}

View file

@ -0,0 +1,954 @@
package com.example.duneterrain;
import org.bukkit.*;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.type.Bed;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Trident;
import io.papermc.paper.event.entity.EntityMoveEvent;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.generator.*;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.ServerLoadEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import java.io.File;
import java.util.*;
public final class DuneTerrain extends JavaPlugin implements Listener {
private static final String[] PLANETS = {"arrakis", "giedi_prime", "kaitain", "caladan", "sigma_draconis_iv"};
private NamespacedKey sietchLootIdKey;
private final Map<UUID, PersonalLoot> openSietchLoot = new HashMap<>();
private record PersonalLoot(Inventory inventory, String id) {}
public void announceSpiceBloom(Location location) {
ArrakisEcology.bloom(this, location);
org.bukkit.plugin.Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
if (core == null || !core.isEnabled()) return;
try {
String id = "bloom:" + location.getWorld().getUID() + ":" + location.getBlockX() + ":" + location.getBlockY() + ":" + location.getBlockZ();
core.getClass().getMethod("announceArrakisEvent", String.class, Location.class, String.class)
.invoke(core, "spicebloom", location, id);
} catch (ReflectiveOperationException ex) { getLogger().warning("Spice bloom announcement failed: " + ex.getMessage()); }
}
@EventHandler public void onBloomChunkLoad(ChunkLoadEvent event) {
if (!event.getWorld().getName().equalsIgnoreCase("arrakis")) return;
Chunk chunk = event.getChunk();
Bukkit.getScheduler().runTask(this, () -> inspectBlooms(chunk));
}
private void inspectBlooms(Chunk chunk) {
World world = chunk.getWorld();
if (!chunk.isLoaded()) return;
for (int x = 0; x < 16; x++) for (int z = 0; z < 16; z++) {
int wx = chunk.getX() * 16 + x, wz = chunk.getZ() * 16 + z;
int y = world.getHighestBlockYAt(wx, wz);
// The raised marker sits above a 3x3 magma patch; no neighbouring chunk access.
if (y > world.getMinHeight() && chunk.getBlock(x, y, z).getType() == Material.MAGMA_BLOCK
&& chunk.getBlock(x, y - 1, z).getType() == Material.MAGMA_BLOCK)
announceSpiceBloom(new Location(world, wx, y, wz));
}
}
@EventHandler public void onSpiceBlowProjectile(ProjectileHitEvent event) {
if (!(event.getEntity() instanceof Arrow) && !(event.getEntity() instanceof Trident)) return;
Player actor=event.getEntity().getShooter() instanceof Player p?p:null;
if (event.getHitBlock() != null) triggerSpiceBlowAt(event.getHitBlock().getLocation(),actor);
else if (event.getHitEntity() != null) triggerSpiceBlowAt(event.getHitEntity().getLocation(),actor);
}
@EventHandler(ignoreCancelled=true) public void onSpiceBlowPlayerMove(PlayerMoveEvent event) {
if (event.getTo() == null || (event.getFrom().getBlockX() == event.getTo().getBlockX()
&& event.getFrom().getBlockY() == event.getTo().getBlockY()
&& event.getFrom().getBlockZ() == event.getTo().getBlockZ())) return;
triggerSpiceBlowAt(event.getTo(),event.getPlayer());
}
@EventHandler public void onSpiceBlowEntityMove(EntityMoveEvent event) {
if (event.hasChangedBlock() && event.getTo() != null) triggerSpiceBlowAt(event.getTo(),null);
}
private void triggerSpiceBlowAt(Location location,Player actor) {
if (location == null || location.getWorld() == null || !location.getWorld().getName().equalsIgnoreCase("arrakis")) return;
int x = location.getBlockX(), y = location.getBlockY(), z = location.getBlockZ();
for (int dy = -1; dy <= 0; dy++) for (int dx = -1; dx <= 1; dx++) for (int dz = -1; dz <= 1; dz++) {
Block block = location.getWorld().getBlockAt(x + dx, y + dy, z + dz);
if (block.getType() != Material.MAGMA_BLOCK) continue;
Block center = findSpiceBlowCenter(block);
if (center != null) {
detonateSpiceBlow(center);
if(actor!=null&&generatedSpiceBlow(center.getX(),center.getZ(),Math.max(256,getConfig().getInt("spice-blow.spacing",2000)))&&center.getType()==Material.GLOWSTONE){
UUID reference=UUID.nameUUIDFromBytes((center.getWorld().getUID()+":"+center.getX()+":"+center.getZ()).getBytes(java.nio.charset.StandardCharsets.UTF_8));
FaunaProof.milestone(actor,"husbandry_spice_blow",reference);
}
}
}
}
static boolean generatedSpiceBlow(int x,int z,int spacing){long cx=Math.floorDiv((long)x,spacing),cz=Math.floorDiv((long)z,spacing);long salt=SpiceBlowPopulator.SALT;long h1=mix64(cx*0x9E3779B97F4A7C15L^cz*0xC2B2AE3D27D4EB4FL^salt),h2=mix64(cz*0x165667B19E3779F9L^cx*0x85EBCA77C2B2AE63L^~salt);return x==cx*spacing+8+Math.floorMod(h1,spacing-16)&&z==cz*spacing+8+Math.floorMod(h2,spacing-16);}
private Block findSpiceBlowCenter(Block touched) {
World world = touched.getWorld();
for (int cx = touched.getX() - 1; cx <= touched.getX() + 1; cx++)
for (int cz = touched.getZ() - 1; cz <= touched.getZ() + 1; cz++)
for (int topY = touched.getY() - 1; topY <= touched.getY() + 1; topY++) {
if (world.getBlockAt(cx, topY, cz).getType() != Material.MAGMA_BLOCK
|| world.getBlockAt(cx, topY - 1, cz).getType() != Material.MAGMA_BLOCK) continue;
boolean patch = true;
for (int dx = -1; dx <= 1 && patch; dx++) for (int dz = -1; dz <= 1; dz++)
if (world.getBlockAt(cx + dx, topY - 1, cz + dz).getType() != Material.MAGMA_BLOCK) { patch = false; break; }
if (patch) return world.getBlockAt(cx, topY, cz);
}
return null;
}
private void detonateSpiceBlow(Block center) {
if (center.getType() != Material.MAGMA_BLOCK) return;
World world = center.getWorld();
int x = center.getX(), z = center.getZ(), baseY = center.getY() - 1;
for (int dx = -1; dx <= 1; dx++) for (int dz = -1; dz <= 1; dz++)
world.getBlockAt(x + dx, baseY, z + dz).setType(Material.AIR, false);
center.setType(Material.GLOWSTONE, false);
world.playSound(center.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 1.5f, 0.7f);
world.spawnParticle(Particle.EXPLOSION, center.getLocation().add(0.5, 0.5, 0.5), 1);
String path = "spice-blow.";
int targetValue = Math.max(1, getConfig().getInt(path + "target-value", 15000));
int unitPrice = Math.max(1, getConfig().getInt(path + "unit-price", 15));
org.bukkit.plugin.Plugin economy = Bukkit.getPluginManager().getPlugin("DuneEss");
if (economy instanceof JavaPlugin economyPlugin)
unitPrice = Math.max(1, economyPlugin.getConfig().getInt("currency.spice-price", unitPrice));
int targetDeposits = (int)Math.ceil(targetValue / (double)unitPrice);
int radius = Math.max(12, getConfig().getInt(path + "radius", 24));
List<Block> candidates = new ArrayList<>();
for (int dx = -radius; dx <= radius; dx++) for (int dz = -radius; dz <= radius; dz++) {
if (dx * dx + dz * dz > radius * radius) continue;
int bx = x + dx, bz = z + dz;
int surfaceY = world.getHighestBlockYAt(bx, bz);
Material surface = world.getBlockAt(bx, surfaceY, bz).getType();
if (surface == Material.SAND || surface == Material.RED_SAND) candidates.add(world.getBlockAt(bx, surfaceY, bz));
}
candidates.sort(Comparator.comparingLong(block -> mix64((long)block.getX() * 0x9E3779B97F4A7C15L
^ (long)block.getZ() * 0xC2B2AE3D27D4EB4FL ^ world.getSeed() ^ 0x5350494345424c4fL)));
int placed = 0;
for (Block block : candidates) {
if (placed >= targetDeposits) break;
block.setType(Material.SUSPICIOUS_SAND, false);
placed++;
}
announceSpiceBloom(center.getLocation());
for (org.bukkit.entity.Player player : world.getPlayers()) player.sendMessage(ChatColor.GOLD + "A spice blow erupted at X " + x + ", Y " + center.getY() + ", Z " + z + " on Arrakis! " + placed + " deposits surfaced.");
getLogger().info("Spice blow at " + x + ", " + z + " deployed " + placed + " spice deposits (target value " + targetValue + " Solaris).");
}
@EventHandler public void onSietchChestOpen(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getClickedBlock() == null) return;
if (event.getHand() != org.bukkit.inventory.EquipmentSlot.HAND) return;
BlockState state = event.getClickedBlock().getState();
if (!(state instanceof Chest chest)) return;
String id = chest.getPersistentDataContainer().get(sietchLootIdKey, PersistentDataType.STRING);
if (id == null) return;
event.setCancelled(true);
org.bukkit.entity.Player player = event.getPlayer();
NamespacedKey claimedKey = new NamespacedKey(this, "sietch_claim_" + id);
if (player.getPersistentDataContainer().has(claimedKey, PersistentDataType.BYTE)) {
player.sendMessage(ChatColor.YELLOW + "You have already claimed this sietch cache.");
return;
}
Inventory inventory = Bukkit.createInventory(null, 27, ChatColor.DARK_GRAY + "Sietch Cache");
addLoot(inventory, spiceItem(64)); addLoot(inventory, spiceItem(64)); addLoot(inventory, spiceItem(64)); addLoot(inventory, spiceItem(58));
addLoot(inventory, enchantedGold(Material.GOLDEN_HELMET));
addLoot(inventory, enchantedGold(Material.GOLDEN_CHESTPLATE));
addLoot(inventory, enchantedGold(Material.GOLDEN_LEGGINGS));
addLoot(inventory, enchantedGold(Material.GOLDEN_BOOTS));
addLoot(inventory, new ItemStack(Material.OAK_PLANKS, 32));
addLoot(inventory, new ItemStack(Material.BREAD, 16));
openSietchLoot.put(player.getUniqueId(), new PersonalLoot(inventory, id));
player.openInventory(inventory);
player.sendMessage(ChatColor.GOLD + "This personal cache contains supplies for you.");
}
@EventHandler public void onSietchLootClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof org.bukkit.entity.Player player)) return;
PersonalLoot loot = openSietchLoot.get(player.getUniqueId());
if (loot == null || event.getView().getTopInventory() != loot.inventory()) return;
if (event.getClickedInventory() != loot.inventory()) return;
event.setCancelled(true);
ItemStack item = event.getCurrentItem();
if (item == null || item.getType().isAir()) return;
Map<Integer, ItemStack> leftovers = player.getInventory().addItem(item.clone());
if (leftovers.isEmpty()) loot.inventory().setItem(event.getSlot(), null);
else {
loot.inventory().setItem(event.getSlot(), leftovers.values().iterator().next());
player.sendMessage(ChatColor.RED + "Your inventory only had room for part of that stack.");
}
}
@EventHandler public void onSietchLootDrag(InventoryDragEvent event) {
if (!(event.getWhoClicked() instanceof org.bukkit.entity.Player player)) return;
PersonalLoot loot = openSietchLoot.get(player.getUniqueId());
if (loot != null && event.getView().getTopInventory() == loot.inventory()) event.setCancelled(true);
}
@EventHandler public void onSietchLootClose(InventoryCloseEvent event) {
if (!(event.getPlayer() instanceof org.bukkit.entity.Player player)) return;
PersonalLoot loot = openSietchLoot.get(player.getUniqueId());
if (loot == null || event.getView().getTopInventory() != loot.inventory()) return;
openSietchLoot.remove(player.getUniqueId());
for (ItemStack item : loot.inventory().getContents()) if (item != null && !item.getType().isAir()) {
Map<Integer, ItemStack> leftovers = player.getInventory().addItem(item);
leftovers.values().forEach(left -> player.getWorld().dropItemNaturally(player.getLocation(), left));
}
player.getPersistentDataContainer().set(new NamespacedKey(this, "sietch_claim_" + loot.id()), PersistentDataType.BYTE, (byte) 1);
}
private static void addLoot(Inventory inventory, ItemStack item) {
for (int slot = 0; slot < inventory.getSize(); slot++) if (inventory.getItem(slot) == null) {
inventory.setItem(slot, item);
return;
}
}
static ItemStack spiceItem(int amount) {
ItemStack item = new ItemStack(Material.ORANGE_DYE, amount);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.GOLD + "Melange Spice");
meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms", "item"), PersistentDataType.STRING, "spice");
item.setItemMeta(meta);
return item;
}
private static ItemStack enchantedGold(Material material) {
ItemStack item = new ItemStack(material);
ItemMeta meta = item.getItemMeta();
meta.addEnchant(Enchantment.PROTECTION, 2, true);
meta.addEnchant(Enchantment.UNBREAKING, 2, true);
item.setItemMeta(meta);
return item;
}
@Override public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) {
String planet = id == null || id.isBlank()
? getConfig().getString("server.planet", "arrakis")
: id;
planet = planet.toLowerCase(Locale.ROOT);
if (!Arrays.asList(PLANETS).contains(planet)) {
getLogger().severe("Invalid generator planet '" + planet + "' for world '" + worldName + "'.");
return null;
}
if (!getConfig().getBoolean("planets." + planet + ".enabled", true)) {
getLogger().severe("Generator planet '" + planet + "' is disabled in config.yml.");
return null;
}
return new PlanetChunkGenerator(this, planet);
}
@Override public BiomeProvider getDefaultBiomeProvider(String worldName, String id) {
String planet = id == null || id.isBlank()
? getConfig().getString("server.planet", "arrakis")
: id;
planet = planet.toLowerCase(Locale.ROOT);
if (!Arrays.asList(PLANETS).contains(planet)) {
getLogger().severe("Invalid biome-provider planet '" + planet + "' for world '" + worldName + "'.");
return null;
}
return new PlanetBiomeProvider(this, planet);
}
@Override public void onEnable() {
saveDefaultConfig();
String formations = "planets.arrakis.darkstone-islands.";
if (getConfig().getInt(formations + "min-radius") == 10
&& getConfig().getInt(formations + "max-radius") == 18) {
getConfig().set(formations + "min-radius", 45);
getConfig().set(formations + "max-radius", 55);
saveConfig();
getLogger().info("Upgraded default Arrakis rock formations to about 100 blocks across in new chunks.");
}
getServer().getPluginManager().registerEvents(this, this);
PlanetMobs.start(this);StarterRepairDrops.start(this);TrailsBridge.start(this);if(getConfig().getString("server.planet","arrakis").equalsIgnoreCase("arrakis"))ArrakisEcology.start(this);
getServer().getPluginManager().registerEvents(new DenseSpice(this), this);
getServer().getPluginManager().registerEvents(new HarkonnenFortress(this), this);
sietchLootIdKey = new NamespacedKey(this, "sietch-loot-id");
String planet = getConfig().getString("server.planet", "arrakis").toLowerCase(Locale.ROOT);
if (!Arrays.asList(PLANETS).contains(planet)) {
getLogger().severe("Invalid server.planet '" + planet + "'. Choose one of: " + String.join(", ", PLANETS));
getServer().getPluginManager().disablePlugin(this);
return;
}
if (!getConfig().getBoolean("planets." + planet + ".enabled", true)) {
getLogger().severe("Planet '" + planet + "' is disabled in config.yml.");
getServer().getPluginManager().disablePlugin(this);
return;
}
getLogger().info("DuneTerrain registered the " + planet + " generator. World setup will run after Paper finishes loading worlds.");
}
@EventHandler public void onServerLoad(ServerLoadEvent event) {
World arrakis = Bukkit.getWorld("arrakis");
if (arrakis != null) for (Chunk chunk : arrakis.getLoadedChunks())
Bukkit.getScheduler().runTask(this, () -> inspectBlooms(chunk));
String planet = getConfig().getString("server.planet", "arrakis").toLowerCase(Locale.ROOT);
World world = Bukkit.getWorld(planet);
if (world == null) {
File worldFolder = new File(getServer().getWorldContainer(), planet);
boolean existingWorld = worldFolder.isDirectory();
world = Bukkit.createWorld(new WorldCreator(planet)
.environment(World.Environment.NORMAL)
.generator(new PlanetChunkGenerator(this, planet)));
if (world == null) {
getLogger().severe("Could not create or load world '" + planet + "'.");
return;
}
if (existingWorld) getLogger().warning("Loaded existing world '" + planet + "'. Existing chunks remain unchanged; move the world folder after backing it up to regenerate terrain.");
else getLogger().info("Created world '" + planet + "' with DuneTerrain.");
} else if (!(world.getGenerator() instanceof PlanetChunkGenerator)) {
getLogger().severe("World '" + planet + "' was loaded without DuneTerrain's generator. Configure bukkit.yml worlds." + planet + ".generator: DuneTerrain:" + planet + " and worlds." + planet + ".biome-provider: DuneTerrain:" + planet + ". Existing chunks remain unchanged.");
} else {
getLogger().info("World '" + planet + "' was loaded with DuneTerrain's configured generator.");
}
world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, !planet.equals("arrakis")&&!planet.equals("giedi_prime"));
if(planet.equals("giedi_prime")){world.setStorm(false);world.setGameRule(GameRule.DO_WEATHER_CYCLE,false);}
world.setTime(planet.equals("giedi_prime") ? 18000 : 6000);
setupPlanetSpawn(world, planet);
}
private void setupPlanetSpawn(World world, String planet) {
String path = "planets." + planet + ".spawn.";
int x = getConfig().getInt(path + "x", 0), z = getConfig().getInt(path + "z", 0);
world.getChunkAt(x >> 4, z >> 4).load(true);
Location spawn = findSafeSpawn(world, x, z);
world.setSpawnLocation(spawn);
}
private Location findSafeSpawn(World world, int x, int z) {
for (int radius = 0; radius <= 12; radius++) {
for (int dx = -radius; dx <= radius; dx++) for (int dz = -radius; dz <= radius; dz++) {
if (radius > 0 && Math.abs(dx) != radius && Math.abs(dz) != radius) continue;
int bx = x + dx, bz = z + dz;
int y = world.getHighestBlockYAt(bx, bz);
Material ground = world.getBlockAt(bx, y, bz).getType();
if (!ground.isSolid() || ground == Material.MAGMA_BLOCK || ground == Material.CACTUS || ground == Material.POWDER_SNOW) continue;
if (world.getBlockAt(bx, y + 1, bz).isLiquid() || world.getBlockAt(bx, y + 2, bz).isLiquid()) continue;
return new Location(world, bx + 0.5, y + 1, bz + 0.5);
}
}
int y = Math.max(world.getMinHeight() + 2, world.getHighestBlockYAt(x, z) + 1);
return new Location(world, x + 0.5, y, z + 0.5);
}
private static class PlanetChunkGenerator extends ChunkGenerator {
private final DuneTerrain plugin;
private final String planet;
private record GroundKey(RockPlateaus.Shape shape, int baseHeight, double variation) {}
private final java.util.concurrent.ConcurrentHashMap<GroundKey,Integer> formationGround = new java.util.concurrent.ConcurrentHashMap<>();
PlanetChunkGenerator(DuneTerrain plugin, String planet) { this.plugin = plugin; this.planet = planet; }
@Override public List<BlockPopulator> getDefaultPopulators(World world) {
return planet.equals("arrakis") && world.getName().equalsIgnoreCase("arrakis")
? List.of(new SietchPopulator(plugin), new SpiceBlowPopulator(plugin), new DesertVillages(plugin), new HarkonnenFortress(plugin)) : List.of();
}
@Override public void generateNoise(WorldInfo world, Random random, int chunkX, int chunkZ, ChunkData data) {
if(TemperateLandscape.enabled(planet)){
TemperateLandscape.generate(world,random,chunkX,chunkZ,data,planet);
placeOres(data,random,"planets."+planet+".",world.getMinHeight(),world.getMaxHeight()-1);return;
}
String path = "planets." + planet + ".";
int minY = world.getMinHeight(), maxY = world.getMaxHeight() - 1;
int baseHeight = plugin.getConfig().getInt(path + "terrain.base-height", 68);
double variation = plugin.getConfig().getDouble(path + "terrain.height-variation", 8);
double scale = Math.max(0.001, plugin.getConfig().getDouble(path + "terrain.noise-scale", 0.02));
int waterLevel = plugin.getConfig().getInt(path + "water.level", 63);
Material surface = configuredMaterial(path + "surface", Material.GRASS_BLOCK);
Material filler = configuredMaterial(path + "filler", Material.DIRT);
Material core = planet.equals("giedi_prime") || planet.equals("sigma_draconis_iv") ? Material.DEEPSLATE : Material.STONE;
double flowers = Math.max(0, plugin.getConfig().getDouble(path + "vegetation.flowers-per-chunk", 0));
double treeChance = Math.max(0, plugin.getConfig().getDouble(path + "vegetation.tree-chance", 0));
int[][] heights = new int[16][16];
for (int x = 0; x < 16; x++) for (int z = 0; z < 16; z++) {
int gx = chunkX * 16 + x, gz = chunkZ * 16 + z;
double n = Math.sin(gx * scale) * Math.cos(gz * scale * 1.13)
+ Math.sin(gx * scale * 2.7 + gz * scale * 1.45) * 0.35;
int h = Math.max(minY + 8, Math.min(maxY - 8, baseHeight + (int) Math.round(n * variation)));
heights[x][z] = h;
data.setBlock(x, minY, z, Material.BEDROCK);
for (int y = minY + 1; y < h - 3; y++) data.setBlock(x, y, z, core);
for (int y = h - 3; y < h; y++) data.setBlock(x, y, z, filler);
data.setBlock(x, h, z, surface);
if (plugin.getConfig().getBoolean(path + "water.swamp-pools", false) && h < waterLevel) {
double poolNoise = Math.sin(gx * 0.035) * Math.cos(gz * 0.031);
double coverage = Math.max(0, Math.min(1, plugin.getConfig().getDouble(path + "water.coverage", 0.18)));
if (poolNoise > 0.72 - coverage * 0.75) {
for (int y = h + 1; y <= Math.min(waterLevel, maxY); y++) data.setBlock(x, y, z, Material.WATER);
}
}
if (flowers > 0 && surface == Material.GRASS_BLOCK && random.nextDouble() < Math.min(1, flowers / 256.0)) {
Material[] flowerTypes = {Material.POPPY, Material.DANDELION, Material.CORNFLOWER,
Material.AZURE_BLUET, Material.ALLIUM, Material.OXEYE_DAISY};
data.setBlock(x, h + 1, z, flowerTypes[random.nextInt(flowerTypes.length)]);
}
if (plugin.getConfig().getBoolean(path + "vegetation.trees", false)
&& surface == Material.GRASS_BLOCK && random.nextDouble() < treeChance && x >= 3 && x <= 12 && z >= 3 && z <= 12) {
placeJungleTree(data, x, h + 1, z, random, maxY);
}
}
boolean arrakisWorld = planet.equals("arrakis") && world.getName().equalsIgnoreCase("arrakis");
if (arrakisWorld) placeOasisTree(data, chunkX, chunkZ, heights, minY, maxY);
if (arrakisWorld) {
placeDarkstoneIsland(data, chunkX, chunkZ, heights, minY, maxY);
placeSpiceDeposits(data, heights, random, minY, maxY);
placeRandomSpicePatch(data, chunkX, chunkZ, heights);
if (plugin.getConfig().getBoolean("dense-spice.enabled", true)) {
int spacing = Math.max(128, plugin.getConfig().getInt("dense-spice.spacing", 512));
for (int x=0;x<16;x++) for(int z=0;z<16;z++)
if(DenseSpice.contains(world.getSeed(),chunkX*16+x,chunkZ*16+z,spacing))
data.setBlock(x,heights[x][z],z,Material.ORANGE_TERRACOTTA);
}
}
placeOres(data, random, path, minY, maxY);
}
@Override public BiomeProvider getDefaultBiomeProvider(WorldInfo worldInfo) {
return new PlanetBiomeProvider(plugin, planet);
}
@Override public void generateCaves(WorldInfo world,Random random,int x,int z,ChunkData data){OceanAquifers.flood(world,x,z,data,planet);OrdosSulfurSurfaces.apply(world,x,z,data);}
@Override public boolean shouldGenerateStructures(WorldInfo world,Random random,int x,int z){return Set.of("caladan","kaitain","giedi_prime","sigma_draconis_iv","arrakis").contains(planet);}
@Override public boolean shouldGenerateDecorations(WorldInfo world,Random random,int x,int z){return TemperateLandscape.enabled(planet);}
@Override public boolean shouldGenerateMobs(WorldInfo world,Random random,int x,int z){return planet.equals("arrakis")||TemperateLandscape.enabled(planet);}
@Override public boolean shouldGenerateCaves(WorldInfo world,Random random,int x,int z){return Set.of("caladan","kaitain","giedi_prime","sigma_draconis_iv","arrakis").contains(planet);}
@Override public int getBaseHeight(WorldInfo world,Random random,int x,int z,org.bukkit.HeightMap map){if(planet.equals("arrakis")){String path="planets.arrakis.terrain.";int base=plugin.getConfig().getInt(path+"base-height",68);double variation=plugin.getConfig().getDouble(path+"height-variation",8),scale=Math.max(.001,plugin.getConfig().getDouble(path+"noise-scale",.02));double n=Math.sin(x*scale)*Math.cos(z*scale*1.13)+Math.sin(x*scale*2.7+z*scale*1.45)*.35;return Math.max(world.getMinHeight()+8,Math.min(world.getMaxHeight()-9,base+(int)Math.round(n*variation)))+1;}if(!TemperateLandscape.enabled(planet))return super.getBaseHeight(world,random,x,z,map);int h=TemperateLandscape.height(world.getSeed(),x,z,planet);return (map==org.bukkit.HeightMap.OCEAN_FLOOR||map==org.bukkit.HeightMap.OCEAN_FLOOR_WG||planet.equals("giedi_prime")&&!TemperateLandscape.lavaSurface(world.getSeed(),x,z)?h:Math.max(TemperateLandscape.SEA,h))+1;}
private void placeOasisTree(ChunkData data, int chunkX, int chunkZ, int[][] heights, int minY, int maxY) {
String path = "planets.arrakis.oasis-trees.";
if (!plugin.getConfig().getBoolean(path + "enabled", true)) return;
int spacing = Math.max(64, plugin.getConfig().getInt(path + "spacing", 300));
long[] anchor = gridAnchor(chunkX, chunkZ, spacing, 0x4f41534953545245L);
if (Math.floorDiv(anchor[0], 16) != chunkX || Math.floorDiv(anchor[1], 16) != chunkZ) return;
int x = Math.floorMod(anchor[0], 16), z = Math.floorMod(anchor[1], 16);
int y = heights[x][z] + 1;
int height = Math.max(4, plugin.getConfig().getInt(path + "trunk-height", 7));
if (y + height + 3 >= maxY || data.getType(x, y - 1, z) != Material.SAND) return;
for (int dy = 0; dy < height; dy++) data.setBlock(x, y + dy, z, Material.OAK_LOG);
for (int dy = height - 3; dy <= height + 2; dy++) {
int radius = dy >= height + 1 ? 2 : 3;
for (int dx = -radius; dx <= radius; dx++) for (int dz = -radius; dz <= radius; dz++) {
if (Math.abs(dx) == radius && Math.abs(dz) == radius && Math.floorMod(dx * 31 + dz * 17, 3) == 0) continue;
int lx = x + dx, lz = z + dz, ly = y + dy;
if (lx < 0 || lx >= 16 || lz < 0 || lz >= 16 || ly >= maxY || !data.getType(lx, ly, lz).isAir()) continue;
org.bukkit.block.data.type.Leaves leaves = (org.bukkit.block.data.type.Leaves) Bukkit.createBlockData(Material.OAK_LEAVES);
leaves.setPersistent(true);
data.setBlock(lx, ly, lz, leaves);
}
}
}
private long[] gridAnchor(int chunkX, int chunkZ, int spacing, long salt) {
int centerX = chunkX * 16 + 8, centerZ = chunkZ * 16 + 8;
long cellX = Math.floorDiv(centerX, spacing), cellZ = Math.floorDiv(centerZ, spacing);
long h1 = mix64(cellX * 0x9E3779B97F4A7C15L ^ cellZ * 0xC2B2AE3D27D4EB4FL ^ salt);
long h2 = mix64(cellZ * 0x165667B19E3779F9L ^ cellX * 0x85EBCA77C2B2AE63L ^ ~salt);
long x = cellX * spacing + 8 + Math.floorMod(h1, spacing - 16);
long z = cellZ * spacing + 8 + Math.floorMod(h2, spacing - 16);
if (Math.floorDiv(x, spacing) != cellX || Math.floorDiv(z, spacing) != cellZ) return new long[]{Long.MIN_VALUE, Long.MIN_VALUE};
return new long[]{x, z};
}
private void placeDarkstoneIsland(ChunkData data, int chunkX, int chunkZ, int[][] heights, int minY, int maxY) {
String path = "planets.arrakis.darkstone-islands.";
if (!plugin.getConfig().getBoolean("planets.arrakis.highlands.enabled", true)) return;
int minimumGap = Math.max(192, plugin.getConfig().getInt("planets.arrakis.highlands.min-spacing", 300));
int maximumGap = Math.max(minimumGap, plugin.getConfig().getInt("planets.arrakis.highlands.max-spacing", 500));
int spacing = (minimumGap + maximumGap) / 2;
int minRadius = Math.max(6, plugin.getConfig().getInt(path + "min-radius", 45));
int maxRadius = Math.max(minRadius, plugin.getConfig().getInt(path + "max-radius", 55));
int maxRise = Math.max(1, plugin.getConfig().getInt(path + "max-height", 14));
boolean highlands = plugin.getConfig().getBoolean("planets.arrakis.highlands.enabled", true);
int mountainRise = highlands ? Math.max(0, Math.min(96, plugin.getConfig().getInt("planets.arrakis.highlands.mountain-rise", 32))) : 0;
int baseHeight = plugin.getConfig().getInt("planets.arrakis.terrain.base-height", 70);
double variation = plugin.getConfig().getDouble("planets.arrakis.terrain.height-variation", 11);
double scale = Math.max(0.001, plugin.getConfig().getDouble("planets.arrakis.terrain.noise-scale", 0.02));
int worldMinX = chunkX * 16, worldMinZ = chunkZ * 16;
int reach = (int)Math.ceil(maxRadius * 2.0) + 3;
int firstCellX = Math.floorDiv(worldMinX - reach, spacing), lastCellX = Math.floorDiv(worldMinX + 15 + reach, spacing);
int firstCellZ = Math.floorDiv(worldMinZ - reach, spacing), lastCellZ = Math.floorDiv(worldMinZ + 15 + reach, spacing);
for (int cellX = firstCellX; cellX <= lastCellX; cellX++) for (int cellZ = firstCellZ; cellZ <= lastCellZ; cellZ++) {
if(!RockPlateaus.activeCell(cellX,cellZ))continue;
long seed = RockPlateaus.formationSeed(cellX, cellZ);
long centerX = RockPlateaus.centerX(cellX,minimumGap,maximumGap);
long centerZ = RockPlateaus.centerZ(cellZ,minimumGap,maximumGap);
int radius = RockPlateaus.radius(seed,minRadius,maxRadius);
RockPlateaus.Shape shape = RockPlateaus.shape(seed, centerX, centerZ, radius, scale);
if (formationGround.size() > 2048) formationGround.clear();
int highestGround = formationGround.computeIfAbsent(new GroundKey(shape,baseHeight,variation),
key -> RockPlateaus.highestGround(key.shape(),key.baseHeight(),key.variation()));
int allowedPlateaus = Math.max(1, Math.min(3, Math.min(maxRise, plugin.getConfig().getInt(path + "max-plateaus", 3))));
int plateauCount = highlands ? allowedPlateaus : RockPlateaus.count(seed, allowedPlateaus);
int interval = RockPlateaus.interval(plugin.getConfig().getInt(path + "plateau-interval", 5), maxRise, plateauCount);
int plateauY = highestGround + mountainRise + plateauCount * interval;
for (int lx = 0; lx < 16; lx++) for (int lz = 0; lz < 16; lz++) {
long gx = (long) worldMinX + lx, gz = (long) worldMinZ + lz;
long rough = mix64(gx * 0x9E3779B97F4A7C15L ^ gz * 0xC2B2AE3D27D4EB4FL ^ seed);
double depth = shape.depth(gx, gz);
if (depth < 0) continue;
int baseY = heights[lx][lz];
if (plateauY + 2 >= maxY || baseY <= minY + 1) continue;
int level = RockPlateaus.level(highlands ? (depth - 0.40) / 0.60 : depth, plateauCount);
int lowerLevel = highlands ? RockPlateaus.lowerTerrace(depth) : 0;
boolean plateau = level > 0 || lowerLevel > 0;
int terraceY = lowerLevel > 0 ? highestGround + lowerLevel * interval : highestGround + mountainRise + level * interval;
double slope = Math.max(0.0, Math.min(1.0, depth / (highlands ? 0.46 : 0.10)));
slope = slope * slope * (3 - 2 * slope);
int sideTop = highlands ? baseY + (int)Math.floor(slope * (highestGround + mountainRise - baseY))
: highestGround + (int)Math.floor(slope * interval);
Material[] darkRock = {Material.BLACKSTONE, Material.BASALT, Material.POLISHED_BLACKSTONE};
if (plateau) {
for (int y = baseY + 1; y < terraceY; y++) {
int hashIndex = (int)Math.floorMod(mix64(rough + y * 0x9E3779B97F4A7C15L), darkRock.length);
data.setBlock(lx, y, lz, darkRock[hashIndex]);
}
data.setBlock(lx, terraceY, lz, Material.SAND);
heights[lx][lz] = terraceY;
} else {
int spire = highlands ? RockPlateaus.spireRise(seed,gx,gz,depth,
plugin.getConfig().getInt("planets.arrakis.highlands.spire-height",40)) : 0;
int sideSurface = Math.max(baseY, Math.min(maxY - 2, sideTop + spire));
heights[lx][lz] = sideSurface;
for (int y = baseY; y <= sideSurface; y++) {
int hashIndex = (int)Math.floorMod(mix64(rough + y * 0x9E3779B97F4A7C15L), darkRock.length);
data.setBlock(lx, y, lz, darkRock[hashIndex]);
}
}
}
}
}
private Material configuredMaterial(String path, Material fallback) {
String name = plugin.getConfig().getString(path, fallback.name());
Material material = Material.matchMaterial(name == null ? "" : name);
return material == null ? fallback : material;
}
private void placeSpiceDeposits(ChunkData data, int[][] heights, Random random, int minY, int maxY) {
int count = Math.max(0, plugin.getConfig().getInt("spice-deposits.per-chunk", 2));
for (int i = 0; i < count; i++) {
int x = random.nextInt(16), z = random.nextInt(16), y = heights[x][z];
Material surface = data.getType(x, y, z);
if (y + 1 < maxY && y > minY && (surface == Material.SAND || surface == Material.RED_SAND))
data.setBlock(x, y, z, Material.SUSPICIOUS_SAND);
}
}
private void placeRandomSpicePatch(ChunkData data, int chunkX, int chunkZ, int[][] heights) {
String path = "spice-deposits.patches.";
if (!plugin.getConfig().getBoolean(path + "enabled", true)) return;
int spacing = Math.max(128, plugin.getConfig().getInt(path + "region-spacing", 600));
int radius = Math.max(2, plugin.getConfig().getInt(path + "radius", 12));
int targetValue = Math.max(1, plugin.getConfig().getInt(path + "target-value", 5000));
int unitPrice = Math.max(1, plugin.getConfig().getInt(path + "unit-price", 15));
double density = Math.min(1.0, Math.ceil(targetValue / (double) unitPrice) / (Math.PI * radius * radius));
double chance = Math.max(0, Math.min(1, plugin.getConfig().getDouble(path + "chance-per-region", 0.35)));
int worldMinX = chunkX * 16, worldMinZ = chunkZ * 16;
int firstCellX = Math.floorDiv(worldMinX - radius, spacing), lastCellX = Math.floorDiv(worldMinX + 15 + radius, spacing);
int firstCellZ = Math.floorDiv(worldMinZ - radius, spacing), lastCellZ = Math.floorDiv(worldMinZ + 15 + radius, spacing);
long salt = 0x5350494345504154L;
for (int cellX = firstCellX; cellX <= lastCellX; cellX++) for (int cellZ = firstCellZ; cellZ <= lastCellZ; cellZ++) {
long cellSeed = mix64((long) cellX * 0x9E3779B97F4A7C15L ^ (long) cellZ * 0xC2B2AE3D27D4EB4FL ^ salt);
if (hashUnit(cellSeed) >= chance) continue;
long offsetX = Math.floorMod(mix64(cellSeed ^ 0x165667B19E3779F9L), spacing - radius * 2L);
long offsetZ = Math.floorMod(mix64(cellSeed ^ 0x85EBCA77C2B2AE63L), spacing - radius * 2L);
long centerX = (long) cellX * spacing + radius + offsetX;
long centerZ = (long) cellZ * spacing + radius + offsetZ;
for (int x = 0; x < 16; x++) for (int z = 0; z < 16; z++) {
long gx = (long) worldMinX + x, gz = (long) worldMinZ + z;
long dx = gx - centerX, dz = gz - centerZ;
if (dx * dx + dz * dz > (long) radius * radius) continue;
long blockSeed = mix64(gx * 0x9E3779B97F4A7C15L ^ gz * 0xC2B2AE3D27D4EB4FL ^ salt);
if (hashUnit(blockSeed) >= density) continue;
int y = heights[x][z];
if (data.getType(x, y, z) == Material.SAND || data.getType(x, y, z) == Material.RED_SAND)
data.setBlock(x, y, z, Material.SUSPICIOUS_SAND);
}
}
}
private static double hashUnit(long hash) { return (hash >>> 11) * 0x1.0p-53; }
private void placeOres(ChunkData data, Random random, String path, int minWorldY, int maxWorldY) {
if(planet.equals("arrakis")){
// Dunes stay visibly ordinary sand, including dense-spice areas.
// Preserve suspicious-sand deposits and exposed rock formations.
for(int x=0;x<16;x++)for(int z=0;z<16;z++)for(int y=maxWorldY;y>minWorldY;y--){
var top=data.getType(x,y,z);if(top.isAir())continue;
if(top==Material.RED_SAND||top==Material.ORANGE_TERRACOTTA)data.setBlock(x,y,z,Material.SAND);
break;
}
// Native clay disk profile: one candidate per chunk, radius 2–3,
// half-height 1. Here red sand replaces clay's wet-floor filter.
int cx=3+random.nextInt(10),cz=3+random.nextInt(10),radius=2+random.nextInt(2),surface=-1;
for(int y=maxWorldY;y>minWorldY+5;y--)if(!data.getType(cx,y,cz).isAir()){surface=y;break;}
if(surface>minWorldY+5&&data.getType(cx,surface,cz)==Material.SAND&&data.getType(cx,surface-1,cz)==Material.RED_SAND){
int center=surface-3;
for(int dx=-radius;dx<=radius;dx++)for(int dz=-radius;dz<=radius;dz++)if(dx*dx+dz*dz<=radius*radius)for(int dy=-1;dy<=1;dy++){
int x=cx+dx,z=cz+dz,y=center+dy,columnSurface=surface+radius;
while(columnSurface>minWorldY+5&&data.getType(x,columnSurface,z).isAir())columnSurface--;
if(y>columnSurface-2||data.getType(x,columnSurface,z)!=Material.SAND||data.getType(x,columnSurface-1,z)!=Material.RED_SAND)continue;
var material=data.getType(x,y,z);
if(material==Material.RED_SAND||material==Material.SAND||material==Material.SANDSTONE||material==Material.STONE)data.setBlock(x,y,z,Material.DRIED_KELP_BLOCK);
}
}
}
// Arrakis now permits only its explicitly configured coal and emerald deposits.
org.bukkit.configuration.ConfigurationSection ores = plugin.getConfig().getConfigurationSection(path + "ores");
if (ores == null) return;
int minY = Math.max(minWorldY + 1, plugin.getConfig().getInt(path + "ores.min-y", -48));
int maxY = Math.min(maxWorldY - 4, plugin.getConfig().getInt(path + "ores.max-y", 48));
int veinSize = Math.max(1, Math.min(16, plugin.getConfig().getInt(path + "ores.vein-size", 5)));
if (maxY < minY) return;
for (String key : ores.getKeys(false)) {
Material ore = Material.matchMaterial(key);
if (ore == null || (!key.endsWith("_ORE") && !(planet.equals("giedi_prime") && ore == Material.ANCIENT_DEBRIS))) continue;
if(planet.equals("arrakis")&&ore!=Material.COAL_ORE&&ore!=Material.EMERALD_ORE)continue;
int attempts = Math.max(0, Math.min(64, ores.getInt(key, 0)));
int effectiveVeinSize = ore == Material.ANCIENT_DEBRIS
? Math.max(1, Math.min(16, plugin.getConfig().getInt(path + "ancient-debris.vein-size", 5))) : veinSize;
int oreMinY = ore == Material.ANCIENT_DEBRIS ? Math.max(minWorldY + 1, plugin.getConfig().getInt(path + "ancient-debris.min-y", -59)) : minY;
int oreMaxY = ore == Material.ANCIENT_DEBRIS ? Math.min(maxWorldY - 4, plugin.getConfig().getInt(path + "ancient-debris.max-y", 16)) : maxY;
if (oreMaxY < oreMinY) continue;
for (int attempt = 0; attempt < attempts; attempt++) {
int x = random.nextInt(16), z = random.nextInt(16), y = oreMinY + random.nextInt(oreMaxY - oreMinY + 1);
for (int n = 0; n < effectiveVeinSize; n++) {
int vx = Math.max(0, Math.min(15, x + random.nextInt(3) - 1));
int vz = Math.max(0, Math.min(15, z + random.nextInt(3) - 1));
int vy = Math.max(oreMinY, Math.min(oreMaxY, y + random.nextInt(3) - 1));
Material existing = data.getType(vx, vy, vz);
if (existing == Material.STONE || existing == Material.DEEPSLATE || existing == Material.TUFF) data.setBlock(vx, vy, vz, ore);
}
}
}
}
private void placeJungleTree(ChunkData data, int x, int y, int z, Random random, int maxY) {
int height = 4 + random.nextInt(4);
if (y + height + 2 >= maxY || data.getType(x, y - 1, z) != Material.GRASS_BLOCK) return;
for (int dy = 0; dy < height; dy++) data.setBlock(x, y + dy, z, Material.JUNGLE_LOG);
for (int dy = height - 2; dy <= height + 1; dy++) {
int radius = dy >= height ? 1 : 2;
for (int dx = -radius; dx <= radius; dx++) for (int dz = -radius; dz <= radius; dz++) {
if (Math.abs(dx) == radius && Math.abs(dz) == radius && random.nextBoolean()) continue;
int lx = x + dx, lz = z + dz, ly = y + dy;
if (lx >= 0 && lx < 16 && lz >= 0 && lz < 16 && data.getType(lx, ly, lz).isAir()) data.setBlock(lx, ly, lz, Material.JUNGLE_LEAVES);
}
}
}
}
private static final class PlanetBiomeProvider extends BiomeProvider {
private final DuneTerrain plugin;
private final String planet;
private final Biome biome, highlands, denseSpice;
PlanetBiomeProvider(DuneTerrain plugin, String planet) {
this.plugin = plugin; this.planet = planet;
String configured = plugin.getConfig().getString("planets." + planet + ".biome", "DESERT");
NamespacedKey key = NamespacedKey.fromString(configured.toLowerCase(Locale.ROOT));
Biome selected = key == null ? null : Registry.BIOME.get(key);
this.biome = selected == null ? Biome.DESERT : selected;
String custom = plugin.getConfig().getString("planets.arrakis.highlands.biome", "dunerealms:dune-highlands");
NamespacedKey customKey = NamespacedKey.fromString(custom);
this.denseSpice = planet.equals("arrakis") && plugin.getConfig().getBoolean("dense-spice.enabled", true)
? Registry.BIOME.get(new NamespacedKey("dunerealms", "dense-spice")) : null;
this.highlands = planet.equals("arrakis") && plugin.getConfig().getBoolean("planets.arrakis.highlands.enabled", true)
&& customKey != null ? Registry.BIOME.get(customKey) : null;
}
@Override public Biome getBiome(WorldInfo info, int x, int y, int z) {
if(TemperateLandscape.enabled(planet))return TemperateLandscape.biome(info,x,y,z,planet);
if (denseSpice != null && DenseSpice.contains(info.getSeed(),x,z,Math.max(128,plugin.getConfig().getInt("dense-spice.spacing",512)))) return denseSpice;
if (highlands == null) return biome;
String path = "planets.arrakis.darkstone-islands.";
int minimumGap = Math.max(192, plugin.getConfig().getInt("planets.arrakis.highlands.min-spacing", 300));
int maximumGap = Math.max(minimumGap, plugin.getConfig().getInt("planets.arrakis.highlands.max-spacing", 500));
int minimum = Math.max(6, plugin.getConfig().getInt(path + "min-radius", 45));
int maximum = Math.max(minimum, plugin.getConfig().getInt(path + "max-radius", 55));
double scale = Math.max(.001, plugin.getConfig().getDouble("planets.arrakis.terrain.noise-scale", .02));
return RockPlateaus.regionDepth(x,z,minimumGap,maximumGap,minimum,maximum,scale) >= 0 ? highlands : biome;
}
@Override public List<Biome> getBiomes(WorldInfo info) {
if(TemperateLandscape.enabled(planet))return TemperateLandscape.biomes(planet);
Set<Biome> all = new LinkedHashSet<>(); all.add(biome); if(highlands!=null)all.add(highlands); if(denseSpice!=null)all.add(denseSpice); return List.copyOf(all);
}
}
private static long mix64(long value) {
value = (value ^ (value >>> 30)) * 0xBF58476D1CE4E5B9L;
value = (value ^ (value >>> 27)) * 0x94D049BB133111EBL;
return value ^ (value >>> 31);
}
private static final class SietchPopulator extends BlockPopulator {
private final DuneTerrain plugin;
private final java.util.concurrent.ConcurrentHashMap<RockPlateaus.Shape,List<HighlandSietches.Site>> highlandSites = new java.util.concurrent.ConcurrentHashMap<>();
private SietchPopulator(DuneTerrain plugin) { this.plugin = plugin; }
@Override public void populate(WorldInfo world, Random random, int cx, int cz, LimitedRegion region) {
if (!world.getName().equalsIgnoreCase("arrakis")) return;
if (!plugin.getConfig().getBoolean("sietches.enabled", true)) return;
populateHighlands(world,cx,cz,region);
int spacing = Math.max(256, plugin.getConfig().getInt("sietches.spacing", 2000));
int centerX = cx * 16 + 8, centerZ = cz * 16 + 8;
long cellX = Math.floorDiv(centerX, spacing), cellZ = Math.floorDiv(centerZ, spacing);
long h1 = mix64(cellX * 0x9E3779B97F4A7C15L ^ cellZ * 0xC2B2AE3D27D4EB4FL ^ 0x534945544348L);
long h2 = mix64(cellZ * 0x165667B19E3779F9L ^ cellX * 0x85EBCA77C2B2AE63L ^ ~0x534945544348L);
long anchorX = cellX * spacing + 8 + Math.floorMod(h1, spacing - 16);
long anchorZ = cellZ * spacing + 8 + Math.floorMod(h2, spacing - 16);
if (Math.floorDiv(anchorX, 16) != cx || Math.floorDiv(anchorZ, 16) != cz) return;
int x = (int) anchorX, z = (int) anchorZ;
int y = region.getHighestBlockYAt(x, z);
if (y < world.getMinHeight() + 40 || y > world.getMaxHeight() - 4 || y - 36 < world.getMinHeight()) return;
// Enlarged hub, side chambers, cache chamber, and reservoir. The surface entrance stays compact.
int hy = y - 11;
carveRoom(region, x, hy, z, 10, 6, 10);
carveTunnelNetwork(region, new int[][]{
{x - 8, hy - 3, z - 2}, {x - 12, hy - 4, z - 2}, {x - 16, hy - 5, z - 2}
});
carveRoom(region, x - 18, hy - 6, z - 2, 8, 4, 8);
carveTunnelNetwork(region, new int[][]{
{x + 8, hy - 3, z + 2}, {x + 12, hy - 4, z + 2}, {x + 16, hy - 5, z + 2}
});
carveRoom(region, x + 18, hy - 6, z + 2, 8, 4, 8);
carveTunnelNetwork(region, new int[][]{
{x, hy - 3, z - 3}, {x - 3, hy - 4, z - 5}, {x - 6, hy - 5, z - 8},
{x - 4, hy - 6, z - 11}, {x, hy - 7, z - 12}, {x + 3, hy - 8, z - 11},
{x, hy - 10, z - 10}
});
carveRoom(region, x, hy - 12, z - 10, 8, 4, 8);
carveRoom(region, x, hy - 23, z + 8, 14, 10, 14);
// A broad, rough cave mouth opens from the surface and slopes down into the hub.
carveCaveEntrance(region, x, z, hy);
// Long switchbacks keep the descent gradual from the hub to the enlarged reservoir.
carveTunnelNetwork(region, new int[][]{
{x, hy - 3, z + 3}, {x - 4, hy - 4, z + 5}, {x - 8, hy - 5, z + 8},
{x - 10, hy - 6, z + 12}, {x - 8, hy - 7, z + 14}, {x - 4, hy - 8, z + 14},
{x - 2, hy - 9, z + 12}, {x - 5, hy - 10, z + 9}, {x - 8, hy - 11, z + 7},
{x - 10, hy - 12, z + 9}, {x - 8, hy - 13, z + 12}, {x - 5, hy - 14, z + 13},
{x - 3, hy - 15, z + 10}, {x - 5, hy - 16, z + 7}, {x - 7, hy - 17, z + 8},
{x - 5, hy - 18, z + 10}, {x - 4, hy - 19, z + 9}, {x - 5, hy - 20, z + 8}
});
// The waterfall runs beside the ramp and feeds a broad pool at the bottom.
for (int dy = -4; dy >= -25; dy--) {
set(region, x + 3, hy + dy, z + 5, Material.WATER);
set(region, x + 2, hy + dy, z + 5, Material.STONE);
set(region, x + 4, hy + dy, z + 5, Material.STONE);
set(region, x + 3, hy + dy, z + 4, Material.STONE);
set(region, x + 3, hy + dy, z + 6, Material.STONE);
}
SietchReservoirs.build(region,x,hy-29,z+8,6,5,4);
int variant=(int)Math.floorMod(DenseSpice.mix(cellX*341873128712L^cellZ*132897987541L),3);
if(variant>0){int side=variant==1?-1:1;carveRoom(region,x+side*10,hy-15,z-14,5,3,6);carveTunnelNetwork(region,new int[][]{{x,hy-12,z-10},{x+side*5,hy-13,z-12},{x+side*10,hy-15,z-14}});}
furnishSleepingHall(region, x - 18, hy - 6, z - 2);
furnishKitchen(region, x + 18, hy - 6, z + 2);
placePersonalChest(region, x, hy - 14, z - 10, cellX, cellZ);
for (int[] lamp : new int[][]{{0,-1,0},{-20,-5,-2},{20,-5,2},{0,-11,-11}})
set(region, x + lamp[0], hy + lamp[1], z + lamp[2], Material.TORCH);
}
private void populateHighlands(WorldInfo world,int cx,int cz,LimitedRegion region) {
if(!plugin.getConfig().getBoolean("planets.arrakis.highlands.enabled",true)
||!plugin.getConfig().getBoolean("sietches.highlands.enabled",true))return;
int minGap=Math.max(192,plugin.getConfig().getInt("planets.arrakis.highlands.min-spacing",300));
int maxGap=Math.max(minGap,plugin.getConfig().getInt("planets.arrakis.highlands.max-spacing",500));
int spacing=(minGap+maxGap)/2;
int minRadius=Math.max(6,plugin.getConfig().getInt("planets.arrakis.darkstone-islands.min-radius",45));
int maxRadius=Math.max(minRadius,plugin.getConfig().getInt("planets.arrakis.darkstone-islands.max-radius",55));
double scale=Math.max(.001,plugin.getConfig().getDouble("planets.arrakis.terrain.noise-scale",.02));
int reach=(int)Math.ceil(maxRadius*2.0)+3;
if(highlandSites.size()>2048)highlandSites.clear();
for(int gx=Math.floorDiv(cx*16-reach,spacing);gx<=Math.floorDiv(cx*16+15+reach,spacing);gx++)
for(int gz=Math.floorDiv(cz*16-reach,spacing);gz<=Math.floorDiv(cz*16+15+reach,spacing);gz++) {
if(!RockPlateaus.activeCell(gx,gz))continue;
long seed=RockPlateaus.formationSeed(gx,gz);
var shape=RockPlateaus.shape(seed,RockPlateaus.centerX(gx,minGap,maxGap),RockPlateaus.centerZ(gz,minGap,maxGap),RockPlateaus.radius(seed,minRadius,maxRadius),scale);
var sites=highlandSites.computeIfAbsent(shape,k->HighlandSietches.sites(k,
plugin.getConfig().getInt("sietches.highlands.frequency-multiplier",3),plugin.getConfig().getInt("sietches.highlands.minimum-per-region",3)));
for(var site:sites) {
int x=site.x(),z=site.z();
if(Math.floorDiv(x,16)!=cx||Math.floorDiv(z,16)!=cz)continue;
int surface=region.getHighestBlockYAt(x,z),hy=surface-11;
if(hy-12<=world.getMinHeight()||surface+2>=world.getMaxHeight())continue;
// Compact multi-room caves fit three sites without the large desert template colliding.
carveRoom(region,x,hy,z,7,4,7);
carveRoom(region,x-5,hy-3,z+5,4,3,4);
carveRoom(region,x+5,hy-3,z+5,4,3,4);
carveTunnelNetwork(region,new int[][]{{x,hy-1,z},{x-3,hy-2,z+3},{x-5,hy-3,z+5}});
carveTunnelNetwork(region,new int[][]{{x,hy-1,z},{x+3,hy-2,z+3},{x+5,hy-3,z+5}});
carveCaveEntrance(region,x,z,hy);
furnishSleepingHall(region,x-5,hy-4,z+5);
furnishKitchen(region,x+5,hy-4,z+5);
carveRoom(region,x,hy-8,z+6,4,3,4);
carveTunnelNetwork(region,new int[][]{{x,hy-1,z+2},{x+2,hy-3,z+4},{x+2,hy-5,z+6},{x,hy-8,z+6}});
SietchReservoirs.build(region,x,hy-11,z+6,3,3,1);
placePersonalChest(region,x,hy-2,z-3,site.cacheId(),0x484947484c414e44L);
set(region,x,hy-3,z,Material.CHISELED_STONE_BRICKS);
set(region,x,hy-2,z,Material.LANTERN);
}
}
}
private static void carveRoom(LimitedRegion region, int cx, int cy, int cz, int rx, int ry, int rz) {
for (int dx = -rx; dx <= rx; dx++) for (int dy = -ry; dy <= ry; dy++) for (int dz = -rz; dz <= rz; dz++) {
double outer = dx * dx / (double)(rx * rx) + dy * dy / (double)(ry * ry) + dz * dz / (double)(rz * rz);
if (outer > 1.15) continue;
int x = cx + dx, y = cy + dy, z = cz + dz;
if (outer >= 0.58) {
long variation = mix64((long)x * 341873128712L ^ (long)y * 132897987541L ^ z);
Material wall = switch ((int)Math.floorMod(variation, 10)) {
case 0, 1 -> Material.TUFF;
case 2 -> Material.ANDESITE;
case 3 -> Material.COBBLED_DEEPSLATE;
case 4 -> Material.COBBLESTONE;
case 5 -> Material.MOSSY_COBBLESTONE;
default -> Material.STONE;
};
set(region, x, y, z, wall);
} else set(region, x, y, z, Material.AIR);
}
}
private static void carveCaveEntrance(LimitedRegion region, int x, int z, int hubY) {
int entryX = x + 6, entryZ = z - 7;
int outsideX = x + 11;
int surfaceY = region.getHighestBlockYAt(outsideX, entryZ);
int mouthY = Math.max(hubY + 4, surfaceY - 3);
// Hollow a rough chamber just behind the stone arch, then connect it to the hub.
carveRoom(region, entryX, mouthY, entryZ, 3, 2, 3);
carveCaveTunnel(region, outsideX, surfaceY - 1, entryZ, x + 6, mouthY, entryZ);
carveTunnelNetwork(region, new int[][]{
{x + 6, mouthY, entryZ}, {x + 3, mouthY - 1, z - 9}, {x, mouthY - 2, z - 11},
{x - 4, mouthY - 3, z - 10}, {x - 6, mouthY - 4, z - 7},
{x - 5, mouthY - 5, z - 3}, {x - 2, mouthY - 6, z - 1}, {x, hubY + 1, z}
});
// Irregular stone and tuff form a visible cave arch around the entrance.
int faceX = x + 7;
for (int dy = -3; dy <= 3; dy++) for (int dz = -4; dz <= 4; dz++) {
double arch = dy * dy / 16.0 + dz * dz / 25.0;
if (arch > 1.35) continue;
if (arch < 0.72) {
set(region, faceX, mouthY + dy, entryZ + dz, Material.AIR);
continue;
}
long variation = mix64((long)(faceX + dz) * 341873128712L ^ (long)(mouthY + dy) * 132897987541L ^ 0x4341564541524348L);
Material rock = switch ((int)Math.floorMod(variation, 5)) {
case 0 -> Material.TUFF;
case 1 -> Material.ANDESITE;
case 2 -> Material.COBBLED_DEEPSLATE;
default -> Material.STONE;
};
set(region, faceX, mouthY + dy, entryZ + dz, rock);
}
}
private static void carveTunnel(LimitedRegion region, double ax, double ay, double az, double bx, double by, double bz) {
int steps = (int)Math.ceil(Math.sqrt((bx-ax)*(bx-ax) + (by-ay)*(by-ay) + (bz-az)*(bz-az)) * 1.5);
for (int i = 0; i <= steps; i++) {
double t = i / (double)Math.max(1, steps);
int cx = (int)Math.round(ax + (bx-ax)*t), cy = (int)Math.round(ay + (by-ay)*t), cz = (int)Math.round(az + (bz-az)*t);
for (int dx = -1; dx <= 1; dx++) for (int dy = -1; dy <= 1; dy++) for (int dz = -1; dz <= 1; dz++)
if (dx*dx + dy*dy + dz*dz <= 2) set(region, cx+dx, cy+dy, cz+dz, Material.AIR);
}
}
private static void carveTunnelNetwork(LimitedRegion region, int[][] points) {
for (int i = 1; i < points.length; i++) {
int[] from = points[i - 1], to = points[i];
carveTunnel(region, from[0], from[1], from[2], to[0], to[1], to[2]);
}
}
private static void carveCaveTunnel(LimitedRegion region, double ax, double ay, double az, double bx, double by, double bz) {
int steps = (int)Math.ceil(Math.sqrt((bx-ax)*(bx-ax) + (by-ay)*(by-ay) + (bz-az)*(bz-az)) * 1.5);
for (int i = 0; i <= steps; i++) {
double t = i / (double)Math.max(1, steps);
int cx = (int)Math.round(ax + (bx-ax)*t), cy = (int)Math.round(ay + (by-ay)*t), cz = (int)Math.round(az + (bz-az)*t);
for (int dx = -2; dx <= 2; dx++) for (int dy = -2; dy <= 2; dy++) for (int dz = -2; dz <= 2; dz++)
if (dx*dx + dy*dy + dz*dz <= 4) set(region, cx+dx, cy+dy, cz+dz, Material.AIR);
}
}
private static void furnishSleepingHall(LimitedRegion r, int x, int y, int z) {
for (int i = -1; i <= 1; i++) {
set(r, x+i, y-1, z, Material.POLISHED_ANDESITE);
set(r, x+i, y, z, Material.RED_CARPET);
set(r, x+i, y+1, z, Material.AIR);
}
set(r, x-1, y, z, Material.WHITE_CARPET);
set(r, x+1, y, z, Material.WHITE_CARPET);
set(r, x-2, y-1, z+2, Material.BARREL);
}
private static void furnishKitchen(LimitedRegion r, int x, int y, int z) {
set(r, x-2, y-1, z, Material.STONE_BRICKS);
set(r, x-2, y, z, Material.FURNACE);
set(r, x-1, y-1, z, Material.STONE_BRICKS);
set(r, x-1, y, z, Material.SMOKER);
set(r, x, y-1, z, Material.STONE_BRICKS);
set(r, x, y, z, Material.CRAFTING_TABLE);
set(r, x+2, y-1, z+1, Material.BARREL);
set(r, x+2, y, z+1, Material.CAULDRON);
}
private void placePersonalChest(LimitedRegion r, int x, int y, int z, long cellX, long cellZ) {
set(r, x, y-1, z, Material.CHISELED_STONE_BRICKS);
set(r, x, y, z, Material.CHEST);
BlockState state = r.getBlockState(x, y, z);
if (state instanceof Chest chest) {
String id = Long.toUnsignedString(mix64(cellX * 0x9E3779B97F4A7C15L ^ cellZ * 0xC2B2AE3D27D4EB4FL ^ 0x534945544348L), 16);
chest.setCustomName("Personal Sietch Cache");
chest.getPersistentDataContainer().set(plugin.sietchLootIdKey, PersistentDataType.STRING, id);
chest.update(true, false);
}
}
private static void set(LimitedRegion region, int x, int y, int z, Material material) {
if (region.isInRegion(x, y, z)) region.setType(x, y, z, material);
}
}
private static final class SpiceBlowPopulator extends BlockPopulator {
private static final long SALT = 0x5350494345424c4fL;
private final DuneTerrain plugin;
private SpiceBlowPopulator(DuneTerrain plugin) { this.plugin = plugin; }
@Override public void populate(WorldInfo world, Random random, int chunkX, int chunkZ, LimitedRegion region) {
if (!world.getName().equalsIgnoreCase("arrakis") || !plugin.getConfig().getBoolean("spice-blow.enabled", true)) return;
int spacing = Math.max(256, plugin.getConfig().getInt("spice-blow.spacing", 2000));
long centerX = chunkX * 16L + 8, centerZ = chunkZ * 16L + 8;
long cellX = Math.floorDiv(centerX, spacing), cellZ = Math.floorDiv(centerZ, spacing);
long h1 = mix64(cellX * 0x9E3779B97F4A7C15L ^ cellZ * 0xC2B2AE3D27D4EB4FL ^ SALT);
long h2 = mix64(cellZ * 0x165667B19E3779F9L ^ cellX * 0x85EBCA77C2B2AE63L ^ ~SALT);
long anchorX = cellX * spacing + 8 + Math.floorMod(h1, spacing - 16);
long anchorZ = cellZ * spacing + 8 + Math.floorMod(h2, spacing - 16);
if (Math.floorDiv(anchorX, 16) != chunkX || Math.floorDiv(anchorZ, 16) != chunkZ) return;
int x = (int)anchorX, z = (int)anchorZ, y = region.getHighestBlockYAt(x, z);
if (y < world.getMinHeight() + 2 || y + 2 >= world.getMaxHeight()) return;
if (!region.isInRegion(x, y, z) || region.getType(x, y, z) != Material.SAND) return;
for (int dx = -1; dx <= 1; dx++) for (int dz = -1; dz <= 1; dz++)
if (region.isInRegion(x + dx, y, z + dz)) region.setType(x + dx, y, z + dz, Material.MAGMA_BLOCK);
if (region.isInRegion(x, y + 1, z)) region.setType(x, y + 1, z, Material.MAGMA_BLOCK);
}
}
}

View file

@ -0,0 +1,45 @@
package com.example.duneterrain;
import java.util.*;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Transformation;
import org.joml.Vector3f;
import org.joml.Quaternionf;
/** One display per animal. The native carrier retains AI, growth and hitbox. */
final class FaunaModels implements AutoCloseable {
private static final NamespacedKey OWNER=new NamespacedKey("dunerealms","fauna_model_for");
private final Map<UUID,ItemDisplay> displays=new HashMap<>();
private final Map<UUID,LivingEntity> carriers=new HashMap<>();
private final Map<UUID,Double> sizes=new HashMap<>();
FaunaModels(Plugin plugin){}
void reset(){var world=Bukkit.getWorld("arrakis");if(world!=null)for(var display:world.getEntitiesByClass(ItemDisplay.class))if(display.getPersistentDataContainer().has(OWNER,PersistentDataType.STRING))display.remove();}
void track(LivingEntity carrier,String model,double size){
UUID id=carrier.getUniqueId();ItemDisplay display=displays.get(id);
if(display==null||!display.isValid()){
display=carrier.getWorld().spawn(carrier.getLocation(),ItemDisplay.class,d->{d.setPersistent(false);d.setInvulnerable(true);d.setGravity(false);d.setTeleportDuration(4);d.setInterpolationDuration(4);d.setViewRange(1.25f);d.getPersistentDataContainer().set(OWNER,PersistentDataType.STRING,id.toString());var stack=new ItemStack(Material.PAPER);var meta=stack.getItemMeta();meta.setItemModel(new NamespacedKey("dunerealms","entity/"+model));stack.setItemMeta(meta);d.setItemStack(stack);d.setItemDisplayTransform(ItemDisplay.ItemDisplayTransform.NONE);});
displays.put(id,display);carriers.put(id,carrier);
}
carrier.setInvisible(true);
NamespacedKey selected=new NamespacedKey("dunerealms","entity/"+model);
var shown=display.getItemStack();var shownMeta=shown.getItemMeta();
if(!selected.equals(shownMeta.getItemModel())){shownMeta.setItemModel(selected);shown.setItemMeta(shownMeta);display.setItemStack(shown);}
// Living-entity ticks recalculate visibility from effects; a raw entity flag
// alone is cleared between model updates on current Paper.
var invisible=carrier.getPotionEffect(PotionEffectType.INVISIBILITY);if(invisible==null||invisible.getDuration()<40)carrier.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY,200,0,false,false,false));
if(!Objects.equals(sizes.get(id),size)){float s=(float)size;display.setTransformation(new Transformation(new Vector3f(0,.5f*s,0),new Quaternionf(),new Vector3f(s),new Quaternionf()));sizes.put(id,size);}
Location at=carrier.getLocation();at.setPitch(0);Location last=display.getLocation();
if(last.distanceSquared(at)>.0001||Math.abs(last.getYaw()-at.getYaw())>.5)display.teleport(at);
}
void retain(Set<UUID> alive){for(UUID id:new ArrayList<>(displays.keySet()))if(!alive.contains(id))remove(id);}
void remove(UUID id){remove(id,true);}
void unload(UUID id){remove(id,false);}
private void remove(UUID id,boolean reveal){ItemDisplay display=displays.remove(id);if(display!=null)display.remove();LivingEntity carrier=carriers.remove(id);if(reveal&&carrier!=null&&carrier.isValid()){carrier.removePotionEffect(PotionEffectType.INVISIBILITY);carrier.setInvisible(false);}sizes.remove(id);}
@Override public void close(){for(UUID id:new ArrayList<>(displays.keySet()))remove(id);}
}

View file

@ -0,0 +1,23 @@
package com.example.duneterrain;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataType;
import java.util.UUID;
/** Bridges actual animal events to the existing durable native quest receipt queue. */
final class FaunaProof {
private FaunaProof(){}
static void record(Player actor,String species,String action,LivingEntity entity){
if(actor==null||entity==null)return;
var translator=Bukkit.getPluginManager().getPlugin("JarvisTranslator");
if(translator==null||!translator.isEnabled())return;
try{translator.getClass().getMethod("recordFaunaActivity",Player.class,String.class,String.class,LivingEntity.class).invoke(translator,actor,species,action,entity);}
catch(ReflectiveOperationException failure){translator.getLogger().warning("Fauna quest receipt unavailable: "+species+"/"+action);}
}
static void milestone(Player actor,String kind,UUID reference){if(actor==null||reference==null)return;var translator=Bukkit.getPluginManager().getPlugin("JarvisTranslator");if(translator==null||!translator.isEnabled())return;try{translator.getClass().getMethod("recordHusbandryActivity",Player.class,String.class,UUID.class,int.class).invoke(translator,actor,kind,reference,1);}catch(ReflectiveOperationException failure){translator.getLogger().warning("Husbandry receipt unavailable: "+kind);}}
static void markDrop(ItemStack stack,UUID reference){if(Bukkit.getServer()==null)return;var translator=Bukkit.getPluginManager().getPlugin("JarvisTranslator");if(!(translator instanceof org.bukkit.plugin.java.JavaPlugin p)||!p.isEnabled()||!p.getConfig().getBoolean("fauna-quest-observations-enabled",false))return;var meta=stack.getItemMeta();if(meta==null)return;meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","fauna_collect_source"),PersistentDataType.STRING,reference.toString());stack.setItemMeta(meta);}
}

View file

@ -0,0 +1,66 @@
package com.example.duneterrain;
import org.bukkit.*;
import org.bukkit.block.Chest;
import org.bukkit.event.*;
import org.bukkit.event.world.LootGenerateEvent;
import org.bukkit.generator.*;
import org.bukkit.inventory.ItemStack;
import java.util.*;
/** Arrakis temple adaptation: stepped roof, upper chamber, stair and buried vault. */
final class HarkonnenFortress extends BlockPopulator implements Listener {
static final NamespacedKey LOOT=new NamespacedKey("dunerealms","chests/old-harkonnen-fortress");
private final DuneTerrain plugin;
HarkonnenFortress(DuneTerrain plugin) { this.plugin=plugin; }
static boolean attempt(long seed,int cx,int cz,int rarity) {
return Math.floorMod(DenseSpice.mix(seed^cx*0x9e3779b97f4a7c15L^cz*0xc2b2ae3d27d4eb4fL^0x4841524b4f4e4e45L),Math.max(1,rarity))==0;
}
@Override public void populate(WorldInfo world,Random random,int cx,int cz,LimitedRegion r) {
if(!world.getName().equalsIgnoreCase("arrakis")||!plugin.getConfig().getBoolean("harkonnen-fortress.enabled",true)
|| !attempt(world.getSeed(),cx,cz,plugin.getConfig().getInt("harkonnen-fortress.rarity",1000)))return;
int x=cx*16+8,z=cz*16+8,y=r.getHighestBlockYAt(x,z);
if(y-7<=world.getMinHeight()||y+10>=world.getMaxHeight())return;
for(int dx:new int[]{-7,7})for(int dz:new int[]{-8,8})
if(!r.isInRegion(x+dx,y,z+dz)||Math.abs(r.getHighestBlockYAt(x+dx,z+dz)-y)>6)return;
// Jungle-temple proportions translated into sandstone and Harkonnen dark stone.
for(int dx=-6;dx<=6;dx++)for(int dz=-7;dz<=7;dz++)for(int dy=-6;dy<=6;dy++) {
boolean shell=dy==-6||dy==0||dy==6||Math.abs(dx)==6||Math.abs(dz)==7;
Material m=shell?((dx+dz+dy)%5==0?Material.CRACKED_POLISHED_BLACKSTONE_BRICKS:Material.SANDSTONE):Material.AIR;
r.setType(x+dx,y+dy,z+dz,m);
}
for(int level=0;level<3;level++)for(int dx=-5+level;dx<=5-level;dx++)for(int dz=-6+level;dz<=6-level;dz++)
r.setType(x+dx,y+7+level,z+dz,Material.CUT_SANDSTONE);
for(int dx:new int[]{-5,5})for(int dz:new int[]{-6,6})for(int dy=1;dy<=5;dy++)r.setType(x+dx,y+dy,z+dz,Material.POLISHED_BLACKSTONE_BRICKS);
for(int dy=1;dy<=3;dy++)r.setType(x,y+dy,z-7,Material.AIR);
for(int step=0;step<6;step++) {
r.setType(x-3,y-step,z+4-step,Material.SANDSTONE);
for(int clear=1;clear<=3;clear++)r.setType(x-3,y-step+clear,z+4-step,Material.AIR);
}
r.setType(x+3,y-5,z+3,Material.CHEST);
if(r.getBlockState(x+3,y-5,z+3) instanceof Chest chest) {
chest.setCustomName("Old Harkveen Fortress");
var table=Bukkit.getLootTable(LOOT);
if(table!=null){chest.setLootTable(table);chest.setSeed(DenseSpice.mix(world.getSeed()^cx^((long)cz<<32)));}
else for(ItemStack item:kit())chest.getSnapshotInventory().addItem(item);
chest.update(true,false);
}
// Ruined red banner and lanterns, no moss, jungle trees, farms or hay.
r.setType(x,y+4,z-8,Material.RED_WALL_BANNER);
var banner=Material.RED_WALL_BANNER.createBlockData();
((org.bukkit.block.data.Directional)banner).setFacing(org.bukkit.block.BlockFace.NORTH);
r.setBlockData(x,y+4,z-8,banner);
r.setType(x+3,y-2,z+3,Material.LANTERN);
}
@SuppressWarnings("unchecked") private List<ItemStack> kit() {
var core=Bukkit.getPluginManager().getPlugin("DuneCore");
if(core!=null && core.isEnabled())try {
return (List<ItemStack>)core.getClass().getMethod("createFactionKit",String.class).invoke(core,"Harkonnen");
}catch(ReflectiveOperationException ex){plugin.getLogger().warning("Harkveen kit requires updated DuneCore: "+ex.getMessage());}
return List.of(new ItemStack(Material.IRON_SWORD),new ItemStack(Material.BREAD,8));
}
@EventHandler(ignoreCancelled=true) public void loot(LootGenerateEvent e) {
if(!e.getLootTable().getKey().equals(LOOT))return;
List<ItemStack> items=new ArrayList<>(e.getLoot());items.addAll(kit());e.setLoot(items);
}
}

View file

@ -0,0 +1,33 @@
package com.example.duneterrain;
import java.util.*;
/** Threefold regional placement, independent of the legacy open-desert sietch grid. */
final class HighlandSietches {
record Site(int x,int z,long cacheId) {}
static List<Site> sites(RockPlateaus.Shape shape,int multiplier,int minimum) {
int target=Math.max(3,Math.min(12,Math.max(minimum,multiplier)));
List<Site> candidates=new ArrayList<>();
int extent=(int)Math.ceil(shape.radius()*1.6);
for(int dx=-extent;dx<=extent;dx+=2)for(int dz=-extent;dz<=extent;dz+=2) {
int x=(int)shape.centerX()+dx,z=(int)shape.centerZ()+dz;
if(shape.depth(x,z)<.25)continue;
candidates.add(new Site(x,z,DenseSpice.mix(shape.seed()^x*341873128712L^z*132897987541L^0x5349455443484849L)));
}
List<Site> result=new ArrayList<>();
// Start at one end, then choose the farthest remaining sites, keeping compact caves apart.
Site center=new Site((int)shape.centerX(),(int)shape.centerZ(),0);
candidates.sort(Comparator.<Site>comparingLong(s->distance(s,center)).reversed().thenComparingLong(Site::cacheId));
while(result.size()<target&&!candidates.isEmpty()) {
Site best=null;long distance=-1;
for(Site candidate:candidates) {
long nearest=result.isEmpty()?Long.MAX_VALUE:result.stream().mapToLong(s->distance(s,candidate)).min().orElse(0);
if(nearest>distance){distance=nearest;best=candidate;}
}
if(!result.isEmpty()&&distance<26L*26)break;
result.add(best);candidates.remove(best);
}
return List.copyOf(result);
}
private static long distance(Site a,Site b) {long dx=a.x()-b.x(),dz=a.z()-b.z();return dx*dx+dz*dz;}
}

View file

@ -0,0 +1,119 @@
package com.example.duneterrain;
import java.util.*;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.entity.*;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.world.EntitiesUnloadEvent;
import org.bukkit.inventory.*;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.Plugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
/** Armadillo locomotion, defensive curling and native breeding, with a separate, real jerboa model. */
final class JerboaMobs implements Listener {
static final NamespacedKey KIND=new NamespacedKey("dunerealms","jerboa"),ROLLED=new NamespacedKey("dunerealms","jerboa_mother_rolled");
private static final NamespacedKey EI=new NamespacedKey("executableitems","ei-id");
static final double SPEED=.225, MOTHER_CHANCE=.005;
private final Plugin plugin;
private final ArrakisEcology.Items items;
private final java.util.function.DoubleSupplier random;
private final Set<UUID> replacing=new HashSet<>();
private final Map<UUID,UUID> retaliation=new HashMap<>();
private final Map<UUID,Long> instantFeeds=new HashMap<>();
private final FaunaModels models;
private long ticks;
JerboaMobs(Plugin plugin,ArrakisEcology.Items items,java.util.function.DoubleSupplier random){this.plugin=plugin;this.items=items;this.random=random;models=new FaunaModels(plugin);}
void start(){models.reset();Bukkit.getPluginManager().registerEvents(this,plugin);Bukkit.getScheduler().runTaskTimer(plugin,this::maintain,1,4);}
static boolean isJerboa(Entity e){return e.getPersistentDataContainer().has(KIND,PersistentDataType.BYTE);}
static boolean mother(Entity e){return e.getPersistentDataContainer().getOrDefault(KIND,PersistentDataType.BYTE,(byte)0)==2;}
private static boolean arrakis(Entity e){return e.getWorld().getName().equalsIgnoreCase("arrakis");}
private static String itemId(ItemStack item){return item==null||!item.hasItemMeta()?null:item.getItemMeta().getPersistentDataContainer().get(EI,PersistentDataType.STRING);}
private static void prepare(Armadillo cat,int age){cat.getPersistentDataContainer().set(KIND,PersistentDataType.BYTE,(byte)1);cat.setAge(age);cat.setSilent(true);cat.setRemoveWhenFarAway(true);cat.customName(Component.text("Jerboa",NamedTextColor.YELLOW));var speed=cat.getAttribute(Attribute.MOVEMENT_SPEED);if(speed!=null)speed.setBaseValue(SPEED);var health=cat.getAttribute(Attribute.MAX_HEALTH);if(health!=null){health.setBaseValue(3);cat.setHealth(3);}}
private Armadillo spawn(Location at,int age){return at.getWorld().spawn(at,Armadillo.class,c->prepare(c,age));}
void replace(Rabbit rabbit){
if(!rabbit.isValid()||rabbit.hasMetadata("NPC")||!replacing.add(rabbit.getUniqueId()))return;
try{Armadillo cat=spawn(rabbit.getLocation(),rabbit.getAge());if(!cat.isValid())return;
cat.setFireTicks(rabbit.getFireTicks());cat.setHealth(Math.min(rabbit.getHealth(),cat.getAttribute(Attribute.MAX_HEALTH).getValue()));rabbit.remove();
}finally{replacing.remove(rabbit.getUniqueId());}
}
void migrate(Cat old){
Armadillo replacement=spawn(old.getLocation(),old.getAge());if(!replacement.isValid())return;replacement.setFireTicks(old.getFireTicks());replacement.setHealth(Math.min(3,old.getHealth()));replacement.customName(old.customName());if(old.getPersistentDataContainer().has(ROLLED,PersistentDataType.BYTE))replacement.getPersistentDataContainer().set(ROLLED,PersistentDataType.BYTE,(byte)1);old.remove();
}
private void maintain(){
World world=Bukkit.getWorld("arrakis");if(world==null)return;
var valid=new HashSet<UUID>();
for(var entity:world.getLivingEntities()){
if(entity instanceof Rabbit rabbit){replace(rabbit);continue;}
if(entity instanceof Cat cat&&isJerboa(cat)){migrate(cat);continue;}
if(isJerboa(entity)){
valid.add(entity.getUniqueId());entity.setSilent(true);boolean curled=entity instanceof Armadillo a&&a.getState()!=Armadillo.State.IDLE;
String model=curled?"jerboa_curled":entity.getVelocity().lengthSquared()>.001?(entity.getTicksLived()/4%2==0?"jerboa_walk_left":"jerboa_walk_right"):"jerboa";
models.track(entity,model,entity instanceof Armadillo c&&!c.isAdult()?.48:mother(entity)?2:1);
if(!curled&&random.getAsDouble()<.01)entity.getWorld().playSound(entity.getLocation(),"dunerealms:jerboa.idle",SoundCategory.NEUTRAL,.35f,mother(entity)?.8f:1.1f);
if(entity instanceof Armadillo cat){if(cat.isAdult()&&!cat.getPersistentDataContainer().has(ROLLED,PersistentDataType.BYTE))rollMother(cat);}
else if(entity instanceof Spider spider){UUID target=retaliation.get(spider.getUniqueId());LivingEntity attacker=target==null?null:Bukkit.getEntity(target) instanceof LivingEntity l?l:null;if(attacker==null||!attacker.isValid()||attacker.isDead()||!attacker.getWorld().equals(world)||attacker.getLocation().distanceSquared(spider.getLocation())>1024){retaliation.remove(spider.getUniqueId());spider.setTarget(null);}else spider.setTarget(attacker);}
}else if(entity instanceof Wolf&&entity.getPersistentDataContainer().has(new NamespacedKey("dunerealms","tiny_worm_pet"),PersistentDataType.BYTE)){
valid.add(entity.getUniqueId());models.track(entity,"tiny_worm",((Wolf)entity).isAdult()?.8:.45);
}
}
models.retain(valid);retaliation.keySet().retainAll(valid);instantFeeds.entrySet().removeIf(e->e.getValue()+1000<System.currentTimeMillis());
if((ticks+=4)%1200==0)for(var adult:world.getEntitiesByClass(Armadillo.class))autoBreed(adult);
}
private void autoBreed(Armadillo adult){
if(!isJerboa(adult)||!adult.isAdult()||!adult.canBreed()||adult.getLoveModeTicks()>0||!adult.isTicking()||random.getAsDouble()>=.20)return;
var nearby=adult.getNearbyEntities(8,4,8);
if(nearby.stream().filter(JerboaMobs::isJerboa).count()>=12)return;
Location at=adult.getLocation();World world=adult.getWorld();boolean spice=false;
for(int x=-4;x<=4&&!spice;x++)for(int z=-4;z<=4&&!spice;z++)for(int y=-1;y<=1;y++){
int bx=at.getBlockX()+x,bz=at.getBlockZ()+z;
if(world.isChunkLoaded(bx>>4,bz>>4)&&world.getBlockAt(bx,at.getBlockY()+y,bz).getType()==Material.DRIED_KELP_BLOCK){spice=true;break;}
}
if(!spice)return;
for(Entity entity:nearby)if(entity instanceof Armadillo other&&isJerboa(other)&&other.isAdult()&&other.canBreed()&&other.getLoveModeTicks()==0){adult.setBreedCause(null);other.setBreedCause(null);adult.setLoveModeTicks(600);other.setLoveModeTicks(600);return;}
}
private void rollMother(Armadillo adult){
adult.getPersistentDataContainer().set(ROLLED,PersistentDataType.BYTE,(byte)1);
if(random.getAsDouble()>=MOTHER_CHANCE||adult.getNearbyEntities(32,16,32).stream().anyMatch(JerboaMobs::mother))return;
Location at=adult.getLocation().clone().add(2,0,2);if(!at.getChunk().isLoaded()||!at.getBlock().isPassable()||!at.clone().add(0,1,0).getBlock().isPassable()||!at.clone().add(0,-1,0).getBlock().getType().isSolid())return;
at.getWorld().spawn(at,Spider.class,s->{s.getPersistentDataContainer().set(KIND,PersistentDataType.BYTE,(byte)2);s.customName(Component.text("Big Mama Jerboa",NamedTextColor.GOLD));s.getAttribute(Attribute.MAX_HEALTH).setBaseValue(6);s.setHealth(6);s.getAttribute(Attribute.MOVEMENT_SPEED).setBaseValue(SPEED);s.getAttribute(Attribute.ATTACK_DAMAGE).setBaseValue(3);var scale=s.getAttribute(Attribute.SCALE);if(scale!=null)scale.setBaseValue(1.4);s.setTarget(null);});
}
private static void consume(Player player,EquipmentSlot hand){if(player.getGameMode()==GameMode.CREATIVE)return;ItemStack item=player.getInventory().getItem(hand);item.setAmount(item.getAmount()-1);player.getInventory().setItem(hand,item);}
private void litter(Armadillo parent,Player breeder){int born=0;UUID reference=null;for(int i=0;i<4;i++){var at=parent.getLocation().clone().add((i%2-.5)*.4,0,(i/2-.5)*.4);var child=spawn(at,-24000);if(child.isValid()){born++;if(reference==null)reference=child.getUniqueId();FaunaProof.record(breeder,"jerboa","breed",child);}}if(born==4)FaunaProof.milestone(breeder,"husbandry_instant_litter",reference);parent.getWorld().spawnParticle(Particle.HEART,parent.getLocation().add(0,.5,0),7,.3,.3,.3);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void feed(PlayerInteractEntityEvent event){
if(!arrakis(event.getRightClicked())||!isJerboa(event.getRightClicked()))return;event.setCancelled(true);
if(!(event.getRightClicked() instanceof Armadillo cat)||!cat.isAdult())return;Player player=event.getPlayer();String id=itemId(player.getInventory().getItem(event.getHand()));
if("spice_block".equals(id)||"smuggled_spice_block".equals(id)){
long now=System.currentTimeMillis();if(now-instantFeeds.getOrDefault(cat.getUniqueId(),0L)<250)return;
litter(cat,player);instantFeeds.put(cat.getUniqueId(),now);consume(player,event.getHand());
}else if("refined_spice".equals(id)&&cat.canBreed()&&cat.getLoveModeTicks()==0){cat.setBreedCause(player.getUniqueId());cat.setLoveModeTicks(600);consume(player,event.getHand());}
}
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void breed(EntityBreedEvent event){
if(!arrakis(event.getEntity())||!isJerboa(event.getMother())||!isJerboa(event.getFather())||!(event.getEntity() instanceof Armadillo child))return;
prepare(child,-24000);Player breeder=event.getBreeder() instanceof Player p?p:null;FaunaProof.record(breeder,"jerboa","breed",child);int extra=0;for(int i=0;i<3;i++){var offspring=spawn(child.getLocation(),-24000);if(offspring.isValid()){extra++;FaunaProof.record(breeder,"jerboa","breed",offspring);}}if(extra==3)FaunaProof.milestone(breeder,"husbandry_normal_litter",child.getUniqueId());
}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void target(EntityTargetLivingEntityEvent event){if(mother(event.getEntity())&&event.getTarget()!=null&&!event.getTarget().getUniqueId().equals(retaliation.get(event.getEntity().getUniqueId())))event.setCancelled(true);}
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void attacked(EntityDamageByEntityEvent event){
if(isJerboa(event.getEntity()))event.getEntity().getWorld().playSound(event.getEntity().getLocation(),"dunerealms:jerboa.hurt",SoundCategory.NEUTRAL,.5f,mother(event.getEntity())?.8f:1.1f);
if(!mother(event.getEntity()))return;Entity attacker=event.getDamager();if(attacker instanceof Projectile p&&p.getShooter() instanceof Entity shooter)attacker=shooter;
if(attacker instanceof LivingEntity&&attacker!=event.getEntity())retaliation.put(event.getEntity().getUniqueId(),attacker.getUniqueId());
}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void shed(EntityDropItemEvent event){if(event.getEntity() instanceof Armadillo&&arrakis(event.getEntity())&&isJerboa(event.getEntity())&&event.getItemDrop().getItemStack().getType()==Material.ARMADILLO_SCUTE)event.setCancelled(true);}
@EventHandler(priority=EventPriority.HIGHEST) public void death(EntityDeathEvent event){
LivingEntity entity=event.getEntity();if(!arrakis(entity)||!isJerboa(entity))return;
FaunaProof.record(entity.getKiller(),"jerboa","kill",entity);
try{int amount=mother(entity)?2:1;var drops=new ArrayList<ItemStack>();
for(String id:List.of(entity.getFireTicks()>0?"jerboa_cooked_meat":"jerboa_raw_meat","jerboa_hide")){ItemStack item=items.build(id);item.setAmount(amount);if(id.equals("jerboa_hide"))FaunaProof.markDrop(item,entity.getUniqueId());drops.add(item);}
if(random.getAsDouble()<.2){ItemStack vial=items.build("blood_vial");vial.setAmount(amount);drops.add(vial);}if(random.getAsDouble()<.02){ItemStack vial=items.build("jerboa_water_vial");vial.setAmount(amount);drops.add(vial);}
if(mother(entity)){ItemStack spice=new ItemStack(Material.ORANGE_DYE,2);var meta=spice.getItemMeta();meta.displayName(Component.text("Melange Spice",NamedTextColor.GOLD));meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING,"spice");meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","origin_world"),PersistentDataType.STRING,"arrakis");spice.setItemMeta(meta);drops.add(spice);}
event.getDrops().clear();event.getDrops().addAll(drops);
}catch(ReflectiveOperationException failure){event.getDrops().clear();plugin.getLogger().severe("Jerboa native item definitions unavailable: "+failure.getClass().getSimpleName());}
models.remove(entity.getUniqueId());retaliation.remove(entity.getUniqueId());
}
@EventHandler public void unload(EntitiesUnloadEvent event){for(Entity e:event.getEntities())models.unload(e.getUniqueId());}
void close(){models.close();}
}

View file

@ -0,0 +1,25 @@
package com.example.duneterrain;
import java.util.*;
import org.bukkit.event.*;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockFertilizeEvent;
import org.bukkit.event.world.StructureGrowEvent;
/** Adds a native-plant restriction without bypassing existing WorldGuard build decisions. */
public final class NativePlants implements Listener {
private static final Map<String,Set<String>> PLANTS=Map.of("arrakis",Set.of("OAK_SAPLING"),"caladan",Set.of("OAK_SAPLING","BIRCH_SAPLING","MANGROVE_PROPAGULE","AZALEA","FLOWERING_AZALEA","JUNGLE_SAPLING","SPRUCE_SAPLING","CHERRY_SAPLING","BAMBOO","BAMBOO_SAPLING"),"kaitain",Set.of("OAK_SAPLING","BIRCH_SAPLING","DARK_OAK_SAPLING","SPRUCE_SAPLING","CHERRY_SAPLING","ACACIA_SAPLING"),"giedi_prime",Set.of("PALE_OAK_SAPLING"),"sigma_draconis_iv",Set.of("SPRUCE_SAPLING"));
private static final Set<String> CROPS=Set.of("WHEAT","CARROTS","POTATOES","BEETROOTS","TORCHFLOWER_CROP","PITCHER_CROP","MELON","MELON_STEM","ATTACHED_MELON_STEM","PUMPKIN","PUMPKIN_STEM","ATTACHED_PUMPKIN_STEM","COCOA","SWEET_BERRY_BUSH","CAVE_VINES","CAVE_VINES_PLANT","SUGAR_CANE","NETHER_WART","BROWN_MUSHROOM","RED_MUSHROOM","KELP","KELP_PLANT");
public static boolean frozenCrop(String world,String material,int cropY,int highestY){return world.equals("sigma_draconis_iv")&&CROPS.contains(material)&&highestY<=cropY;}
public static boolean allowed(String world,String material){
if(!PLANTS.containsKey(world))return true;
if((material.equals("MELON")||material.contains("MELON_STEM"))&&!world.equals("caladan"))return false;
if((material.equals("PUMPKIN")||material.contains("PUMPKIN_STEM"))&&!world.equals("kaitain"))return false;
if((world.equals("arrakis")||world.equals("giedi_prime"))&&CROPS.contains(material))return false;
return !(material.endsWith("_SAPLING")||Set.of("MANGROVE_PROPAGULE","AZALEA","FLOWERING_AZALEA","BAMBOO","CRIMSON_FUNGUS","WARPED_FUNGUS").contains(material))||PLANTS.get(world).contains(material);
}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void place(BlockPlaceEvent event){if(!allowed(event.getBlock().getWorld().getName(),event.getBlock().getType().name())){event.setCancelled(true);event.getPlayer().sendMessage("That plant is not native to this world.");}}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void crop(BlockGrowEvent event){var at=event.getBlock();var world=at.getWorld();var material=event.getNewState().getType().name();if(!allowed(world.getName(),material)||frozenCrop(world.getName(),material,at.getY(),world.getHighestBlockYAt(at.getLocation())))event.setCancelled(true);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void fertilize(BlockFertilizeEvent event){for(var state:event.getBlocks()){var world=state.getWorld();if(!allowed(world.getName(),state.getType().name())||frozenCrop(world.getName(),state.getType().name(),state.getY(),world.getHighestBlockYAt(state.getLocation()))){event.setCancelled(true);return;}}}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void grow(StructureGrowEvent event){var at=event.getLocation();if(!allowed(at.getWorld().getName(),at.getBlock().getType().name()))event.setCancelled(true);}
}

View file

@ -0,0 +1,16 @@
package com.example.duneterrain;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.generator.*;
/** After vanilla carving, before structures/decorations: preserve their intentionally dry rooms. */
public final class OceanAquifers {
public static void flood(WorldInfo world,int cx,int cz,ChunkGenerator.ChunkData data,String planet){
if(planet.equals("arrakis")){for(int x=0;x<16;x++)for(int z=0;z<16;z++)for(int y=Math.max(world.getMinHeight()+1,data.getMinHeight());y<data.getMaxHeight();y++)if(data.getType(x,y,z)==Material.WATER)data.setBlock(x,y,z,Material.AIR);return;}
if(planet.equals("giedi_prime")){for(int x=0;x<16;x++)for(int z=0;z<16;z++)for(int y=Math.max(world.getMinHeight()+1,data.getMinHeight());y<data.getMaxHeight();y++)if(data.getType(x,y,z)==Material.WATER||data.getType(x,y,z)==Material.LAVA)data.setBlock(x,y,z,Material.AIR);return;}
if(!Set.of("caladan","kaitain").contains(planet))return;
for(int x=0;x<16;x++)for(int z=0;z<16;z++){
if(TemperateLandscape.height(world.getSeed(),cx*16+x,cz*16+z,planet)>=TemperateLandscape.SEA)continue;
for(int y=Math.max(world.getMinHeight()+1,data.getMinHeight());y<=Math.min(TemperateLandscape.SEA,data.getMaxHeight()-1);y++){var type=data.getType(x,y,z);if(type==Material.AIR||type==Material.CAVE_AIR||type==Material.VOID_AIR)data.setBlock(x,y,z,Material.WATER);}
}
}
}

View file

@ -0,0 +1,35 @@
package com.example.duneterrain;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.generator.WorldInfo;
import org.bukkit.generator.ChunkGenerator.ChunkData;
/** Native sulfur/cinnabar cave lining, between vanilla carving and vanilla decoration. */
public final class OrdosSulfurSurfaces {
private static final Material SULFUR=Material.matchMaterial("SULFUR"),CINNABAR=Material.matchMaterial("CINNABAR");
private static final Set<Material> ROCK=Set.of(Material.STONE,Material.DEEPSLATE,Material.TUFF,Material.GRANITE,Material.DIORITE,Material.ANDESITE);
private static final int[][] SIDES={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
public static void apply(WorldInfo world,int chunkX,int chunkZ,ChunkData data){
if(!world.getName().equals("sigma_draconis_iv")||SULFUR==null||CINNABAR==null)return;
int min=Math.max(data.getMinHeight()+1,-44),max=Math.min(data.getMaxHeight()-2,34);long seed=world.getSeed();
for(int x=0;x<16;x++)for(int z=0;z<16;z++){
int gx=chunkX*16+x,gz=chunkZ*16+z;
if(!TemperateLandscape.sulfurPocket(seed,gx,0,gz))continue;
for(int y=min;y<=max;y++){
if(!ROCK.contains(data.getType(x,y,z)))continue;
boolean exposed=false;
for(int[] side:SIDES){int nx=x+side[0],ny=y+side[1],nz=z+side[2];if(nx>=0&&nx<16&&nz>=0&&nz<16&&data.getType(nx,ny,nz).isAir()){exposed=true;break;}}
if(!exposed)continue;
paint(data,seed,chunkX,chunkZ,x,y,z,min,max);
for(int[] side:SIDES)paint(data,seed,chunkX,chunkZ,x+side[0],y+side[1],z+side[2],min,max);
}
}
}
private static void paint(ChunkData data,long seed,int cx,int cz,int x,int y,int z,int min,int max){
if(x<0||x>=16||z<0||z>=16||y<min||y>max||!ROCK.contains(data.getType(x,y,z)))return;
int gx=cx*16+x,gz=cz*16+z;if(!TemperateLandscape.sulfurPocket(seed,gx,y,gz))return;
boolean red=TemperateLandscape.noise(seed^0x43494e4e41424152L,gx+y*2,gz-y,24)>.25;
data.setBlock(x,y,z,red?CINNABAR:SULFUR);
}
}

View file

@ -0,0 +1,22 @@
package com.example.duneterrain;
import java.util.*;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.server.ServerLoadEvent;
import org.bukkit.plugin.Plugin;
/** World-specific wildlife. NPC/custom-plugin spawns and existing pets keep their own owners. */
public final class PlanetMobs implements Listener {
private static final Set<String> NETHER=Set.of("BLAZE","GHAST","HOGLIN","MAGMA_CUBE","PIGLIN","PIGLIN_BRUTE","STRIDER","WITHER_SKELETON","ZOGLIN","ZOMBIFIED_PIGLIN","SKELETON","ENDERMAN");
private static final Set<String> PASSIVE=Set.of("ALLAY","ARMADILLO","AXOLOTL","BAT","CAMEL","CAT","CHICKEN","COD","COW","DONKEY","FROG","GLOW_SQUID","HORSE","MUSHROOM_COW","MOOSHROOM","MULE","OCELOT","PARROT","PIG","PUFFERFISH","RABBIT","SALMON","SHEEP","SNIFFER","SNOWMAN","SNOW_GOLEM","SQUID","STRIDER","TADPOLE","TROPICAL_FISH","TURTLE","VILLAGER","WANDERING_TRADER");
public static boolean allowed(String planet,String mob,boolean island){return switch(planet){case "caladan"->!mob.equals("CREEPER");case "kaitain"->PASSIVE.contains(mob);case "giedi_prime"->NETHER.contains(mob);case "sigma_draconis_iv"->Set.of("SKELETON","STRAY","WITHER_SKELETON","BOGGED").contains(mob)||island&&Set.of("MUSHROOM_COW","MOOSHROOM","SULFUR_CUBE").contains(mob);default->true;};}
public static boolean allowedSpawn(String planet,String mob,boolean island,String reason){return allowed(planet,mob,island)||planet.equals("giedi_prime")&&(reason.equals("SPAWNER")&&Set.of("SKELETON","ZOMBIE","SPIDER","CAVE_SPIDER").contains(mob)||mob.equals("WARDEN"));}
public static void start(Plugin plugin){Bukkit.getPluginManager().registerEvents(new PlanetMobs(),plugin);Bukkit.getPluginManager().registerEvents(new NativePlants(),plugin);PlanetSoil.start(plugin);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void spawning(CreatureSpawnEvent event){var e=event.getEntity();String planet=e.getWorld().getName();if(!TemperateLandscape.enabled(planet))return;
if(e instanceof PiglinAbstract piglin&&planet.equals("giedi_prime"))piglin.setImmuneToZombification(true);if(e instanceof Hoglin hoglin&&planet.equals("giedi_prime"))hoglin.setImmuneToZombification(true);
if(event.getSpawnReason()==CreatureSpawnEvent.SpawnReason.CUSTOM||e.hasMetadata("NPC")||e instanceof Tameable pet&&pet.isTamed())return;
var at=e.getLocation();if(planet.equals("sigma_draconis_iv")&&e.getType().name().equals("SULFUR_CUBE")&&at.getBlock().getBiome().getKey().getKey().equals("sulfur_caves"))return;if(!allowedSpawn(planet,e.getType().name(),TemperateLandscape.islandDistance(e.getWorld().getSeed(),at.getBlockX(),at.getBlockZ())<112,event.getSpawnReason().name()))event.setCancelled(true);
}
@EventHandler public void loaded(ServerLoadEvent event){var world=Bukkit.getWorld("giedi_prime");if(world!=null){world.setTime(18000);world.setStorm(false);world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE,false);world.setGameRule(GameRule.DO_WEATHER_CYCLE,false);}var arrakis=Bukkit.getWorld("arrakis");if(arrakis!=null)arrakis.setGameRule(GameRule.WATER_SOURCE_CONVERSION,false);}
}

View file

@ -0,0 +1,64 @@
package com.example.duneterrain;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Snowable;
import org.bukkit.block.data.Waterlogged;
import org.bukkit.plugin.Plugin;
/** Bounded native soil weathering; never loads a chunk or regenerates terrain. */
public final class PlanetSoil {
private static final Set<String> PLANETS=Set.of("arrakis","giedi_prime","sigma_draconis_iv");
private static final Set<Plugin> STARTED=Collections.newSetFromMap(new WeakHashMap<>());
private final Plugin owner;
private int round;
private PlanetSoil(Plugin owner){this.owner=owner;}
public static void start(Plugin owner){if(!STARTED.add(owner))return;var feature=new PlanetSoil(owner);Bukkit.getScheduler().runTaskTimer(owner,feature::tick,100,20);owner.getLogger().info("Planet soil weathering active; loaded chunks only, roofs and nearby water preserved");}
static boolean source(Material material){return material==Material.GRASS_BLOCK||material==Material.DIRT;}
static boolean exposed(Block soil){return soil.getWorld().getHighestBlockYAt(soil.getX(),soil.getZ(),HeightMap.WORLD_SURFACE)==soil.getY();}
/** Unknown adjacent chunks retain soil. Waterlogged blocks hydrate like water. */
static boolean hydrated(Block soil){
World world=soil.getWorld();
for(int x=soil.getX()-4;x<=soil.getX()+4;x++)for(int z=soil.getZ()-4;z<=soil.getZ()+4;z++){
if(!world.isChunkLoaded(x>>4,z>>4))return true;
for(int y=soil.getY();y<=soil.getY()+1&&y<world.getMaxHeight();y++){
Block at=world.getBlockAt(x,y,z);if(at.getType()==Material.WATER||at.getBlockData() instanceof Waterlogged water&&water.isWaterlogged())return true;
}
}
return false;
}
static Material target(String planet){return switch(planet){case "arrakis"->Material.SAND;case "giedi_prime"->Material.COARSE_DIRT;case "sigma_draconis_iv"->Material.GRASS_BLOCK;default->null;};}
private void tick(){
int current=round++;
for(World world:Bukkit.getWorlds()){
if(!PLANETS.contains(world.getName()))continue;
Chunk[] chunks=world.getLoadedChunks();if(chunks.length==0)continue;
for(int i=0;i<Math.min(8,chunks.length);i++){
Chunk chunk=chunks[Math.floorMod(current*8+i,chunks.length)];
for(int j=0;j<2;j++){
int x=(chunk.getX()<<4)+ThreadLocalRandom.current().nextInt(16),z=(chunk.getZ()<<4)+ThreadLocalRandom.current().nextInt(16);
int y=world.getHighestBlockYAt(x,z,HeightMap.WORLD_SURFACE);if(y<world.getMinHeight()||y>=world.getMaxHeight()-1)continue;
Block block=world.getBlockAt(x,y,z);if(source(block.getType())&&exposed(block)&&!hydrated(block))weather(block);
}
}
}
}
private void weather(Block block){
Material material=target(block.getWorld().getName());if(material==null)return;
BlockData before=block.getBlockData();BlockData next=material.createBlockData();
if(block.getWorld().getName().equals("sigma_draconis_iv")){
// Native snowy grass plus a thin snow layer is the frozen-ground representation.
if(!block.getRelative(0,1,0).getType().isAir())return;
((Snowable)next).setSnowy(true);
Block cover=block.getRelative(0,1,0);BlockData air=cover.getBlockData();cover.setType(Material.SNOW,false);log(cover,air,cover.getBlockData());
}
block.setBlockData(next,true);log(block,before,next);
}
private void log(Block block,BlockData before,BlockData after){
Plugin core=Bukkit.getPluginManager().getPlugin("CoreProtect");if(core==null||!core.isEnabled())return;
try{Object api=core.getClass().getMethod("getAPI").invoke(core);api.getClass().getMethod("logRemoval",String.class,Location.class,Material.class,BlockData.class).invoke(api,"#DuneClimate",block.getLocation(),before.getMaterial(),before);api.getClass().getMethod("logPlacement",String.class,Location.class,Material.class,BlockData.class).invoke(api,"#DuneClimate",block.getLocation(),after.getMaterial(),after);}catch(ReflectiveOperationException failure){owner.getLogger().warning("Soil weathering CoreProtect logging unavailable: "+failure.getClass().getSimpleName());}
}
}

View file

@ -0,0 +1,118 @@
package com.example.duneterrain;
/** Seeded continuous ridge contours, shared across every intersecting chunk. */
final class RockPlateaus {
// Keep the existing cell coordinates and cross-chunk contours. Three-by-three
// groups occupy an irregular window in each eight-cell region, leaving long
// clear desert corridors without moving formations across the search grid.
static boolean activeCell(long x,long z){long sx=Math.floorDiv(x,8),sz=Math.floorDiv(z,8),seed=formationSeed(sx,sz);int ox=(int)Math.floorMod(seed,3),oz=(int)Math.floorMod(seed>>>16,3);long dx=Math.floorMod(x,8),dz=Math.floorMod(z,8);return dx>=ox&&dx<ox+3&&dz>=oz&&dz<oz+3;}
static int count(long seed, int configuredMaximum) {
return 1 + (int)Math.floorMod(seed, Math.max(1, Math.min(3, configuredMaximum)));
}
static int interval(int configuredInterval, int maximumHeight, int count) {
return Math.max(1, Math.min(5, Math.min(configuredInterval, Math.max(1, maximumHeight / count))));
}
static int level(double depth, int count) {
if (depth < 0.10) return 0;
return Math.min(count, 1 + (int)Math.floor((depth - 0.10) / (0.78 / count)));
}
static double terrain(double x, double z, double scale) {
return Math.sin(x * scale) * Math.cos(z * scale * 1.13)
+ Math.sin(x * scale * 2.7 + z * scale * 1.45) * 0.35;
}
static Shape shape(long seed, long centerX, long centerZ, double radius, double scale) {
// Follow the local dune contour instead of cutting a circular island across it.
double gx = terrain(centerX + 8, centerZ, scale) - terrain(centerX - 8, centerZ, scale);
double gz = terrain(centerX, centerZ + 8, scale) - terrain(centerX, centerZ - 8, scale);
double angle = Math.atan2(gz, gx) + Math.PI / 2;
return new Shape(seed, centerX, centerZ, radius, scale, Math.cos(angle), Math.sin(angle));
}
record Shape(long seed, long centerX, long centerZ, double radius, double scale, double cosine, double sine) {
double depth(long x, long z) {
double dx = (x - centerX) / radius, dz = (z - centerZ) / radius;
double u = dx * cosine + dz * sine, v = -dx * sine + dz * cosine;
// Low-frequency domain warping produces connected promontories, bays and uneven terraces.
double warpedU = u + 0.14 * noise(u * 2.0 + 17, v * 2.0 - 9, seed);
double spine = 0.24 * noise(u * 2.2 - 31, 7, seed ^ 0x51ed2705L)
+ 0.12 * (terrain(x, z, scale) - terrain(centerX, centerZ, scale));
double width = 0.57 + 0.14 * noise(u * 2.5, 13, seed ^ 0x6eed0e9dL);
double cross = (v - spine + 0.10 * noise(u * 3, v * 3, ~seed)) / width;
double envelope = Math.pow(Math.pow(Math.abs(warpedU), 2.6) + Math.pow(Math.abs(cross), 2.6), 1.0 / 2.6);
return 1.0 - envelope + 0.17 * noise(u * 3.1 + 4, v * 3.1 - 5, seed ^ 0x9e3779b9L);
}
}
static int lowerTerrace(double depth) {
if(depth < .025 || depth >= .25)return 0;
return Math.min(3,1+(int)Math.floor((depth-.025)/.075));
}
static int spireRise(long seed, long x, long z, double depth, int height) {
// Thin erosion ridges on the outer mountain shoulder; terrace surfaces remain untouched.
if (depth <= 0.25 || depth >= 0.46 || height <= 0) return 0;
double shoulder = Math.sin(Math.PI * (depth - 0.25) / 0.21);
double ridge = 1.0 - Math.abs(noise(x / 16.0, z / 16.0, seed ^ 0x45524f53494f4eL));
double broken = 0.65 + 0.35 * (noise(x / 4.5, z / 4.5, ~seed) + 1) / 2;
return (int)Math.floor(Math.min(64,height) * shoulder * Math.pow(ridge,3) * broken);
}
static int highestGround(Shape shape, int baseHeight, double variation) {
int extent = (int)Math.ceil(shape.radius() * 2.0) + 3;
int highest = Integer.MIN_VALUE;
for (int x = (int)shape.centerX() - extent; x <= shape.centerX() + extent; x++)
for (int z = (int)shape.centerZ() - extent; z <= shape.centerZ() + extent; z++) {
if (shape.depth(x,z) >= 0)
highest = Math.max(highest, baseHeight + (int)Math.round(terrain(x,z,shape.scale()) * variation));
}
return highest == Integer.MIN_VALUE ? baseHeight : highest;
}
static long formationSeed(long cellX, long cellZ) {
return mix(cellX * 0x9E3779B97F4A7C15L ^ cellZ * 0xC2B2AE3D27D4EB4FL ^ 0x4441524B49534C41L);
}
// Shared axis positions keep north/south and east/west neighbours aligned.
// Independent bounded jitter makes each gap lie within the requested limits.
static long axisCenter(long cell, int minimumGap, int maximumGap, long salt) {
int spacing = (minimumGap + maximumGap) / 2;
int jitter = Math.min(spacing - minimumGap, maximumGap - spacing) / 2;
long offset = Math.floorMod(mix(cell ^ salt), jitter * 2L + 1) - jitter;
return cell * spacing + spacing / 2 + offset;
}
static long centerX(long cell, int minimumGap, int maximumGap) {
return axisCenter(cell,minimumGap,maximumGap,0x165667B19E3779F9L);
}
static long centerZ(long cell, int minimumGap, int maximumGap) {
return axisCenter(cell,minimumGap,maximumGap,0x85EBCA77C2B2AE63L);
}
static int radius(long seed, int minimum, int maximum) {
return minimum + (int)Math.floorMod(seed >>> 1, maximum - minimum + 1L);
}
static double regionDepth(int x, int z, int minimumGap, int maximumGap, int minimum, int maximum, double scale) {
int spacing = (minimumGap + maximumGap) / 2;
int reach = (int)Math.ceil(maximum * 2.0) + 3;
double depth = -1;
for (int cx = Math.floorDiv(x - reach, spacing); cx <= Math.floorDiv(x + reach, spacing); cx++)
for (int cz = Math.floorDiv(z - reach, spacing); cz <= Math.floorDiv(z + reach, spacing); cz++) {
long seed = formationSeed(cx, cz);
if(!activeCell(cx,cz))continue;
depth = Math.max(depth, shape(seed, centerX(cx,minimumGap,maximumGap), centerZ(cz,minimumGap,maximumGap),
radius(seed,minimum,maximum), scale).depth(x,z));
}
return depth;
}
private static long mix(long h) {
h = (h ^ (h >>> 30)) * 0xBF58476D1CE4E5B9L;
h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL;
return h ^ (h >>> 31);
}
static double noise(double x, double z, long seed) {
long ix = (long)Math.floor(x), iz = (long)Math.floor(z);
double tx = x - ix, tz = z - iz;
tx = tx * tx * (3 - 2 * tx); tz = tz * tz * (3 - 2 * tz);
double a = sample(ix, iz, seed), b = sample(ix + 1, iz, seed);
double c = sample(ix, iz + 1, seed), d = sample(ix + 1, iz + 1, seed);
return (a + (b - a) * tx) * (1 - tz) + (c + (d - c) * tx) * tz;
}
private static double sample(long x, long z, long seed) {
long h = x * 0x9E3779B97F4A7C15L ^ z * 0xC2B2AE3D27D4EB4FL ^ seed;
h = (h ^ (h >>> 30)) * 0xBF58476D1CE4E5B9L;
h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL;
return ((h ^ (h >>> 31)) >>> 11) * 0x1.0p-52 - 1;
}
}

View file

@ -0,0 +1,18 @@
package com.example.duneterrain;
import org.bukkit.Material;
import org.bukkit.generator.LimitedRegion;
/** Retaining walls, a real floor and foundations: never an unsupported disc of water. */
final class SietchReservoirs {
static void build(LimitedRegion region,int x,int floor,int z,int width,int length,int depth){
for(int dx=-width;dx<=width;dx++)for(int dz=-length;dz<=length;dz++){
set(region,x+dx,floor,z+dz,Material.STONE_BRICKS);
boolean wall=Math.abs(dx)==width||Math.abs(dz)==length;
for(int dy=1;dy<=depth;dy++)set(region,x+dx,floor+dy,z+dz,wall?Material.CUT_SANDSTONE:Material.WATER);
if(wall)set(region,x+dx,floor+depth+1,z+dz,Material.SMOOTH_SANDSTONE_SLAB);
// Piers under the corners and edges remain visible inside larger caverns.
if((Math.abs(dx)==width&&(dz==0||Math.abs(dz)==length))||(dx==0&&Math.abs(dz)==length))
for(int down=1;down<=6;down++)set(region,x+dx,floor-down,z+dz,Material.SANDSTONE);
}
}
private static void set(LimitedRegion r,int x,int y,int z,Material m){if(r.isInRegion(x,y,z))r.setType(x,y,z,m);}
}

View file

@ -0,0 +1,23 @@
package com.example.duneterrain;
import com.google.gson.*;import java.io.*;import java.nio.charset.StandardCharsets;import java.util.*;
import org.bukkit.*;import org.bukkit.entity.*;import org.bukkit.event.*;import org.bukkit.event.entity.EntityDeathEvent;import org.bukkit.event.inventory.*;import org.bukkit.event.block.CrafterCraftEvent;import org.bukkit.event.server.ServerLoadEvent;import org.bukkit.inventory.*;import org.bukkit.persistence.PersistentDataType;import org.bukkit.plugin.Plugin;
import net.kyori.adventure.text.Component;import net.kyori.adventure.text.format.NamedTextColor;import net.kyori.adventure.text.format.TextDecoration;
/** Existing starter-part identities, supplied by native-world drops or spice crafting. */
public final class StarterRepairDrops implements Listener {
private static final Set<Plugin> ACTIVE=Collections.newSetFromMap(new WeakHashMap<>());
private final Plugin plugin;private final List<JsonObject> parts;private final String origin;
public static void start(Plugin plugin){if(!ACTIVE.add(plugin))return;try{Bukkit.getPluginManager().registerEvents(new StarterRepairDrops(plugin),plugin);}catch(IOException e){throw new IllegalStateException("Starter repair policy unavailable",e);}}
private StarterRepairDrops(Plugin plugin)throws IOException{this.plugin=plugin;String planet=plugin.getConfig().getString("server.planet","");origin=planet.replace('_','-');try(var in=plugin.getResource("starter-repair-parts.json")){if(in==null)throw new IOException("Repair parts missing");var rows=JsonParser.parseReader(new InputStreamReader(in,StandardCharsets.UTF_8)).getAsJsonArray();parts=new ArrayList<>();for(var row:rows)parts.add(row.getAsJsonObject());}}
static String drop(String world,String mob){return switch(world.replaceFirst("_(?:nether|the_end)$","")+":"+mob){case "caladan:DROWNED"->"starter-tool-fitting-v1";case "kaitain:COW"->"starter-binding-patch-v1";case "giedi_prime:PIGLIN"->"starter-calibration-piece-v1";case "sigma_draconis_iv:SKELETON"->"starter-repair-plate-v1";default->null;};}
private JsonObject definition(String id){return parts.stream().filter(p->p.get("id").getAsString().equals(id)).findFirst().orElseThrow();}
private ItemStack build(JsonObject part){var item=new ItemStack(Objects.requireNonNull(Material.matchMaterial(part.get("material").getAsString())));var m=item.getItemMeta();m.displayName(Component.text(part.get("name").getAsString(),NamedTextColor.GREEN).decoration(TextDecoration.ITALIC,false));m.lore(List.of(Component.text(part.get("purpose").getAsString(),NamedTextColor.GRAY).decoration(TextDecoration.ITALIC,false)));var d=m.getPersistentDataContainer();d.set(new NamespacedKey("dunerealms","starter_part"),PersistentDataType.STRING,part.get("id").getAsString());d.set(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING,part.get("id").getAsString());d.set(new NamespacedKey("dunerealms","quality"),PersistentDataType.STRING,"uncommon");d.set(new NamespacedKey("dunerealms","equipment_mark"),PersistentDataType.STRING,"1");d.set(new NamespacedKey("dunerealms","item_class"),PersistentDataType.STRING,"resource");d.set(new NamespacedKey("dunerealms","metadata_policy"),PersistentDataType.STRING,"s1-item-metadata-v1");d.set(new NamespacedKey("dunerealms","origin_world"),PersistentDataType.STRING,origin);item.setItemMeta(m);return item;}
@EventHandler(priority=EventPriority.HIGH) public void killed(EntityDeathEvent event){var entity=event.getEntity();String id=drop(entity.getWorld().getName(),entity.getType().name());if(id==null||entity.hasMetadata("NPC")||entity.getCustomName()!=null||entity.getKiller()==null||Math.random()>=.05)return;event.getDrops().add(build(definition(id)));}
@EventHandler public void loaded(ServerLoadEvent event){for(var part:parts){var key=new NamespacedKey("dunerealms",part.get("id").getAsString().replace('-','_'));Bukkit.removeRecipe(key);var recipe=new ShapelessRecipe(key,build(part));recipe.addIngredient(Objects.requireNonNull(Material.matchMaterial(part.get("material").getAsString())));recipe.addIngredient(Material.ORANGE_DYE);if(!Bukkit.addRecipe(recipe))throw new IllegalStateException("Repair recipe registration failed");}plugin.getLogger().info("Four starter repair parts: native-world 5% player-kill drops and spice crafting registered.");}
private boolean ours(Recipe recipe){return recipe instanceof Keyed k&&k.getKey().getNamespace().equals("dunerealms")&&parts.stream().anyMatch(p->p.get("id").getAsString().replace('-','_').equals(k.getKey().getKey()));}
static boolean spice(ItemStack item){if(item==null||item.getType()!=Material.ORANGE_DYE||!item.hasItemMeta())return false;var d=item.getItemMeta().getPersistentDataContainer();String id=d.get(new NamespacedKey("executableitems","ei-id"),PersistentDataType.STRING);return "smuggled_spice".equals(id)||"spice".equals(d.get(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING))&&(id==null||id.equals("spice"));}
private boolean ingredients(ItemStack[] matrix){return Arrays.stream(matrix).anyMatch(StarterRepairDrops::spice);}
@EventHandler(priority=EventPriority.HIGHEST) public void preview(PrepareItemCraftEvent e){if(ours(e.getRecipe())&&!ingredients(e.getInventory().getMatrix()))e.getInventory().setResult(null);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void craft(CraftItemEvent e){if(ours(e.getRecipe())&&!ingredients(e.getInventory().getMatrix()))e.setCancelled(true);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void automated(CrafterCraftEvent e){if(ours(e.getRecipe())&&(!(e.getBlock().getState() instanceof org.bukkit.block.Crafter crafter)||!ingredients(crafter.getInventory().getContents())))e.setCancelled(true);}
}

View file

@ -0,0 +1,93 @@
package com.example.duneterrain;
import java.util.*;
import org.bukkit.*;
import org.bukkit.block.Biome;
import org.bukkit.block.data.type.Leaves;
import org.bukkit.generator.ChunkGenerator.ChunkData;
import org.bukkit.generator.WorldInfo;
/** Seeded world profiles. Existing planet-specific ore placement runs afterwards. */
public final class TemperateLandscape {
public static final int SEA=64;
public static boolean enabled(String planet){return Set.of("caladan","kaitain","giedi_prime","sigma_draconis_iv").contains(planet);}
private static long mix(long v){v=(v^(v>>>30))*0xbf58476d1ce4e5b9L;v=(v^(v>>>27))*0x94d049bb133111ebL;return v^(v>>>31);}
private static double point(long seed,long x,long z){return (mix(seed^x*0x9e3779b97f4a7c15L^z*0xc2b2ae3d27d4eb4fL)>>>11)*0x1.0p-52-1;}
private static double lerp(double a,double b,double t){return a+(b-a)*t;}
private static double smooth(double t){return t*t*t*(t*(t*6-15)+10);}
static double noise(long seed,int x,int z,int size){long cx=Math.floorDiv(x,size),cz=Math.floorDiv(z,size);double tx=smooth(Math.floorMod(x,size)/(double)size),tz=smooth(Math.floorMod(z,size)/(double)size);return lerp(lerp(point(seed,cx,cz),point(seed,cx+1,cz),tx),lerp(point(seed,cx,cz+1),point(seed,cx+1,cz+1),tx),tz);}
// Multi-scale continuous terrain with broad, domain-warped climate regions.
private static double layered(long seed,int x,int z,int size){return .58*noise(seed,x,z,size)+.27*noise(seed^0x641L,x,z,Math.max(24,size/2))+.11*noise(seed^0x182L,x,z,Math.max(16,size/4))+.04*noise(seed^0x93L,x,z,Math.max(12,size/8));}
private static double climate(long seed,int x,int z,int size){int wx=(int)Math.round(x+noise(seed^91,x,z,size*2)*size*.24),wz=(int)Math.round(z+noise(seed^172,x,z,size*2)*size*.24);return .85*noise(seed,wx,wz,size)+.15*noise(seed^421,wx,wz,Math.max(48,size/3));}
private static double ridge(double n){return Math.sqrt(n*n+.012)-Math.sqrt(.012);}
private static double clamp(double n){return Math.max(0,Math.min(1,n));}
private static double beachWidth(long seed,int x,int z){return 4+noise(seed^623,x,z,96)*2;}
private static double riverDistance(long seed,int x,int z){return Math.abs(climate(seed^0x5249564552L,x,z,620));}
private static double riverHeight(long seed,int x,int z,double height){if(height<=SEA-4||height>=SEA+45)return height;double bank=1-smooth(clamp((riverDistance(seed,x,z)-.014)/.065));double highland=1-smooth(clamp((height-SEA-25)/20));return lerp(height,SEA-3,bank*highland);}
private static double mountains(long seed,int x,int z){double spine=1-smooth(clamp((Math.abs(climate(seed^0x4d4f554e5441494eL,x,z,1400))-.025)/.24));return spine*(75+layered(seed^5231,x,z,500)*30);}
private static Biome frozenDesert(){var biome=Registry.BIOME.get(NamespacedKey.fromString("dunerealms:frozen_desert"));return biome==null?Biome.SNOWY_PLAINS:biome;}
static boolean ordosBadlands(long seed,int x,int z){int h=height(seed,x,z,"sigma_draconis_iv");return h>SEA+4&&h<150&&islandDistance(seed,x,z)>=240&&climate(seed^0x5445525241434f54L,x,z,1500)>.30;}
private static Biome sulfurBiome(){return Registry.BIOME.get(NamespacedKey.minecraft("sulfur_caves"));}
static boolean sulfurPocket(long seed,int x,int y,int z){return y<35&&y> -45&&climate(seed^0x53554c465552L,x,z,900)>.24;}
public static int height(long seed,int x,int z,String planet){
if(planet.equals("sigma_draconis_iv")){
double distance=islandDistance(seed,x,z);
double field=Math.max(0,Math.min(1,(layered(seed^31,x,z,600)+.3)*3)),continent=layered(seed,x,z,1100);double h=78+continent*30+field*ridge(layered(seed^19,x,z,260))*64+noise(seed^927,x,z,70)*1.5+mountains(seed,x,z)*field*.85;
double ocean=smooth(Math.max(0,Math.min(1,(-continent-.15)/.3)));h=lerp(h,62+(continent+.3)*75+field*ridge(layered(seed^19,x,z,260))*18,ocean);if(distance>=240&&h>SEA+4&&h<120&&climate(seed^974,x,z,1200)<-.18)h+=ridge(layered(seed^163,x,z,90))*9;
if(distance<240){double volcano=distance<30?30*Math.pow(1-distance/30,1.2):0;double islandHeight=SEA+5+clamp(1-distance/112)*5+volcano-8*(1-smooth(clamp((distance-4)/5)));if(distance>95)islandHeight=lerp(islandHeight,SEA-12,smooth(clamp((distance-95)/65)));h=lerp(h,islandHeight,1-smooth(clamp((distance-130)/110)));}return (int)Math.round(Math.max(16,h));
}
if(planet.equals("giedi_prime")){return (int)Math.round(Math.max(24,giediGround(seed,x,z)));}
boolean island=planet.equals("caladan");double continent=layered(seed,x,z,island?600:950)+.3*layered(seed^19,x,z,island?210:420)+(island?-.16:.4);
double spawn=Math.max(0,1-Math.hypot((double)x,z)/220);if(spawn>0)continent=Math.max(continent,spawn*spawn*.85);
double hills=layered(seed^734,x,z,island?220:260),detail=layered(seed^927,x,z,70);
double h=island?SEA-18+continent*90+ridge(hills)*48*Math.max(0,Math.min(1,(continent+.2)*3))+detail*4:SEA+continent*30+hills*8+detail*2;
if(island)h+=mountains(seed,x,z)*smooth(clamp((continent+.06)/.5));
h=riverHeight(seed,x,z,h);return (int)Math.round(Math.max(12,Math.min(245,h)));
}
private static double giediGround(long seed,int x,int z){double spawn=Math.max(0,1-Math.hypot((double)x,z)/220),terrain=layered(seed,x,z,1100);if(spawn>0)terrain=Math.max(terrain,spawn*.6);double h=66+terrain*40+layered(seed^19,x,z,300)*7+mountains(seed,x,z);double canyon=1-smooth(clamp((Math.abs(climate(seed^0x43414e594f4eL,x,z,900))-.012)/.07));return h-canyon*(26+ridge(layered(seed^812,x,z,320))*20);}
public static boolean lavaSurface(long seed,int x,int z){return false;}
public static double islandDistance(long seed,int x,int z){long cx=Math.floorDiv(x,1024),cz=Math.floorDiv(z,1024),key=mix(seed^cx*0x9e3779b97f4a7c15L^cz*0xc2b2ae3d27d4eb4fL^0x4d555348524f4f4dL);if((key&127)!=0)return Double.POSITIVE_INFINITY;long centerX=cx*1024+384+Math.floorMod(key>>>8,256),centerZ=cz*1024+384+Math.floorMod(key>>>24,256);return Math.hypot(x-(double)centerX,z-(double)centerZ);}
public static Biome biome(WorldInfo world,int x,int y,int z,String planet){long seed=world.getSeed();int h=height(seed,x,z,planet);double region=climate(seed^321,x,z,420);
if(planet.equals("sigma_draconis_iv")){if(y<35&&sulfurPocket(seed,x,y,z)&&sulfurBiome()!=null)return sulfurBiome();if(islandDistance(seed,x,z)<145)return Biome.MUSHROOM_FIELDS;if(ordosBadlands(seed,x,z))return region>.2?Biome.ERODED_BADLANDS:Biome.BADLANDS;double cold=climate(seed^974,x,z,1200);if(h<SEA-14)return cold>.3?Biome.DEEP_COLD_OCEAN:Biome.DEEP_FROZEN_OCEAN;if(h<SEA-2)return h>SEA-8&&region>.2?Biome.FROZEN_RIVER:cold>.3?Biome.COLD_OCEAN:Biome.FROZEN_OCEAN;if(h<=SEA+2)return Biome.SNOWY_BEACH;if(h>155)return region>0?Biome.JAGGED_PEAKS:Biome.FROZEN_PEAKS;if(h>145)return region>.1?Biome.GROVE:Biome.SNOWY_SLOPES;if(cold<-.22)return frozenDesert();double forest=climate(seed^32171,x,z,1800);if(forest>.14)return Biome.OLD_GROWTH_SPRUCE_TAIGA;if(forest>.02)return Biome.OLD_GROWTH_PINE_TAIGA;if(forest>-.18)return Biome.SNOWY_TAIGA;if(region<-.4)return Biome.ICE_SPIKES;if(region>.3)return Biome.SNOWY_TAIGA;return h>105?(region>0?Biome.WINDSWEPT_HILLS:Biome.WINDSWEPT_GRAVELLY_HILLS):Biome.SNOWY_PLAINS;}
if(planet.equals("giedi_prime")){region=climate(seed^321,x,z,1100);double zone=climate(seed^791,x,z,850);if(y< -16&&zone>.1)return Biome.DEEP_DARK;if(y<25&&zone<-.22)return Biome.DRIPSTONE_CAVES;if(h>140)return Biome.STONY_PEAKS;if(Math.abs(region)<.32&&zone<.25)return Biome.WINDSWEPT_GRAVELLY_HILLS;if(zone<-.4||region<-.55||region>.55)return Biome.WINDSWEPT_GRAVELLY_HILLS;if(zone>.25)return region>.1?Biome.ERODED_BADLANDS:region<-.1?Biome.WOODED_BADLANDS:Biome.BADLANDS;return Biome.PALE_GARDEN;}
if(planet.equals("caladan")){if(h>=SEA-4&&h<=SEA+1&&riverDistance(seed,x,z)<.018)return Biome.RIVER;if(y<35+layered(seed^431,x,z,140)*14&&h>SEA+4)return Biome.LUSH_CAVES;double wet=climate(seed^873,x,z,520),forest=climate(seed^681,x,z,640);if(h<40)return wet<-.15?Biome.DEEP_OCEAN:Biome.DEEP_LUKEWARM_OCEAN;if(h<SEA-2)return wet<-.15?Biome.LUKEWARM_OCEAN:Biome.WARM_OCEAN;if(h<=SEA+10&&wet>.18)return wet>.34?Biome.MANGROVE_SWAMP:Biome.SWAMP;if(h<=SEA+2)return Biome.STONY_SHORE;if(h>155)return Biome.STONY_PEAKS;if(h>115&&forest>.1)return Biome.WINDSWEPT_FOREST;if(forest<-.38)return Biome.OLD_GROWTH_BIRCH_FOREST;if(forest<-.12&&region<0)return Biome.FOREST;return region<-.4?Biome.CHERRY_GROVE:region>.35?Biome.BAMBOO_JUNGLE:forest>.3?Biome.SPARSE_JUNGLE:Biome.JUNGLE;}
if(h>=SEA-4&&h<=SEA+1&&riverDistance(seed,x,z)<.018)return Biome.RIVER;if(h<SEA-2)return Biome.OCEAN;if(h<=SEA+beachWidth(seed,x,z))return Biome.BEACH;double meadow=climate(seed^912,x,z,620);if(meadow>.3)return h>88?Biome.WINDSWEPT_SAVANNA:h>78?Biome.SAVANNA_PLATEAU:Biome.SAVANNA;if(region>.3)return Biome.DARK_FOREST;if(region<-.48)return Biome.CHERRY_GROVE;if(region<-.25)return Biome.TAIGA;if(meadow<-.38)return Biome.FLOWER_FOREST;if(meadow<-.15)return Biome.BIRCH_FOREST;if(h>87)return Biome.MEADOW;return meadow>.08?Biome.SUNFLOWER_PLAINS:Biome.PLAINS;
}
public static List<Biome> biomes(String planet){return switch(planet){case "caladan"->List.of(Biome.SWAMP,Biome.MANGROVE_SWAMP,Biome.SPARSE_JUNGLE,Biome.FOREST,Biome.OLD_GROWTH_BIRCH_FOREST,Biome.STONY_PEAKS,Biome.WINDSWEPT_FOREST,Biome.LUKEWARM_OCEAN,Biome.DEEP_OCEAN,Biome.RIVER,Biome.WARM_OCEAN,Biome.DEEP_LUKEWARM_OCEAN,Biome.STONY_SHORE,Biome.JUNGLE,Biome.BAMBOO_JUNGLE,Biome.CHERRY_GROVE,Biome.LUSH_CAVES);case "kaitain"->List.of(Biome.FLOWER_FOREST,Biome.MEADOW,Biome.SUNFLOWER_PLAINS,Biome.BIRCH_FOREST,Biome.SAVANNA,Biome.SAVANNA_PLATEAU,Biome.WINDSWEPT_SAVANNA,Biome.RIVER,Biome.OCEAN,Biome.BEACH,Biome.PLAINS,Biome.DARK_FOREST,Biome.CHERRY_GROVE,Biome.TAIGA);case "giedi_prime"->List.of(Biome.STONY_PEAKS,Biome.WINDSWEPT_GRAVELLY_HILLS,Biome.DEEP_DARK,Biome.DRIPSTONE_CAVES,Biome.BADLANDS,Biome.ERODED_BADLANDS,Biome.WOODED_BADLANDS,Biome.PALE_GARDEN);default->ordosBiomes();};}
private static List<Biome> ordosBiomes(){var result=new ArrayList<>(List.of(frozenDesert(),Biome.COLD_OCEAN,Biome.DEEP_COLD_OCEAN,Biome.OLD_GROWTH_PINE_TAIGA,Biome.OLD_GROWTH_SPRUCE_TAIGA,Biome.WINDSWEPT_HILLS,Biome.WINDSWEPT_GRAVELLY_HILLS,Biome.SNOWY_PLAINS,Biome.SNOWY_SLOPES,Biome.FROZEN_RIVER,Biome.MUSHROOM_FIELDS,Biome.ICE_SPIKES,Biome.SNOWY_TAIGA,Biome.SNOWY_BEACH,Biome.FROZEN_PEAKS,Biome.JAGGED_PEAKS,Biome.FROZEN_OCEAN,Biome.DEEP_FROZEN_OCEAN,Biome.GROVE,Biome.BADLANDS,Biome.ERODED_BADLANDS));var sulfur=sulfurBiome();if(sulfur!=null)result.add(sulfur);return List.copyOf(result);}
public static void generate(WorldInfo world,Random random,int chunkX,int chunkZ,ChunkData data,String planet){
boolean island=planet.equals("caladan");int min=world.getMinHeight(),max=world.getMaxHeight()-1;int[][] tops=new int[16][16];long seed=world.getSeed();
for(int x=0;x<16;x++)for(int z=0;z<16;z++){
int gx=chunkX*16+x,gz=chunkZ*16+z,h=Math.max(min+8,Math.min(max-20,height(seed,gx,gz,planet)));tops[x][z]=h;
double slope=Math.max(Math.abs(height(seed,gx+2,gz,planet)-height(seed,gx-2,gz,planet)),Math.abs(height(seed,gx,gz+2,planet)-height(seed,gx,gz-2,planet)))/4.0;
boolean rock=island&&(slope>1.1||h>132&&noise(seed^32,gx,gz,48)>.05);
boolean snow=planet.equals("sigma_draconis_iv"),ash=planet.equals("giedi_prime");double distance=snow?islandDistance(seed,gx,gz):Double.POSITIVE_INFINITY;
Biome surfaceBiome=ash||snow?biome(world,gx,h,gz,planet):null;boolean rocky=ash&&(surfaceBiome==Biome.STONY_PEAKS||surfaceBiome==Biome.WINDSWEPT_GRAVELLY_HILLS),basalt=ash&&surfaceBiome==Biome.BASALT_DELTAS,soul=ash&&surfaceBiome==Biome.SOUL_SAND_VALLEY,badlands=(ash||snow)&&(surfaceBiome==Biome.BADLANDS||surfaceBiome==Biome.ERODED_BADLANDS||surfaceBiome==Biome.WOODED_BADLANDS);
double ashBiome=climate(seed^321,gx,gz,1100),soil=noise(seed^741,gx,gz,64);
boolean snowForest=snow&&Set.of(Biome.SNOWY_TAIGA,Biome.OLD_GROWTH_PINE_TAIGA,Biome.OLD_GROWTH_SPRUCE_TAIGA,Biome.GROVE).contains(biome(world,gx,h,gz,planet));
boolean mangrove=island&&h>=SEA-2&&h<=SEA+10&&climate(seed^873,gx,gz,520)>.34;
Material surface=rocky?(soil>.35?Material.GRAVEL:soil<-.45?Material.COARSE_DIRT:Material.STONE):basalt?Material.BASALT:soul?(soil>0?Material.SOUL_SAND:Material.SOUL_SOIL):badlands?(surfaceBiome==Biome.WOODED_BADLANDS?Material.COARSE_DIRT:Material.RED_SAND):mangrove?Material.MUD:snow?(distance<30?Material.BASALT:distance<112?Material.MYCELIUM:snowForest?Material.GRASS_BLOCK:Material.SNOW_BLOCK):ash?(h<=SEA+2||slope>1?soil>0?Material.STONE:Material.DEEPSLATE:soil<-.2?Material.COARSE_DIRT:Material.DIRT):h<SEA-2?Material.SAND:planet.equals("kaitain")&&h<=SEA+beachWidth(seed,gx,gz)?Material.SAND:h<=SEA+2||rock?Material.STONE:Material.GRASS_BLOCK;
data.setBlock(x,min,z,Material.BEDROCK);
for(int y=min+1;y<h-3;y++)data.setBlock(x,y,z,badlands&&y>h-28?(Math.floorMod(y,12)<4?Material.BROWN_TERRACOTTA:Math.floorMod(y,12)<8?Material.GRAY_TERRACOTTA:Material.RED_TERRACOTTA):y<0?Material.DEEPSLATE:Material.STONE);
for(int y=h-3;y<h;y++)data.setBlock(x,y,z,surface==Material.GRASS_BLOCK||surface==Material.COARSE_DIRT?Material.DIRT:surface==Material.CRIMSON_NYLIUM||surface==Material.WARPED_NYLIUM?Material.NETHERRACK:surface);
data.setBlock(x,h,z,surface);if(snowForest&&h>SEA+2)data.setBlock(x,h+1,z,Material.SNOW);if(!ash)for(int y=h+1;y<=SEA;y++)data.setBlock(x,y,z,ash?Material.LAVA:Material.WATER);
if(snow&&h<SEA&&distance>=145)data.setBlock(x,SEA,z,Material.ICE);
if(snow&&distance<5)data.setBlock(x,h,z,Material.LAVA);
if(snow&&distance>34&&distance<49&&Math.floorMod(gx,11)<6&&Math.floorMod(gz,13)<6){data.setBlock(x,h-2,z,Material.MAGMA_BLOCK);data.setBlock(x,h-1,z,Material.WATER);data.setBlock(x,h,z,Material.BUBBLE_COLUMN);}
}
Material[] flowers={Material.POPPY,Material.DANDELION,Material.CORNFLOWER,Material.AZURE_BLUET,Material.OXEYE_DAISY};
for(int x=0;x<16;x++)for(int z=0;z<16;z++){
int h=tops[x][z],gx=chunkX*16+x,gz=chunkZ*16+z;boolean ash=planet.equals("giedi_prime");if(h<=SEA+2||planet.equals("sigma_draconis_iv")||(!ash&&data.getType(x,h,z)!=Material.GRASS_BLOCK)||Math.hypot((double)gx,gz)<16)continue;
if(planet.equals("kaitain")&&random.nextDouble()<.10)data.setBlock(x,h+1,z,flowers[random.nextInt(flowers.length)]);
if(x<3||x>12||z<3||z>12||random.nextDouble()>(island?.095:.022))continue;
int roll=random.nextInt(100);Biome treeBiome=ash?biome(world,gx,h,gz,planet):null;if(ash&&!Set.of(Biome.PALE_GARDEN,Biome.CRIMSON_FOREST,Biome.WARPED_FOREST,Biome.WOODED_BADLANDS).contains(treeBiome))continue;Material log=ash?(treeBiome==Biome.CRIMSON_FOREST?Material.CRIMSON_STEM:treeBiome==Biome.WARPED_FOREST?Material.WARPED_STEM:Material.PALE_OAK_LOG):island?(roll<65?Material.JUNGLE_LOG:roll<88?Material.SPRUCE_LOG:Material.CHERRY_LOG):roll<25?Material.OAK_LOG:roll<45?Material.BIRCH_LOG:roll<65?Material.DARK_OAK_LOG:roll<80?Material.SPRUCE_LOG:roll<90?Material.CHERRY_LOG:Material.ACACIA_LOG;
Material leaf=switch(log){case PALE_OAK_LOG->Material.PALE_OAK_LEAVES;case CRIMSON_STEM->Material.NETHER_WART_BLOCK;case WARPED_STEM->Material.WARPED_WART_BLOCK;case CHERRY_LOG->Material.CHERRY_LEAVES;case ACACIA_LOG->Material.ACACIA_LEAVES;case JUNGLE_LOG->Material.JUNGLE_LEAVES;case SPRUCE_LOG->Material.SPRUCE_LEAVES;case BIRCH_LOG->Material.BIRCH_LEAVES;case DARK_OAK_LOG->Material.DARK_OAK_LEAVES;default->Material.OAK_LEAVES;};
int tall=(island?7:5)+random.nextInt(island?6:4);if(h+tall+3>=max||!data.getType(x,h+2,z).isAir())continue;
for(int dy=1;dy<=tall;dy++)data.setBlock(x,h+dy,z,log);
for(int dy=log==Material.SPRUCE_LOG?2:tall-2;dy<=tall+1;dy++){
int radius=log==Material.SPRUCE_LOG?Math.min(3,1+(tall-dy)/2):(dy>=tall?2:3);radius=Math.max(0,radius);
for(int dx=-radius;dx<=radius;dx++)for(int dz=-radius;dz<=radius;dz++)if(Math.abs(dx)+Math.abs(dz)<=radius*2-1||radius==0){int lx=x+dx,lz=z+dz,ly=h+dy;if(lx<0||lx>=16||lz<0||lz>=16||!data.getType(lx,ly,lz).isAir())continue;var foliage=Bukkit.createBlockData(leaf);if(foliage instanceof Leaves leaves){leaves.setPersistent(false);leaves.setDistance(Math.max(1,Math.min(7,Math.abs(dx)+Math.abs(dz)+Math.max(0,dy-tall))));}data.setBlock(lx,ly,lz,foliage);}
}
}
}
}

View file

@ -0,0 +1,68 @@
package com.example.duneterrain;
import java.lang.reflect.*;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.block.*;
import org.bukkit.event.player.*;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.persistence.*;
import org.bukkit.plugin.Plugin;
/** Native Trails owns wear, counters and decay. Only provenance and brush input live here. */
public final class TrailsBridge implements Listener {
private static final NamespacedKey ORIGIN=new NamespacedKey("dunerealms","trail_original_data");
private final Plugin owner;
private TrailsBridge(Plugin owner){this.owner=owner;}
public static void start(Plugin owner){Bukkit.getPluginManager().registerEvents(new TrailsBridge(owner),owner);}
private Plugin engine(){Plugin plugin=Bukkit.getPluginManager().getPlugin("Trails");return plugin!=null&&plugin.isEnabled()?plugin:null;}
private PersistentDataContainer data(Plugin plugin,Block block)throws ReflectiveOperationException{
return (PersistentDataContainer)plugin.getClass().getClassLoader().loadClass("me.ccrama.Trails.customblockdata.CustomBlockData").getConstructor(Block.class,Plugin.class).newInstance(block,plugin);
}
static Object nativeListener(Plugin plugin)throws ReflectiveOperationException{
Class<?> result=plugin.getClass().getClassLoader().loadClass("me.ccrama.Trails.listeners.MoveEventListener");
// Resolve this one API method without resolving optional PAPI hook return types.
try{return MethodHandles.publicLookup().findVirtual(plugin.getClass(),"getMoveEventListener",MethodType.methodType(result)).invoke(plugin);}catch(Throwable failure){throw new ReflectiveOperationException("Native Trails movement API unavailable",failure);}
}
private Object listener(Plugin plugin)throws ReflectiveOperationException{return nativeListener(plugin);}
private Object link(Plugin plugin,Block block)throws ReflectiveOperationException{Object listener=listener(plugin);return listener.getClass().getMethod("getLink",Block.class).invoke(listener,block);}
private static boolean player(Player p){return p.getGameMode()==GameMode.SURVIVAL||p.getGameMode()==GameMode.ADVENTURE;}
private void failure(Exception failure){owner.getLogger().warning("Native trail brush unavailable: "+failure.getClass().getSimpleName());}
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=true) public void step(PlayerMoveEvent event){
if(event.getTo()==null||!player(event.getPlayer())||event.getPlayer().isFlying()||event.getPlayer().isInsideVehicle()||event.getFrom().getWorld()!=event.getTo().getWorld()||event.getFrom().getBlockX()==event.getTo().getBlockX()&&event.getFrom().getBlockZ()==event.getTo().getBlockZ())return;
Plugin plugin=engine();if(plugin==null)return;Block block=event.getFrom().clone().subtract(0,.1,0).getBlock();
try{if(link(plugin,block)==null)return;PersistentDataContainer data=data(plugin,block);if(!data.has(ORIGIN,PersistentDataType.STRING))data.set(ORIGIN,PersistentDataType.STRING,block.getBlockData().getAsString());}catch(ReflectiveOperationException failure){failure(failure);}
}
@EventHandler(priority=EventPriority.HIGHEST) public void brush(PlayerInteractEvent event){
if(event.getAction()!=Action.RIGHT_CLICK_BLOCK||event.getHand()!=EquipmentSlot.HAND||event.getClickedBlock()==null||event.getItem()==null||event.getItem().getType()!=Material.BRUSH||!player(event.getPlayer()))return;
Plugin plugin=engine();if(plugin==null)return;Block block=event.getClickedBlock();
try{
PersistentDataContainer data=data(plugin,block);String original=data.get(ORIGIN,PersistentDataType.STRING);if(original==null)return;
NamespacedKey walks=new NamespacedKey(plugin,"w"),name=new NamespacedKey(plugin,"n");if(!data.has(walks,PersistentDataType.INTEGER)&&!data.has(name,PersistentDataType.STRING))return;
Object current=link(plugin,block);if(current==null){clear(plugin,block);return;}
BlockData restore=Bukkit.createBlockData(original);Class<?> type=current.getClass();Object first=current;
// Reuse the plugin's own reverse-stage implementation and bookkeeping.
Class<?> decay=plugin.getClass().getClassLoader().loadClass("me.ccrama.Trails.compatibility.DecayTask");
for(int i=0;i<32;i++){
Object previous=type.getMethod("getPrevious").invoke(first);if(previous==null)break;
data.set(walks,PersistentDataType.INTEGER,0);decay.getMethod("decayPath",Block.class,type).invoke(null,block,first);first=previous;
}
// A chain may have been entered at DIRT or COARSE_DIRT rather than GRASS.
// Stored provenance, not the chain's first stage, defines the actual original.
if(!block.getBlockData().matches(restore)){BlockData before=block.getBlockData();Material beforeType=block.getType();block.setBlockData(restore,true);log(event.getPlayer().getName(),block,beforeType,before,restore.getMaterial(),restore);}
clear(plugin,block);event.setCancelled(true);event.getPlayer().swingMainHand();block.getWorld().playSound(block.getLocation(),Sound.ITEM_BRUSH_BRUSHING_GENERIC,.5f,1);
}catch(ReflectiveOperationException|IllegalArgumentException failure){failure(failure);}
}
private void clear(Plugin plugin,Block block)throws ReflectiveOperationException{PersistentDataContainer data=data(plugin,block);data.remove(ORIGIN);data.remove(new NamespacedKey(plugin,"w"));data.remove(new NamespacedKey(plugin,"n"));}
private void log(String actor,Block block,Material before,BlockData old,Material after,BlockData next){
Plugin cp=Bukkit.getPluginManager().getPlugin("CoreProtect");if(cp==null||!cp.isEnabled())return;
try{Object api=cp.getClass().getMethod("getAPI").invoke(cp);api.getClass().getMethod("logRemoval",String.class,Location.class,Material.class,BlockData.class).invoke(api,actor,block.getLocation(),before,old);api.getClass().getMethod("logPlacement",String.class,Location.class,Material.class,BlockData.class).invoke(api,actor,block.getLocation(),after,next);}catch(ReflectiveOperationException failure){owner.getLogger().warning("Trail brush CoreProtect logging unavailable");}
}
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void placed(BlockPlaceEvent event){Plugin plugin=engine();if(plugin!=null)try{clear(plugin,event.getBlock());}catch(ReflectiveOperationException failure){failure(failure);}}
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void broken(BlockBreakEvent event){Plugin plugin=engine();if(plugin!=null)try{clear(plugin,event.getBlock());}catch(ReflectiveOperationException failure){failure(failure);}}
}