Add Arrakis Jerboa ecology and native worm pets without rebuilding live terrain

This commit is contained in:
unimatrixgit 2026-11-23 00:24:01 +01:00
commit 1bc455ae48
5 changed files with 1062 additions and 908 deletions

View file

@ -0,0 +1,87 @@
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 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);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 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 boolean protectedMob(LivingEntity e){return pet(e)||e.customName()!=null||e.hasMetadata("NPC")||!e.getPersistentDataContainer().getKeys().isEmpty()||e instanceof Tameable t&&t.isTamed();}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void spawning(CreatureSpawnEvent event){
var e=event.getEntity();if(!arrakis(e))return;
if(e instanceof Rabbit rabbit){rabbit.customName(Component.text("Jerboa",NamedTextColor.YELLOW));rabbit.setRabbitType(Rabbit.Type.GOLD);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))return;
Bukkit.getScheduler().runTask(plugin,()->{if(!e.isValid())return;if(e instanceof Rabbit rabbit){rabbit.customName(Component.text("Jerboa",NamedTextColor.YELLOW));rabbit.setRabbitType(Rabbit.Type.GOLD);}else if(pet(e))restoreWater((Wolf)e);else if(!protectedMob(e))e.remove();});
}
private void maintain(){for(var world:Bukkit.getWorlds())for(var e:world.getEntitiesByClass(Wolf.class))if(pet(e))restoreWater(e);}
/** 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.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);if(!wolf.isTamed()){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);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.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){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");var drops=new ArrayList<ItemStack>();drops.add(raw);drops.add(hide);if(random.getAsDouble()<.2)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");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")||!"jerboa_raw_meat".equals(itemId(event.getSource())))return;try{event.setResult(items.build("jerboa_cooked_meat"));}catch(ReflectiveOperationException failure){event.setCancelled(true);plugin.getLogger().warning("Jerboa cooking definition unavailable; input retained");}}
private static Object call(Object target,String name,Object...args)throws ReflectiveOperationException{for(var method:target.getClass().getMethods())if(method.getName().equals(name)&&method.getParameterCount()==args.length){var types=method.getParameterTypes();boolean valid=true;for(int i=0;i<args.length;i++)if(!types[i].isInstance(args[i])&&!(types[i]==int.class&&args[i] instanceof Integer))valid=false;if(valid)return method.invoke(target,args);}throw new NoSuchMethodException(name);}
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 api=score.getClass().getClassLoader().loadClass("com.ssomar.score.api.executableitems.ExecutableItemsAPI");var manager=api.getMethod("getExecutableItemsManager").invoke(null);var definition=(Optional<?>)call(manager,"getExecutableItem",id);if(definition.isEmpty())throw new ReflectiveOperationException("Missing native item definition");return (ItemStack)call(definition.get(),"buildItem",1,Optional.empty(),Optional.empty());}
@EventHandler public void disable(PluginDisableEvent event){if(event.getPlugin()!=plugin)return;INSTANCES.remove(plugin);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,20 @@
package com.example.duneterrain;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.*;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.event.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.*;
import org.bukkit.plugin.Plugin;
class ArrakisEcologyTest {
private <T extends LivingEntity>T entity(Class<T> kind,String worldName){T e=mock(kind);World world=mock(World.class);when(world.getName()).thenReturn(worldName);when(e.getWorld()).thenReturn(world);var pdc=mock(PersistentDataContainer.class);when(e.getPersistentDataContainer()).thenReturn(pdc);when(pdc.getKeys()).thenReturn(Set.of());return e;}
@Test void ordinaryNaturalMobsAreBlockedOnlyOnArrakis(){var feature=new ArrakisEcology(mock(Plugin.class),id->{throw new AssertionError();},()->0);var desert=new CreatureSpawnEvent(entity(Zombie.class,"arrakis"),CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(desert);assertTrue(desert.isCancelled());var other=new CreatureSpawnEvent(entity(Zombie.class,"caladan"),CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(other);assertFalse(other.isCancelled());}
@Test void customSpawnedRaidersAndTaggedCreaturesSurvive(){var feature=new ArrakisEcology(mock(Plugin.class),id->{throw new AssertionError();},()->0);var custom=new CreatureSpawnEvent(entity(Zombie.class,"arrakis"),CreatureSpawnEvent.SpawnReason.CUSTOM);feature.spawning(custom);assertFalse(custom.isCancelled());var tagged=entity(Zombie.class,"arrakis");when(tagged.getPersistentDataContainer().getKeys()).thenReturn(Set.of(new NamespacedKey("dunerealms","raider")));var event=new CreatureSpawnEvent(tagged,CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(event);assertFalse(event.isCancelled());}
@Test void fireDeathsUseCookedDefinitionAndWaterRollIsExactlyTwentyPercent(){for(boolean burning:new boolean[]{false,true})for(double roll:new double[]{.19999,.2}){var animal=entity(Rabbit.class,"arrakis");when(animal.getFireTicks()).thenReturn(burning?20:0);var meat=mock(ItemStack.class);var hide=mock(ItemStack.class);var vial=mock(ItemStack.class);var requested=new ArrayList<String>();var feature=new ArrakisEcology(mock(Plugin.class),id->{requested.add(id);return id.equals("jerboa_hide")?hide:id.equals("jerboa_water_vial")?vial:meat;},()->roll);var event=new EntityDeathEvent(animal,mock(org.bukkit.damage.DamageSource.class),new ArrayList<>());feature.death(event);assertEquals(burning?"jerboa_cooked_meat":"jerboa_raw_meat",requested.getFirst());assertEquals(roll<.2?List.of(meat,hide,vial):List.of(meat,hide),event.getDrops());}}
@Test void suffocationImmunityDoesNotDependOnWater(){var wolf=entity(Wolf.class,"arrakis");when(wolf.getPersistentDataContainer().has(new NamespacedKey("dunerealms","tiny_worm_pet"),PersistentDataType.BYTE)).thenReturn(true);var feature=new ArrakisEcology(mock(Plugin.class),id->{throw new AssertionError();},()->0);var event=mock(EntityDamageEvent.class);when(event.getEntity()).thenReturn(wolf);when(event.getCause()).thenReturn(EntityDamageEvent.DamageCause.SUFFOCATION);feature.suffocation(event);verify(event).setCancelled(true);var attack=mock(EntityDamageEvent.class);when(attack.getEntity()).thenReturn(wolf);when(attack.getCause()).thenReturn(EntityDamageEvent.DamageCause.ENTITY_ATTACK);feature.suffocation(attack);verify(attack,never()).setCancelled(anyBoolean());}
}

View file

@ -17,3 +17,13 @@ and preserve the live 1.0.12-arrakeen1 terrain build when recovering its source.
Reapplication refreshes the duration rather than stacking modifiers.
- Pet death: spice and one bone, both guaranteed. Bone bears the pet's name,
Legendary MK XIV; memorial item, no extra combat power.
## Ecology implementation and rollout
`ArrakisEcology` supplies the Arrakis-only spawn filter, Jerboa breeding and custom drops, fire cooking, furnace/smoker/campfire result hook, and native wolf pet flow. Bloom coordinates are recorded in the chunk PDC so revisiting a bloom does not issue another pet. Water applies one named +25% attack/max-health modifier for 90 seconds, plus Regeneration I. Refreshes do not stack modifiers; absolute expiry is checked after entity load and on a one-second maintenance tick. Native wolf AI, ownership, growth and mating remain in use.
`tools/PatchArrakisEcology.java` adds only this class and its item-factory interface to the exact SHA-256-pinned live `1.0.12-arrakeen1` JAR. It injects two calls into the existing startup and bloom methods. All unrelated existing methods and JAR entries are checked byte for byte. Do not deploy the complete older terrain build from this checkout.
Four new behavioural tests cover planet isolation, natural vs custom/tagged mobs, raw vs fire-cooked death drops and the exact 20% vial threshold, and suffocation immunity without a water buff. The terrain suite has 19 passing tests.
Still pending: custom Jerboa/worm textures and the flesh/hide artwork, pet/water runtime verification, and actual rollout. Gold rabbits and native wolves remain visual placeholders until the world-scoped artwork is ready. No texture or real player interaction is claimed as verified.

View file

@ -0,0 +1,35 @@
import java.io.*;
import java.nio.file.*;
import java.security.*;
import java.util.*;
import java.util.zip.*;
import org.objectweb.asm.*;
import org.objectweb.asm.tree.*;
/** Extend the exact live terrain build; never deploy a rebuild of stale terrain sources. */
public final class PatchArrakisEcology {
static final String MAIN="com/example/duneterrain/DuneTerrain.class",ADDON="com/example/duneterrain/ArrakisEcology";
static final String ORIGINAL="f6f8547049bfd022bc68b57f37c5a259f268c2ad54a2aa08790ac3f011920bcf";
static byte[] methodBytes(MethodNode method){var out=new ClassWriter(0);out.visit(65,Opcodes.ACC_PUBLIC,"MethodCheck",null,"java/lang/Object",null);method.accept(out.visitMethod(method.access,method.name,method.desc,method.signature,method.exceptions.toArray(String[]::new)));out.visitEnd();return out.toByteArray();}
static byte[] patch(byte[] original){
var node=new ClassNode();new ClassReader(original).accept(node,0);var before=new HashMap<String,byte[]>();var touched=new HashSet<String>();
for(var method:node.methods){
for(var instruction:method.instructions)if(instruction instanceof MethodInsnNode call&&call.owner.equals(ADDON))throw new IllegalStateException("Ecology is already installed");
String key=method.name+method.desc;before.put(key,methodBytes(method));
boolean start=key.equals("onEnable()V"),bloom=key.equals("announceSpiceBloom(Lorg/bukkit/Location;)V");if(!start&&!bloom)continue;
var hook=new InsnList();hook.add(new VarInsnNode(Opcodes.ALOAD,0));if(bloom)hook.add(new VarInsnNode(Opcodes.ALOAD,1));hook.add(new MethodInsnNode(Opcodes.INVOKESTATIC,ADDON,start?"start":"bloom",start?"(Lorg/bukkit/plugin/Plugin;)V":"(Lorg/bukkit/plugin/Plugin;Lorg/bukkit/Location;)V",false));method.instructions.insert(hook);method.maxStack=Math.max(method.maxStack,bloom?2:1);touched.add(key);
}
if(!touched.equals(Set.of("onEnable()V","announceSpiceBloom(Lorg/bukkit/Location;)V")))throw new IllegalStateException("Live terrain hooks changed");
var writer=new ClassWriter(0);node.accept(writer);byte[] result=writer.toByteArray();var check=new ClassNode();new ClassReader(result).accept(check,0);for(var method:check.methods){String key=method.name+method.desc;if(!touched.contains(key)&&!Arrays.equals(before.get(key),methodBytes(method)))throw new IllegalStateException("Unrelated terrain method changed: "+key);}return result;
}
public static void main(String[] args)throws Exception{
if(args.length!=3)throw new IllegalArgumentException("original.jar classes-folder output.jar");var source=Path.of(args[0]);var classes=Path.of(args[1]);var target=Path.of(args[2]);if(Files.exists(target)||source.toRealPath().equals(target.toAbsolutePath()))throw new IllegalStateException("Use a new output file");if(!HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(source))).equals(ORIGINAL))throw new IllegalStateException("Live terrain identity changed");
var entries=new LinkedHashMap<String,byte[]>();try(var zip=new ZipInputStream(Files.newInputStream(source))){for(ZipEntry entry;(entry=zip.getNextEntry())!=null;){if(entries.put(entry.getName(),zip.readAllBytes())!=null)throw new IllegalStateException("Duplicate JAR entry");}}
var baseline=new LinkedHashMap<>(entries);entries.put(MAIN,patch(Objects.requireNonNull(entries.get(MAIN))));String descriptor=new String(entries.get("plugin.yml"),java.nio.charset.StandardCharsets.UTF_8);if(!descriptor.contains("version: 1.0.12-arrakeen1"))throw new IllegalStateException("Unexpected live version");entries.put("plugin.yml",descriptor.replace("version: 1.0.12-arrakeen1","version: 1.0.12-arrakeen1-ecology1").getBytes(java.nio.charset.StandardCharsets.UTF_8));
var additions=new ArrayList<String>();try(var paths=Files.list(classes.resolve("com/example/duneterrain"))){for(var p:paths.filter(p->p.getFileName().toString().matches("ArrakisEcology(?:\\$[A-Za-z0-9]+)?\\.class")).sorted().toList()){String name="com/example/duneterrain/"+p.getFileName();if(entries.containsKey(name))throw new IllegalStateException("Duplicate ecology class");entries.put(name,Files.readAllBytes(p));additions.add(name);}}
if(!additions.contains(ADDON+".class")||!additions.contains(ADDON+"$Items.class"))throw new IllegalStateException("Compiled ecology classes missing");
for(var e:baseline.entrySet())if(!Set.of(MAIN,"plugin.yml").contains(e.getKey())&&!Arrays.equals(e.getValue(),entries.get(e.getKey())))throw new IllegalStateException("Unrelated JAR entry changed");
Files.createDirectories(target.toAbsolutePath().getParent());try(var out=new ZipOutputStream(Files.newOutputStream(target,StandardOpenOption.CREATE_NEW))){for(var e:entries.entrySet()){var entry=new ZipEntry(e.getKey());entry.setTime(0);out.putNextEntry(entry);out.write(e.getValue());out.closeEntry();}}
System.out.println("Preserved "+(baseline.size()-2)+" existing JAR entries; changed only terrain hooks and version; added "+additions.size()+" ecology classes.");System.out.println("SHA256 "+HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(target))));
}
}