From e4a5b72406292b2826f02f164cae4d9e3d381cfb Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:33:07 +0100 Subject: [PATCH] Add tiered Arrakis sietches and explicit no-backup regeneration --- DuneTerrain/build.gradle.kts | 2 +- .../com/example/duneterrain/DuneTerrain.java | 1741 ++++++++--------- .../example/duneterrain/SietchBuilder.java | 324 +++ .../com/example/duneterrain/SietchLayout.java | 130 ++ DuneTerrain/src/main/resources/config.yml | 14 +- DuneTerrain/src/main/resources/plugin.yml | 2 +- .../duneterrain/HighlandSietchesTest.java | 27 - .../example/duneterrain/SietchLayoutTest.java | 91 + tools/plugin_pillager_abi.py | 2 +- tools/reset-arrakis-terrain.py | 51 + 10 files changed, 1383 insertions(+), 1001 deletions(-) create mode 100644 DuneTerrain/src/main/java/com/example/duneterrain/SietchBuilder.java create mode 100644 DuneTerrain/src/main/java/com/example/duneterrain/SietchLayout.java create mode 100644 DuneTerrain/src/test/java/com/example/duneterrain/SietchLayoutTest.java diff --git a/DuneTerrain/build.gradle.kts b/DuneTerrain/build.gradle.kts index 41b50641..db020d30 100644 --- a/DuneTerrain/build.gradle.kts +++ b/DuneTerrain/build.gradle.kts @@ -1,7 +1,7 @@ plugins { java } group = "com.example" -version = "1.0.15-pillager1" +version = "1.0.16-sietch1" repositories { mavenCentral() diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java b/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java index b63558ca..754a6bc4 100644 --- a/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java +++ b/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java @@ -1,966 +1,775 @@ -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; - final SpiceDepositProvenance spiceProvenance=new SpiceDepositProvenance(); - public boolean isGeneratedSpiceDeposit(Block block){return block!=null&&block.getWorld().getName().equals("arrakis")&&SpiceDepositProvenance.authentic(block);} - @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void placedSpice(org.bukkit.event.block.BlockPlaceEvent event){if(event.getBlock().getWorld().getName().equals("arrakis")){SpiceDepositProvenance.forget(event.getBlock());SpiceDepositProvenance.invalidateBloom(event.getBlock());}} - @EventHandler public void spiceChunkPopulated(org.bukkit.event.world.ChunkPopulateEvent event){if(event.getWorld().getName().equals("arrakis"))spiceProvenance.commitBloom(event.getChunk());} - @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void brokenBloom(org.bukkit.event.block.BlockBreakEvent event){if(event.getBlock().getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(event.getBlock());} - @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void movedBloom(org.bukkit.event.block.BlockPistonExtendEvent event){for(Block block:event.getBlocks())if(block.getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(block);} - @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void retractedBloom(org.bukkit.event.block.BlockPistonRetractEvent event){for(Block block:event.getBlocks())if(block.getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(block);} - @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void explodedBloom(org.bukkit.event.entity.EntityExplodeEvent event){for(Block block:event.blockList())if(block.getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(block);} - @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void changedBloom(org.bukkit.event.entity.EntityChangeBlockEvent event){if(event.getBlock().getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(event.getBlock());} - private final Map 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)))||ArrakisBlooms.matches(center.getWorld().getSeed(),center.getX(),center.getZ(),Math.max(1,getConfig().getInt("spice-blow.rarity",ArrakisBlooms.DESERT_WELL_RARITY))))&¢er.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; - boolean authenticatedBloom=SpiceDepositProvenance.takeBloom(center); - 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 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); - if(authenticatedBloom)SpiceDepositProvenance.mark(block.getState()); - 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 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 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() { com.dunerealms.npc.CitizensBridge.start(this,new NamespacedKey("dunerealms","spice-seller")); - 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 formationGround = new java.util.concurrent.ConcurrentHashMap<>(); - PlanetChunkGenerator(DuneTerrain plugin, String planet) { this.plugin = plugin; this.planet = planet; } - @Override public List 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),plugin.spiceProvenance) : 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); - if(planet.equals("arrakis")){ - for(int y=minY+1;y<=h;y++)data.setBlock(x,y,z,ArrakisStrata.material(h-y)); - }else{ - 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); - var emittedSpice=new ArrayList(); - if (arrakisWorld) { - placeDarkstoneIsland(data, chunkX, chunkZ, heights, minY, maxY); - placeSpiceDeposits(data, heights, random, minY, maxY,emittedSpice); - placeRandomSpicePatch(data, chunkX, chunkZ, heights,emittedSpice); - 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); - if(arrakisWorld&&plugin.spiceProvenance!=null)plugin.spiceProvenance.capture(world,chunkX,chunkZ,emittedSpice,data); - } - @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,List emitted) { - 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);emitted.add(new SpiceDepositProvenance.Position(x,y,z));} - } - } - private void placeRandomSpicePatch(ChunkData data, int chunkX, int chunkZ, int[][] heights,List emitted) { - 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);emitted.add(new SpiceDepositProvenance.Position(x,y,z));} - } - } - } - 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(ArrakisStrata.air(top))continue; - if(top==Material.RED_SAND||top==Material.ORANGE_TERRACOTTA)data.setBlock(x,y,z,Material.SAND); - break; - } - // Native clay disk geometry: one candidate per chunk, radius 2–3, - // half-height 1, inside sandstone below the four sand layers. - 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(!ArrakisStrata.air(data.getType(cx,y,cz))){surface=y;break;} - if(surface>minWorldY+7&&data.getType(cx,surface,cz)==Material.SAND&&data.getType(cx,surface-3,cz)==Material.SAND&&data.getType(cx,surface-4,cz)==Material.SANDSTONE){ - int center=surface-5; - 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&&ArrakisStrata.air(data.getType(x,columnSurface,z)))columnSurface--; - if(y>columnSurface-4||data.getType(x,columnSurface,z)!=Material.SAND||data.getType(x,columnSurface-3,z)!=Material.SAND||data.getType(x,columnSurface-4,z)!=Material.SANDSTONE)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 getBiomes(WorldInfo info) { - if(TemperateLandscape.enabled(planet))return TemperateLandscape.biomes(planet); - Set 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> 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; - var anchor=ArrakisBlooms.anchor(world.getSeed(),chunkX,chunkZ,Math.max(1,plugin.getConfig().getInt("spice-blow.rarity",ArrakisBlooms.DESERT_WELL_RARITY))); - if(anchor==null)return; - int x=anchor.x(),z=anchor.z(),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); - if(plugin.spiceProvenance!=null)plugin.spiceProvenance.bloom(world,chunkX,chunkZ,new SpiceDepositProvenance.Position(x,y+1,z)); - } - } -} +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; + final SpiceDepositProvenance spiceProvenance=new SpiceDepositProvenance(); + public boolean isGeneratedSpiceDeposit(Block block){return block!=null&&block.getWorld().getName().equals("arrakis")&&SpiceDepositProvenance.authentic(block);} + @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void placedSpice(org.bukkit.event.block.BlockPlaceEvent event){if(event.getBlock().getWorld().getName().equals("arrakis")){SpiceDepositProvenance.forget(event.getBlock());SpiceDepositProvenance.invalidateBloom(event.getBlock());}} + @EventHandler public void spiceChunkPopulated(org.bukkit.event.world.ChunkPopulateEvent event){if(event.getWorld().getName().equals("arrakis"))spiceProvenance.commitBloom(event.getChunk());} + @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void brokenBloom(org.bukkit.event.block.BlockBreakEvent event){if(event.getBlock().getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(event.getBlock());} + @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void movedBloom(org.bukkit.event.block.BlockPistonExtendEvent event){for(Block block:event.getBlocks())if(block.getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(block);} + @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void retractedBloom(org.bukkit.event.block.BlockPistonRetractEvent event){for(Block block:event.getBlocks())if(block.getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(block);} + @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void explodedBloom(org.bukkit.event.entity.EntityExplodeEvent event){for(Block block:event.blockList())if(block.getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(block);} + @EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true) public void changedBloom(org.bukkit.event.entity.EntityChangeBlockEvent event){if(event.getBlock().getWorld().getName().equals("arrakis"))SpiceDepositProvenance.invalidateBloom(event.getBlock());} + private final Map 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)))||ArrakisBlooms.matches(center.getWorld().getSeed(),center.getX(),center.getZ(),Math.max(1,getConfig().getInt("spice-blow.rarity",ArrakisBlooms.DESERT_WELL_RARITY))))&¢er.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; + boolean authenticatedBloom=SpiceDepositProvenance.takeBloom(center); + 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 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); + if(authenticatedBloom)SpiceDepositProvenance.mark(block.getState()); + 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 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 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() { com.dunerealms.npc.CitizensBridge.start(this,new NamespacedKey("dunerealms","spice-seller")); + 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 formationGround = new java.util.concurrent.ConcurrentHashMap<>(); + PlanetChunkGenerator(DuneTerrain plugin, String planet) { this.plugin = plugin; this.planet = planet; } + @Override public List 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),plugin.spiceProvenance) : 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); + if(planet.equals("arrakis")){ + for(int y=minY+1;y<=h;y++)data.setBlock(x,y,z,ArrakisStrata.material(h-y)); + }else{ + 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); + var emittedSpice=new ArrayList(); + if (arrakisWorld) { + placeDarkstoneIsland(data, chunkX, chunkZ, heights, minY, maxY); + placeSpiceDeposits(data, heights, random, minY, maxY,emittedSpice); + placeRandomSpicePatch(data, chunkX, chunkZ, heights,emittedSpice); + 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); + if(arrakisWorld&&plugin.spiceProvenance!=null)plugin.spiceProvenance.capture(world,chunkX,chunkZ,emittedSpice,data); + } + @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,List emitted) { + 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);emitted.add(new SpiceDepositProvenance.Position(x,y,z));} + } + } + private void placeRandomSpicePatch(ChunkData data, int chunkX, int chunkZ, int[][] heights,List emitted) { + 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);emitted.add(new SpiceDepositProvenance.Position(x,y,z));} + } + } + } + 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(ArrakisStrata.air(top))continue; + if(top==Material.RED_SAND||top==Material.ORANGE_TERRACOTTA)data.setBlock(x,y,z,Material.SAND); + break; + } + // Native clay disk geometry: one candidate per chunk, radius 2–3, + // half-height 1, inside sandstone below the four sand layers. + 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(!ArrakisStrata.air(data.getType(cx,y,cz))){surface=y;break;} + if(surface>minWorldY+7&&data.getType(cx,surface,cz)==Material.SAND&&data.getType(cx,surface-3,cz)==Material.SAND&&data.getType(cx,surface-4,cz)==Material.SANDSTONE){ + int center=surface-5; + 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&&ArrakisStrata.air(data.getType(x,columnSurface,z)))columnSurface--; + if(y>columnSurface-4||data.getType(x,columnSurface,z)!=Material.SAND||data.getType(x,columnSurface-3,z)!=Material.SAND||data.getType(x,columnSurface-4,z)!=Material.SANDSTONE)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 getBiomes(WorldInfo info) { + if(TemperateLandscape.enabled(planet))return TemperateLandscape.biomes(planet); + Set 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 SietchBuilder builder; + private SietchPopulator(DuneTerrain plugin) { + this.plugin = plugin; + this.builder = new SietchBuilder((region, x, y, z, a, b) -> placePersonalChest(region, x, y, z, a, b)); + } + + private int spacing(SietchLayout.Tier tier) { + int fallback = tier == SietchLayout.Tier.LARGE ? plugin.getConfig().getInt("sietches.spacing", tier.spacing) : tier.spacing; + return Math.max(128, plugin.getConfig().getInt("sietches." + tier.key() + ".spacing", fallback)); + } + + @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; + for (SietchLayout.Tier tier : SietchLayout.Tier.values()) { + if (!plugin.getConfig().getBoolean("sietches." + tier.key() + ".enabled", true)) continue; + SietchLayout.Anchor anchor = SietchLayout.anchor(tier, spacing(tier), cx, cz); + if (anchor == null || !SietchLayout.fitsWindow(tier, anchor.x(), anchor.z(), cx, cz)) continue; + if (!SietchLayout.clear(tier, anchor, this::spacing)) continue; + builder.build(region, tier, anchor, world.getMinHeight(), world.getMaxHeight()); + return; + } + } + + private void placePersonalChest(LimitedRegion r, int x, int y, int z, long cellX, long cellZ) { + set(r, x, y-1, z, Material.CHISELED_SANDSTONE); + 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; + var anchor=ArrakisBlooms.anchor(world.getSeed(),chunkX,chunkZ,Math.max(1,plugin.getConfig().getInt("spice-blow.rarity",ArrakisBlooms.DESERT_WELL_RARITY))); + if(anchor==null)return; + int x=anchor.x(),z=anchor.z(),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); + if(plugin.spiceProvenance!=null)plugin.spiceProvenance.bloom(world,chunkX,chunkZ,new SpiceDepositProvenance.Position(x,y+1,z)); + } + } +} diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/SietchBuilder.java b/DuneTerrain/src/main/java/com/example/duneterrain/SietchBuilder.java new file mode 100644 index 00000000..b5114df0 --- /dev/null +++ b/DuneTerrain/src/main/java/com/example/duneterrain/SietchBuilder.java @@ -0,0 +1,324 @@ +package com.example.duneterrain; + +import java.util.Random; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.Ageable; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.Bisected; +import org.bukkit.block.data.Levelled; +import org.bukkit.block.data.type.Bed; +import org.bukkit.block.data.type.Farmland; +import org.bukkit.block.data.type.Ladder; +import org.bukkit.block.data.type.Lantern; +import org.bukkit.block.data.type.Stairs; +import org.bukkit.block.data.type.TrapDoor; +import org.bukkit.generator.LimitedRegion; + +/** + * Builds the three Arrakis sietch tiers inside a populate window. Geometry comes from {@link SietchLayout}. + * Small: a hidden cell with no water. Medium: three rooms plus an organic pool. Large: a cistern hall with a big + * pool, a bridge, six rooms and a three-plot farm. All entrances are windtrap towers (Medium, Large) or a hatch (Small). + * Untested in game; the placement is written against Paper 1.21.8 LimitedRegion. + */ +final class SietchBuilder { + interface Cache { void place(LimitedRegion region, int x, int y, int z, long a, long b); } + + private final Cache cache; + SietchBuilder(Cache cache) { this.cache = cache; } + + /** Returns false when the terrain is unsuitable (too steep, wet or too shallow) and nothing was built. */ + boolean build(LimitedRegion region, SietchLayout.Tier tier, SietchLayout.Anchor anchor, int minHeight, int maxHeight) { + return new Site(region, tier, anchor, minHeight, maxHeight).run(); + } + + private static final Material WALL = Material.CUT_SANDSTONE, FLOOR = Material.SMOOTH_SANDSTONE, CEIL = Material.SMOOTH_SANDSTONE; + + private final class Site { + final LimitedRegion r; final SietchLayout.Tier tier; final int ax, az, minHeight, maxHeight; final long id; final Random rng; + int L; // y of the hall/room floor row; floor top is L+1 + int hallH; // air height of the hall + + Site(LimitedRegion r, SietchLayout.Tier tier, SietchLayout.Anchor a, int minHeight, int maxHeight) { + this.r = r; this.tier = tier; this.ax = a.x(); this.az = a.z(); this.id = a.id(); this.minHeight = minHeight; this.maxHeight = maxHeight; + this.rng = new Random(a.id()); + } + + // ---------- low-level helpers (dx/dz relative to the anchor, y absolute) ---------- + void put(int dx, int y, int dz, Material m) { int x = ax + dx, z = az + dz; if (r.isInRegion(x, y, z)) r.setType(x, y, z, m); } + void data(int dx, int y, int dz, BlockData d) { int x = ax + dx, z = az + dz; if (r.isInRegion(x, y, z)) r.setBlockData(x, y, z, d); } + int surface(int dx, int dz) { return r.getHighestBlockYAt(ax + dx, az + dz); } + void box(int x1, int y1, int z1, int x2, int y2, int z2, Material m) { + for (int x = Math.min(x1, x2); x <= Math.max(x1, x2); x++) for (int y = Math.min(y1, y2); y <= Math.max(y1, y2); y++) + for (int z = Math.min(z1, z2); z <= Math.max(z1, z2); z++) put(x, y, z, m); + } + BlockData stairs(Material m, BlockFace face) { Stairs s = (Stairs) m.createBlockData(); s.setFacing(face); s.setHalf(Bisected.Half.BOTTOM); return s; } + void lantern(int dx, int y, int dz) { Lantern l = (Lantern) Material.LANTERN.createBlockData(); l.setHanging(true); data(dx, y, dz, l); } + void bed(int footX, int y, int footZ, BlockFace headToward, Material color) { + Bed foot = (Bed) color.createBlockData(); foot.setFacing(headToward); foot.setPart(Bed.Part.FOOT); + Bed head = (Bed) color.createBlockData(); head.setFacing(headToward); head.setPart(Bed.Part.HEAD); + data(footX, y, footZ, foot); data(footX + headToward.getModX(), y, footZ + headToward.getModZ(), head); + } + + // ---------- driver ---------- + boolean run() { + int minS = Integer.MAX_VALUE, maxS = Integer.MIN_VALUE, h = tier.half - 2; + for (int[] p : new int[][]{{0, 0}, {h, h}, {-h, h}, {h, -h}, {-h, -h}, {h, 0}, {-h, 0}, {0, h}, {0, -h}}) { + int s = surface(p[0], p[1]); minS = Math.min(minS, s); maxS = Math.max(maxS, s); + } + if (maxS - minS > 12 || maxS + 16 >= maxHeight) return false; + var top = r.getType(ax, surface(0, 0), az); + if (top == Material.WATER || top == Material.LAVA || top == Material.ICE || top == Material.PACKED_ICE) return false; + switch (tier) { + case SMALL -> { int fy = minS - 9; if (fy - 3 < minHeight) return false; small(fy, surface(-6, 0)); } + case MEDIUM -> { hallH = 6; L = minS - 11; if (L - 4 < minHeight) return false; big(); } + case LARGE -> { hallH = 8; L = minS - 13; if (L - 4 < minHeight) return false; big(); } + } + return true; + } + + // ---------- rooms ---------- + void shell(SietchLayout.Room rm, int y1, int y2) { + box(rm.x1() - 1, y1 - 1, rm.z1() - 1, rm.x2() + 1, y2 + 1, rm.z2() + 1, WALL); + box(rm.x1() - 1, y1 - 1, rm.z1() - 1, rm.x2() + 1, y1 - 1, rm.z2() + 1, FLOOR); + box(rm.x1() - 1, y2 + 1, rm.z1() - 1, rm.x2() + 1, y2 + 1, rm.z2() + 1, CEIL); + } + void hollow(SietchLayout.Room rm, int y1, int y2) { box(rm.x1(), y1, rm.z1(), rm.x2(), y2, rm.z2(), Material.AIR); } + int y1Of(SietchLayout.Room rm) { return rm.kind().equals("farm") ? L : L + 1; } + + // ---------- SMALL: the hidden cell ---------- + void small(int fy, int hatchY) { + var rooms = SietchLayout.rooms(tier); + for (var rm : rooms) shell(rm, fy, fy + rm.height() - 1); + for (var rm : rooms) hollow(rm, fy, fy + rm.height() - 1); + box(5, fy, -1, 5, fy + 2, 1, Material.AIR); // arch between chamber and alcove + for (int x = -5; x <= 1; x += 2) bed(x, fy, -2, BlockFace.NORTH, Material.RED_BED); // four bunks along the north wall + put(4, fy, 3, Material.BARREL); put(3, fy, 3, Material.BARREL); + put(-1, fy, 1, Material.ACACIA_FENCE); put(-1, fy + 1, 1, Material.ACACIA_PRESSURE_PLATE); + lantern(-1, fy + 3, 0); lantern(7, fy + 2, 0); + cache.place(r, ax + 7, fy, az, id, 0x534d414c4cL); + put(7, fy, -1, Material.BARREL); + // ladder shaft above the west wall of the chamber, hatch on the surface + int ceilingRow = fy + 4; + for (int y = fy; y < hatchY; y++) { put(-6, y, 0, Material.AIR); } + for (int y = ceilingRow; y < hatchY; y++) { put(-7, y, 0, WALL); put(-5, y, 0, WALL); put(-6, y, -1, WALL); put(-6, y, 1, WALL); } + for (int y = fy; y < hatchY; y++) { Ladder l = (Ladder) Material.LADDER.createBlockData(); l.setFacing(BlockFace.EAST); data(-6, y, 0, l); } + for (int dx = -7; dx <= -5; dx++) for (int dz = -1; dz <= 1; dz++) put(dx, hatchY, dz, Material.SMOOTH_SANDSTONE_SLAB); + TrapDoor hatch = (TrapDoor) Material.JUNGLE_TRAPDOOR.createBlockData(); hatch.setFacing(BlockFace.NORTH); hatch.setHalf(Bisected.Half.BOTTOM); hatch.setOpen(false); + data(-6, hatchY, 0, hatch); + } + + // ---------- MEDIUM and LARGE ---------- + void big() { + var rooms = SietchLayout.rooms(tier); + var pool = SietchLayout.pool(tier); + SietchLayout.Room hall = rooms.get(0); + int hallTop = L + hallH, ceilRow = hallTop + 1; + int[] sw = SietchLayout.stairwell(tier); + int gStair = surface(sw[0], sw[1]); + int topSky = 0; + for (int dx = -1; dx <= 1; dx++) for (int dz = -1; dz <= 1; dz++) topSky = Math.max(topSky, surface(pool.cx() + dx, pool.cz() + dz)); + int g2 = tier == SietchLayout.Tier.LARGE ? surface(-18, 8) : 0; + + for (var rm : rooms) shell(rm, y1Of(rm), y1Of(rm) + rm.height() - 1); + shell5(sw[0], sw[1], ceilRow, gStair + 7); // stairwell shell above the hall ceiling + shell5(pool.cx(), pool.cz(), ceilRow, topSky); // skylight shell + for (var rm : rooms) hollow(rm, y1Of(rm), y1Of(rm) + rm.height() - 1); + doors(); + pool(hall, pool); + pillars(hall, pool); + if (tier == SietchLayout.Tier.LARGE) bridge(pool); + spout(hall, pool); + for (var rm : rooms) furnish(rm); + hallLanterns(hall); + stairwell(sw[0], sw[1], gStair, ceilRow); + skylight(pool, ceilRow, topSky); + if (tier == SietchLayout.Tier.LARGE) windtrapDecor(-18, 8, g2); + } + + void shell5(int cx, int cz, int fromY, int toY) { + for (int y = fromY; y <= toY; y++) for (int dx = -2; dx <= 2; dx++) for (int dz = -2; dz <= 2; dz++) + if (Math.abs(dx) == 2 || Math.abs(dz) == 2) put(cx + dx, y, cz + dz, WALL); + } + + void doors() { + if (tier == SietchLayout.Tier.MEDIUM) { + for (int x : new int[]{-8, 0, 8}) box(x - 1, L + 1, -5, x + 1, L + 3, -5, Material.AIR); + } else { + for (int x : new int[]{-15, -5, 5, 15}) box(x - 1, L + 1, -11, x + 1, L + 3, -10, Material.AIR); + box(-16, L + 1, -4, -15, L + 3, -2, Material.AIR); + box(15, L + 1, -4, 16, L + 3, -2, Material.AIR); + box(-1, L + 1, 11, 1, L + 3, 12, Material.AIR); + box(-1, L, 11, 1, L, 12, Material.DIRT_PATH); + } + } + + // ---------- the organic pool: stepped depth, mosaic floor, curbed rim ---------- + void pool(SietchLayout.Room hall, SietchLayout.Pool p) { + int rx = SietchLayout.reachX(p) + 1, rz = SietchLayout.reachZ(p) + 1; + for (int dx = p.cx() - rx; dx <= p.cx() + rx; dx++) for (int dz = p.cz() - rz; dz <= p.cz() + rz; dz++) { + if (!hall.contains(dx, dz)) continue; + int depth = SietchLayout.poolDepth(id, p, dx, dz); + if (depth > 0) { + Material mosaic = depth == p.maxDepth() ? Material.YELLOW_TERRACOTTA + : ((Math.floorMod(dx, 2) + Math.floorMod(dz, 2)) % 2 == 0 ? Material.BLUE_TERRACOTTA : Material.LIGHT_BLUE_TERRACOTTA); + put(dx, L - depth, dz, mosaic); + for (int y = L - depth + 1; y <= L; y++) put(dx, y, dz, Material.WATER); + } else if (neighbourWet(hall, p, dx, dz)) { + for (int y = L - p.maxDepth(); y < L; y++) put(dx, y, dz, WALL); + put(dx, L, dz, (dx + dz) % 2 == 0 ? Material.CHISELED_SANDSTONE : Material.CUT_SANDSTONE); // curb + } + } + } + boolean neighbourWet(SietchLayout.Room hall, SietchLayout.Pool p, int dx, int dz) { + for (int[] d : new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) + if (hall.contains(dx + d[0], dz + d[1]) && SietchLayout.poolDepth(id, p, dx + d[0], dz + d[1]) > 0) return true; + return false; + } + + void pillars(SietchLayout.Room hall, SietchLayout.Pool p) { + int[][] spots; + if (tier == SietchLayout.Tier.MEDIUM) spots = new int[][]{{-5, -3}, {5, -3}, {-5, 3}}; + else { + spots = new int[12][]; + for (int i = 0; i < 12; i++) { + double a = i * Math.PI / 6; + spots[i] = new int[]{(int) Math.round(p.cx() + (p.rx() + 2) * Math.cos(a)), (int) Math.round(p.cz() + (p.rz() + 2) * Math.sin(a))}; + } + } + int[] sw = SietchLayout.stairwell(tier); + for (int[] s : spots) { + if (!hall.contains(s[0], s[1]) || SietchLayout.poolDepth(id, p, s[0], s[1]) > 0) continue; + if (Math.abs(s[0] - sw[0]) <= 3 && Math.abs(s[1] - sw[1]) <= 3) continue; + box(s[0], L + 1, s[1], s[0], L + hallH, s[1], WALL); + put(s[0], L + hallH, s[1], Material.CHISELED_SANDSTONE); + put(s[0], L + 1, s[1], Material.SMOOTH_SANDSTONE); + } + } + + void bridge(SietchLayout.Pool p) { + for (int dx = p.cx() - SietchLayout.reachX(p); dx <= p.cx() + SietchLayout.reachX(p); dx++) for (int dz = p.cz() - 1; dz <= p.cz() + 1; dz++) + if (SietchLayout.poolDepth(id, p, dx, dz) > 0) put(dx, L, dz, Material.SMOOTH_SANDSTONE); + } + + /** A copper hood spills a falling stream into the north edge of the pool. Only the top cell is a source. */ + void spout(SietchLayout.Room hall, SietchLayout.Pool p) { + int x = p.cx(), zEdge = Integer.MIN_VALUE; + for (int dz = p.cz() - SietchLayout.reachZ(p) - 1; dz <= p.cz(); dz++) if (SietchLayout.poolDepth(id, p, x, dz) > 0) { zEdge = dz; break; } + if (zEdge == Integer.MIN_VALUE || !hall.contains(x, zEdge - 1)) return; + int yTop = L + hallH - 1; + box(x, L + 1, zEdge - 1, x, L + hallH, zEdge - 1, Material.EXPOSED_CUT_COPPER); + put(x - 1, yTop, zEdge, Material.CUT_COPPER); put(x + 1, yTop, zEdge, Material.CUT_COPPER); + put(x, yTop, zEdge + 1, Material.CUT_COPPER); put(x, yTop + 1, zEdge, Material.CUT_COPPER); + put(x, yTop, zEdge, Material.WATER); + Levelled falling = (Levelled) Material.WATER.createBlockData(); falling.setLevel(8); + for (int y = yTop - 1; y > L; y--) data(x, y, zEdge, falling); + } + + void hallLanterns(SietchLayout.Room hall) { + int step = tier == SietchLayout.Tier.LARGE ? 6 : 4; + for (int x = hall.x1() + 1; x <= hall.x2() - 1; x += step) { lantern(x, L + hallH, hall.z1()); lantern(x, L + hallH, hall.z2()); } + } + + // ---------- stairwell: a spiral inside a windtrap tower, opening onto the hall's corner ---------- + static final int[][] RING = {{0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}, {1, 0}, {1, 1}}; + BlockFace face(int dx, int dz) { return dx > 0 ? BlockFace.EAST : dx < 0 ? BlockFace.WEST : dz > 0 ? BlockFace.SOUTH : BlockFace.NORTH; } + + void stairwell(int sx, int sz, int g, int ceilRow) { + for (int[] c : RING) box(sx + c[0], ceilRow, sz + c[1], sx + c[0], g + 6, sz + c[1], Material.AIR); // open shaft through the ceiling + box(sx, L + 1, sz, sx, g + 6, sz, WALL); // central pillar + put(sx, g + 6, sz, Material.CHISELED_SANDSTONE); + for (int k = 0; k < g - L; k++) { + int[] cell = RING[k % 8], prev = RING[Math.floorMod(k - 1, 8)]; + int y = g - k, px = sx + cell[0], pz = sz + cell[1]; + box(px, y + 1, pz, px, y + 3, pz, Material.AIR); + BlockFace f = k == 0 ? BlockFace.SOUTH : face(prev[0] - cell[0], prev[1] - cell[1]); + data(px, y, pz, stairs(Material.SANDSTONE_STAIRS, f)); + } + // the tower above ground: 5x5 body with vents, a door on the south side, a tapered spire + for (int y = g + 1; y <= g + 7; y++) for (int dx = -2; dx <= 2; dx++) for (int dz = -2; dz <= 2; dz++) + if (Math.abs(dx) == 2 || Math.abs(dz) == 2) put(sx + dx, y, sz + dz, WALL); + for (int y = g + 3; y <= g + 5; y += 2) { put(sx - 2, y, sz, Material.SANDSTONE_WALL); put(sx + 2, y, sz, Material.SANDSTONE_WALL); put(sx, y, sz - 2, Material.SANDSTONE_WALL); } + box(sx, g + 1, sz + 2, sx, g + 2, sz + 2, Material.AIR); + put(sx, g + 3, sz + 2, Material.CHISELED_SANDSTONE); + box(sx - 2, g + 8, sz - 2, sx + 2, g + 8, sz + 2, Material.SMOOTH_SANDSTONE_SLAB); + box(sx - 1, g + 8, sz - 1, sx + 1, g + 9, sz + 1, WALL); + box(sx, g + 10, sz, sx, g + 11, sz, WALL); + put(sx, g + 12, sz, Material.CUT_COPPER_SLAB); + lantern(sx, g + 7, sz + 1); + } + + /** A purely decorative second windtrap (no interior), so the surface reads as a sietch from a distance. */ + void windtrapDecor(int tx, int tz, int g) { + int base = Integer.MAX_VALUE; + for (int dx = -2; dx <= 2; dx++) for (int dz = -2; dz <= 2; dz++) base = Math.min(base, surface(tx + dx, tz + dz)); + for (int y = base; y <= g + 7; y++) for (int dx = -2; dx <= 2; dx++) for (int dz = -2; dz <= 2; dz++) + if (Math.abs(dx) == 2 || Math.abs(dz) == 2) put(tx + dx, y, tz + dz, WALL); + for (int y = g + 3; y <= g + 5; y += 2) { put(tx - 2, y, tz, Material.SANDSTONE_WALL); put(tx + 2, y, tz, Material.SANDSTONE_WALL); put(tx, y, tz - 2, Material.SANDSTONE_WALL); put(tx, y, tz + 2, Material.SANDSTONE_WALL); } + box(tx - 2, g + 8, tz - 2, tx + 2, g + 8, tz + 2, Material.SMOOTH_SANDSTONE_SLAB); + box(tx - 1, g + 8, tz - 1, tx + 1, g + 9, tz + 1, WALL); + box(tx, g + 10, tz, tx, g + 11, tz, WALL); + put(tx, g + 12, tz, Material.CUT_COPPER_SLAB); + } + + void skylight(SietchLayout.Pool p, int ceilRow, int top) { + for (int dx = -1; dx <= 1; dx++) for (int dz = -1; dz <= 1; dz++) { + box(p.cx() + dx, ceilRow, p.cz() + dz, p.cx() + dx, top - 1, p.cz() + dz, Material.AIR); + put(p.cx() + dx, top, p.cz() + dz, Material.GLASS); + } + } + + // ---------- furnishing ---------- + void furnish(SietchLayout.Room rm) { + int y = y1Of(rm), top = y + rm.height() - 1, cx = (rm.x1() + rm.x2()) / 2, cz = (rm.z1() + rm.z2()) / 2; + switch (rm.kind()) { + case "sleeping" -> { + for (int x = rm.x1() + 1; x <= rm.x2() - 1; x += 2) bed(x, y, rm.z1() + 1, BlockFace.NORTH, Material.RED_BED); + put(rm.x2(), y, rm.z2(), Material.BARREL); put(rm.x1(), y, rm.z2(), Material.BARREL); + lantern(cx, top, cz); + } + case "kitchen" -> { + put(rm.x1() + 1, y, rm.z1(), Material.FURNACE); put(rm.x1() + 2, y, rm.z1(), Material.SMOKER); + put(rm.x1() + 3, y, rm.z1(), Material.CRAFTING_TABLE); put(rm.x1() + 4, y, rm.z1(), Material.COMPOSTER); + for (int x = rm.x1(); x <= rm.x2(); x += 2) put(x, y, rm.z2(), Material.BARREL); + lantern(cx, top, cz); + } + case "workshop" -> { + put(rm.x1() + 1, y, rm.z1(), Material.SMITHING_TABLE); put(rm.x1() + 3, y, rm.z1(), Material.GRINDSTONE); + put(rm.x1() + 5, y, rm.z1(), Material.ANVIL); put(rm.x2(), y, rm.z2(), Material.BARREL); put(rm.x1(), y, rm.z2(), Material.BARREL); + lantern(cx, top, cz); + } + case "council" -> { + put(cx, y, rm.z1(), Material.LECTERN); + for (int z = rm.z1() + 1; z <= rm.z2(); z++) { put(cx, y, z, Material.RED_CARPET); put(rm.x1(), y, z, Material.BOOKSHELF); put(rm.x2(), y, z, Material.BOOKSHELF); } + lantern(cx, top, cz); + } + case "bank" -> { + for (int z = rm.z1(); z <= rm.z2(); z++) put(rm.x1(), y, z, Material.BOOKSHELF); + put(cx, y, rm.z1(), Material.LECTERN); put(cx + 1, y, rm.z1(), Material.COPPER_BLOCK); put(cx - 1, y, rm.z1(), Material.COPPER_BLOCK); + cache.place(r, ax + cx, y, az + rm.z2(), id, 0x42414e4bL); + lantern(cx, top, cz); + } + case "farm" -> farm(rm); + default -> { } + } + } + + // ---------- farm: three plots, each split by an open irrigation channel ---------- + void farm(SietchLayout.Room rm) { + int y = L; // farmland row; the floor row is below + box(rm.x1(), y, rm.z1(), rm.x2(), y, rm.z2(), Material.DIRT_PATH); + int[][] plots = {{-19, -8}, {-6, 5}, {7, 18}}; + Material[] crops = {Material.BEETROOTS, Material.CARROTS, Material.POTATOES}; + for (int i = 0; i < 3; i++) for (int x = plots[i][0]; x <= plots[i][1]; x++) { + for (int z = 13; z <= 19; z++) { + if (z == 16) { put(x, y, z, Material.WATER); continue; } + Farmland f = (Farmland) Material.FARMLAND.createBlockData(); f.setMoisture(7); data(x, y, z, f); + Ageable crop = (Ageable) crops[i].createBlockData(); + crop.setAge(rng.nextInt(crop.getMaximumAge() + 1)); data(x, y + 1, z, crop); + } + } + for (int x = rm.x1() + 2; x <= rm.x2() - 2; x += 5) { lantern(x, y + 4, 14); lantern(x, y + 4, 18); } + } + } +} diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/SietchLayout.java b/DuneTerrain/src/main/java/com/example/duneterrain/SietchLayout.java new file mode 100644 index 00000000..65f41410 --- /dev/null +++ b/DuneTerrain/src/main/java/com/example/duneterrain/SietchLayout.java @@ -0,0 +1,130 @@ +package com.example.duneterrain; + +import java.util.List; +import java.util.function.ToIntFunction; + +/** + * Pure geometry for the three sietch tiers: placement grids, room boxes (relative to the anchor) and the organic + * pool shape. No Bukkit types, so it is unit-tested without a server. + * + * Every footprint is centred on the middle of its chunk so it stays inside the populator's 16-block margin. + */ +final class SietchLayout { + private SietchLayout() {} + + enum Tier { + SMALL("small", 8, 600, 0x534d414c4c43454cL, 0), + MEDIUM("medium", 14, 900, 0x4d454449554d5753L, 1), + LARGE("large", 22, 2000, 0x534945544348L, 2); // LARGE keeps the legacy hash so existing anchors stay put + final String key; final int half, spacing, rank; final long salt; + Tier(String key, int half, int spacing, long salt, int rank) { this.key = key; this.half = half; this.spacing = spacing; this.salt = salt; this.rank = rank; } + String key() { return key; } + } + + record Anchor(int x, int z, long id) {} + /** Interior box relative to the anchor, inclusive; {@code height} is the number of air blocks above the floor row. */ + record Room(String kind, int x1, int z1, int x2, int z2, int height) { + boolean contains(int x, int z) { return x >= x1 && x <= x2 && z >= z1 && z <= z2; } + } + record Pool(int cx, int cz, int rx, int rz, int maxDepth) {} + + // ---------- placement ---------- + static long mix(long z) { + z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L; z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL; return z ^ (z >>> 31); + } + + /** The anchor of one grid cell, snapped to the centre of the chunk it falls in. */ + static Anchor cellAnchor(Tier tier, int spacing, long cellX, long cellZ) { + long h1 = mix(cellX * 0x9E3779B97F4A7C15L ^ cellZ * 0xC2B2AE3D27D4EB4FL ^ tier.salt); + long h2 = mix(cellZ * 0x165667B19E3779F9L ^ cellX * 0x85EBCA77C2B2AE63L ^ ~tier.salt); + long ax = cellX * spacing + 8 + Math.floorMod(h1, spacing - 16), az = cellZ * spacing + 8 + Math.floorMod(h2, spacing - 16); + int cx = (int) Math.floorDiv(ax, 16), cz = (int) Math.floorDiv(az, 16); + return new Anchor(cx * 16 + 8, cz * 16 + 8, mix(h1 ^ h2 * 31)); + } + + /** The anchor for this chunk, or null when the chunk does not host one. */ + static Anchor anchor(Tier tier, int spacing, int chunkX, int chunkZ) { + int centreX = chunkX * 16 + 8, centreZ = chunkZ * 16 + 8; + long cellX = Math.floorDiv(centreX, spacing), cellZ = Math.floorDiv(centreZ, spacing); + // the hosting cell can differ from the chunk's cell when the anchor is near a cell edge + for (long dx = -1; dx <= 1; dx++) for (long dz = -1; dz <= 1; dz++) { + Anchor a = cellAnchor(tier, spacing, cellX + dx, cellZ + dz); + if (a.x() == centreX && a.z() == centreZ) return a; + } + return null; + } + + /** Larger tiers win; equal tiers are broken by anchor id. Distances keep footprints plus a margin apart. */ + static boolean clear(Tier tier, Anchor anchor, ToIntFunction spacingOf) { + for (Tier other : Tier.values()) { + if (other.rank < tier.rank) continue; + int spacing = spacingOf.applyAsInt(other); + long cellX = Math.floorDiv(anchor.x(), spacing), cellZ = Math.floorDiv(anchor.z(), spacing); + long limit = tier.half + other.half + 16; + for (long dx = -1; dx <= 1; dx++) for (long dz = -1; dz <= 1; dz++) { + Anchor o = cellAnchor(other, spacing, cellX + dx, cellZ + dz); + if (o.x() == anchor.x() && o.z() == anchor.z() && other == tier) continue; + long ddx = o.x() - anchor.x(), ddz = o.z() - anchor.z(); + if (ddx * ddx + ddz * ddz >= limit * limit) continue; + if (other != tier) return false; + if (o.id() < anchor.id()) return false; + } + } + return true; + } + + /** True when the whole footprint (shell included) lies inside the chunk plus its 16-block populate margin. */ + static boolean fitsWindow(Tier tier, int anchorX, int anchorZ, int chunkX, int chunkZ) { + int reach = tier.half + 1; + return anchorX - reach >= chunkX * 16 - 16 && anchorX + reach <= chunkX * 16 + 31 + && anchorZ - reach >= chunkZ * 16 - 16 && anchorZ + reach <= chunkZ * 16 + 31; + } + + // ---------- rooms (interior boxes relative to the anchor) ---------- + static List rooms(Tier tier) { + return switch (tier) { + case SMALL -> List.of(new Room("chamber", -6, -3, 4, 3, 4), new Room("alcove", 6, -1, 7, 1, 3)); + case MEDIUM -> List.of( + new Room("hall", -6, -4, 6, 4, 6), + new Room("sleeping", -11, -10, -5, -6, 4), new Room("bank", -3, -10, 3, -6, 4), new Room("kitchen", 5, -10, 11, -6, 4)); + case LARGE -> List.of( + new Room("hall", -14, -9, 14, 10, 8), + new Room("sleeping", -19, -20, -11, -12, 4), new Room("sleeping", -9, -20, -1, -12, 4), + new Room("kitchen", 1, -20, 9, -12, 4), new Room("workshop", 11, -20, 19, -12, 4), + new Room("bank", -21, -8, -17, 2, 4), new Room("council", 17, -8, 21, 2, 4), + new Room("farm", -20, 13, 20, 20, 5)); + }; + } + + static Pool pool(Tier tier) { + return switch (tier) { + case SMALL -> null; + case MEDIUM -> new Pool(0, 0, 4, 3, 3); + case LARGE -> new Pool(0, 1, 10, 7, 4); + }; + } + + /** Hall corner where the entrance stairwell descends (centre of its 3x3 ring), or null for the ladder-shaft tier. */ + static int[] stairwell(Tier tier) { + return switch (tier) { case SMALL -> null; case MEDIUM -> new int[]{5, 3}; case LARGE -> new int[]{13, 9}; }; + } + + // ---------- organic pool ---------- + private static double phase(long seed, int k) { return (mix(seed * 31 + k) >>> 11) / (double) (1L << 53) * Math.PI * 2; } + + /** Water depth in blocks at an anchor-relative column: 0 outside the pool, 1 on the shallow shelf up to maxDepth in the middle. */ + static int poolDepth(long seed, Pool pool, int dx, int dz) { + double x = (dx - pool.cx()) / (double) pool.rx(), z = (dz - pool.cz()) / (double) pool.rz(); + double d = Math.sqrt(x * x + z * z); + if (d == 0) return pool.maxDepth(); + double theta = Math.atan2(z, x); + double r = 1 + 0.12 * Math.sin(3 * theta + phase(seed, 1)) + 0.06 * Math.sin(5 * theta + phase(seed, 2)); + double n = d / r; + if (n >= 1) return 0; + return Math.min(pool.maxDepth(), 1 + (int) ((1 - n) * pool.maxDepth())); + } + + /** Outer reach of the pool along each axis, including the wobble. */ + static int reachX(Pool p) { return (int) Math.ceil(p.rx() * 1.18); } + static int reachZ(Pool p) { return (int) Math.ceil(p.rz() * 1.18); } +} diff --git a/DuneTerrain/src/main/resources/config.yml b/DuneTerrain/src/main/resources/config.yml index 4592e73d..a92eb2ec 100644 --- a/DuneTerrain/src/main/resources/config.yml +++ b/DuneTerrain/src/main/resources/config.yml @@ -8,12 +8,16 @@ server: sietches: enabled: true - spacing: 2000 - # Additional sites only in Dune-highlands; open-desert grid stays unchanged. - highlands: + # Three tiers on separate grids. Larger tiers win when footprints would collide. + small: # hidden cell, no water enabled: true - frequency-multiplier: 3 - minimum-per-region: 3 + spacing: 600 + medium: # three rooms and a pool + enabled: true + spacing: 900 + large: # cistern hall, big pool, six rooms and a farm + enabled: true + spacing: 2000 spice-blow: enabled: true diff --git a/DuneTerrain/src/main/resources/plugin.yml b/DuneTerrain/src/main/resources/plugin.yml index 4f7b4578..1b4605ef 100644 --- a/DuneTerrain/src/main/resources/plugin.yml +++ b/DuneTerrain/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: DuneTerrain -version: 1.0.15-pillager1 +version: 1.0.16-sietch1 main: com.example.duneterrain.DuneTerrain api-version: '1.21' load: STARTUP diff --git a/DuneTerrain/src/test/java/com/example/duneterrain/HighlandSietchesTest.java b/DuneTerrain/src/test/java/com/example/duneterrain/HighlandSietchesTest.java index fdaaeaf2..fbcffd29 100644 --- a/DuneTerrain/src/test/java/com/example/duneterrain/HighlandSietchesTest.java +++ b/DuneTerrain/src/test/java/com/example/duneterrain/HighlandSietchesTest.java @@ -12,31 +12,4 @@ class HighlandSietchesTest { for(var a:sites){assertTrue(shape.depth(a.x(),a.z())>=.25);for(var b:sites)if(a!=b){int dx=a.x()-b.x(),dz=a.z()-b.z();assertTrue(dx*dx+dz*dz>=676);}} } } - @Test void highlandPopulationPlacesThreeSeparateCachesWithoutChangingDesertSpacing() throws Exception { - var plugin=org.mockito.Mockito.mock(DuneTerrain.class); - var config=new org.bukkit.configuration.file.YamlConfiguration(); - org.mockito.Mockito.when(plugin.getConfig()).thenReturn(config); - var world=org.mockito.Mockito.mock(org.bukkit.generator.WorldInfo.class); - org.mockito.Mockito.when(world.getMinHeight()).thenReturn(-64); - org.mockito.Mockito.when(world.getMaxHeight()).thenReturn(320); - var region=org.mockito.Mockito.mock(org.bukkit.generator.LimitedRegion.class); - org.mockito.Mockito.when(region.getHighestBlockYAt(org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.anyInt())).thenReturn(110); - org.mockito.Mockito.when(region.isInRegion(org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.anyInt())).thenReturn(true); - var cls=Class.forName("com.example.duneterrain.DuneTerrain$SietchPopulator"); - var constructor=cls.getDeclaredConstructor(DuneTerrain.class);constructor.setAccessible(true); - var populator=constructor.newInstance(plugin); - var method=cls.getDeclaredMethod("populateHighlands",org.bukkit.generator.WorldInfo.class,int.class,int.class,org.bukkit.generator.LimitedRegion.class);method.setAccessible(true); - int activeX=0,activeZ=0;outer:for(int ax=0;ax<8;ax++)for(int az=0;az<8;az++)if(RockPlateaus.activeCell(ax,az)){activeX=ax;activeZ=az;break outer;} - long seed=RockPlateaus.formationSeed(activeX,activeZ); - var shape=RockPlateaus.shape(seed,RockPlateaus.centerX(activeX,300,500),RockPlateaus.centerZ(activeZ,300,500),RockPlateaus.radius(seed,45,55),.02); - var chunks=new java.util.HashSet(); - for(var site:HighlandSietches.sites(shape,3,3))chunks.add(Math.floorDiv(site.x(),16)+","+Math.floorDiv(site.z(),16)); - for(var chunk:chunks){var parts=chunk.split(",");method.invoke(populator,world,Integer.parseInt(parts[0]),Integer.parseInt(parts[1]),region);} - org.mockito.Mockito.verify(region,org.mockito.Mockito.times(3)).setType(org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.eq(org.bukkit.Material.CHEST)); - config.set("sietches.highlands.enabled",false); - org.mockito.Mockito.clearInvocations(region); - method.invoke(populator,world,10,10,region); - org.mockito.Mockito.verifyNoInteractions(region); - assertFalse(config.contains("sietches.spacing")); - } } diff --git a/DuneTerrain/src/test/java/com/example/duneterrain/SietchLayoutTest.java b/DuneTerrain/src/test/java/com/example/duneterrain/SietchLayoutTest.java new file mode 100644 index 00000000..6fd26f42 --- /dev/null +++ b/DuneTerrain/src/test/java/com/example/duneterrain/SietchLayoutTest.java @@ -0,0 +1,91 @@ +package com.example.duneterrain; + +import static org.junit.jupiter.api.Assertions.*; +import com.example.duneterrain.SietchLayout.Tier; +import java.util.*; +import org.junit.jupiter.api.Test; + +class SietchLayoutTest { + static int spacing(Tier t) { return t.spacing; } + + @Test void anchorsAreDeterministicAndChunkCentred() { + for (Tier t : Tier.values()) for (int c = -3; c <= 3; c++) { + var a = SietchLayout.cellAnchor(t, t.spacing, c, -c); + assertEquals(a, SietchLayout.cellAnchor(t, t.spacing, c, -c)); + assertEquals(8, Math.floorMod(a.x(), 16)); assertEquals(8, Math.floorMod(a.z(), 16)); + } + } + + @Test void everyAnchorIsFoundByExactlyItsOwnChunk() { + for (Tier t : Tier.values()) for (int cell = -2; cell <= 2; cell++) { + var a = SietchLayout.cellAnchor(t, t.spacing, cell, 3 - cell); + int cx = Math.floorDiv(a.x(), 16), cz = Math.floorDiv(a.z(), 16); + assertEquals(a, SietchLayout.anchor(t, t.spacing, cx, cz)); + assertNull(SietchLayout.anchor(t, t.spacing, cx + 1, cz)); + assertTrue(SietchLayout.fitsWindow(t, a.x(), a.z(), cx, cz)); + } + } + + @Test void clearRejectsOverlapsAndKeepsLargerTier() { + int checked = 0, rejected = 0; + for (long cx = -40; cx < 40; cx++) for (long cz = -40; cz < 40; cz++) { + var s = SietchLayout.cellAnchor(Tier.SMALL, Tier.SMALL.spacing, cx, cz); + boolean ok = SietchLayout.clear(Tier.SMALL, s, SietchLayoutTest::spacing); + checked++; if (!ok) rejected++; + for (long lx = -2; lx <= 2; lx++) for (long lz = -2; lz <= 2; lz++) { + var l = SietchLayout.cellAnchor(Tier.LARGE, Tier.LARGE.spacing, lx, lz); + long dx = l.x() - s.x(), dz = l.z() - s.z(), lim = Tier.SMALL.half + Tier.LARGE.half + 16; + if (dx * dx + dz * dz < lim * lim) assertFalse(ok); + } + } + assertTrue(checked > rejected); + var l = SietchLayout.cellAnchor(Tier.LARGE, Tier.LARGE.spacing, 0, 0); + assertTrue(SietchLayout.clear(Tier.LARGE, l, SietchLayoutTest::spacing)); + } + + @Test void roomsStayInsideTheFootprint() { + for (Tier t : Tier.values()) for (var r : SietchLayout.rooms(t)) { + for (int v : new int[]{r.x1() - 1, r.x2() + 1, r.z1() - 1, r.z2() + 1}) assertTrue(Math.abs(v) <= t.half, t + " " + r); + assertTrue(r.x1() <= r.x2() && r.z1() <= r.z2()); + } + } + + @Test void smallHasNoPoolMediumAndLargeDo() { + assertNull(SietchLayout.pool(Tier.SMALL)); assertNotNull(SietchLayout.pool(Tier.MEDIUM)); assertNotNull(SietchLayout.pool(Tier.LARGE)); + assertEquals(3, SietchLayout.rooms(Tier.MEDIUM).size() - 1); + assertEquals(1L, SietchLayout.rooms(Tier.LARGE).stream().filter(r -> r.kind().equals("farm")).count()); + } + + @Test void poolIsOrganicInsideTheHallAndDeepestInTheMiddle() { + for (Tier t : new Tier[]{Tier.MEDIUM, Tier.LARGE}) { + var p = SietchLayout.pool(t); var hall = SietchLayout.rooms(t).get(0); + for (long seed = 1; seed <= 50; seed++) { + assertEquals(p.maxDepth(), SietchLayout.poolDepth(seed, p, p.cx(), p.cz())); + Set depths = new TreeSet<>(); int wet = 0; + for (int x = hall.x1(); x <= hall.x2(); x++) for (int z = hall.z1(); z <= hall.z2(); z++) { + int d = SietchLayout.poolDepth(seed, p, x, z); + if (d > 0) { wet++; depths.add(d); assertTrue(d <= p.maxDepth()); } + } + assertTrue(wet > 20); assertTrue(depths.size() >= 3, "stepped shelf"); + for (int x = p.cx() - SietchLayout.reachX(p) - 2; x <= p.cx() + SietchLayout.reachX(p) + 2; x++) + for (int z = p.cz() - SietchLayout.reachZ(p) - 2; z <= p.cz() + SietchLayout.reachZ(p) + 2; z++) + if (SietchLayout.poolDepth(seed, p, x, z) > 0) assertTrue(hall.contains(x, z), "pool inside hall with a rim"); + } + assertNotEquals(poolMask(1, p), poolMask(2, p)); + } + } + + static String poolMask(long seed, SietchLayout.Pool p) { + StringBuilder b = new StringBuilder(); + for (int x = -15; x <= 15; x++) for (int z = -12; z <= 12; z++) b.append(SietchLayout.poolDepth(seed, p, x, z) > 0 ? '1' : '0'); + return b.toString(); + } + + @Test void stairwellFitsInsideTheHall() { + for (Tier t : new Tier[]{Tier.MEDIUM, Tier.LARGE}) { + var h = SietchLayout.rooms(t).get(0); var s = SietchLayout.stairwell(t); + assertTrue(h.contains(s[0] + 1, s[1] + 1) && h.contains(s[0] - 1, s[1] - 1)); + } + assertNull(SietchLayout.stairwell(Tier.SMALL)); + } +} diff --git a/tools/plugin_pillager_abi.py b/tools/plugin_pillager_abi.py index 363d26f9..e37dcb95 100644 --- a/tools/plugin_pillager_abi.py +++ b/tools/plugin_pillager_abi.py @@ -7,7 +7,7 @@ import sys import zipfile sys.path.insert(0,str(Path(__file__).resolve().parent)) from plugin_backend_abi import jar_classes -REVIEWED_TERRAIN_SHA256='b0777941e5c320e16731e447101b4157fb8af917951fc0e3128c4e6b73710b4f' +REVIEWED_TERRAIN_SHA256='d373aa5e0b83c85c8270f099df46bdb6343565434a20976de2f5ffff6ecf6748' def verify_contract(path,fixture,require_hash=False): diff --git a/tools/reset-arrakis-terrain.py b/tools/reset-arrakis-terrain.py index e5ebb82b..86526515 100644 --- a/tools/reset-arrakis-terrain.py +++ b/tools/reset-arrakis-terrain.py @@ -249,6 +249,51 @@ def apply(value, controller, stamp=None): raise +def regenerate_without_backup(value, controller): + if not controller.active(): + raise ValueError('Arrakis must be running before regeneration') + world, dimension, target = map(Path, (value['world'], value['dimension'], value['target'])) + controller.stop() + if controller.active(): + raise RuntimeError('Arrakis service did not stop') + destructive = False + temporary = target.with_suffix('.incoming') + staged_here = False + try: + if digest(target) != value['previousSha256'] or digest(value['incoming']) != value['incomingSha256']: + raise ValueError('Terrain changed after planning') + verify_retained(value) + profiles = protected(world) + chunks = [] + for name in CHUNKS: + for file in sorted(checked(dimension / name).iterdir()): + if not re.fullmatch(r'[rc]\.-?\d+\.-?\d+\.(?:mca|mcc)', file.name) or not checked(file).is_file(): + raise ValueError('Unexpected entry in Arrakis chunk storage') + chunks.append(file) + with temporary.open('xb') as staged: + staged_here = True + with Path(value['incoming']).open('rb') as source: + shutil.copyfileobj(source, staged) + set_metadata(temporary, value['previousMetadata']) + if digest(temporary) != value['incomingSha256']: + raise ValueError('Staged Terrain hash mismatch') + os.replace(temporary, target) + destructive = True + for file in chunks: + file.unlink() + if protected(world) != profiles: + raise ValueError('Protected world/player data changed') + verify_retained(value) + controller.start() + return len(chunks) + except Exception: + if not destructive: + if staged_here: + temporary.unlink(missing_ok=True) + controller.start() + raise + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--root', required=True) @@ -256,8 +301,11 @@ def main(): parser.add_argument('--expected-source', required=True) parser.add_argument('--expected-terrain-sha', default=OLD_TERRAIN_SHA) parser.add_argument('--apply-reset', action='store_true') + parser.add_argument('--no-backup', action='store_true') parser.add_argument('--rollback-receipt') args = parser.parse_args() + if args.no_backup and (not args.apply_reset or args.rollback_receipt): + parser.error('--no-backup requires --apply-reset without rollback') value = None if args.rollback_receipt: value = json.loads(Path(args.rollback_receipt).read_text()) @@ -277,6 +325,9 @@ def main(): if args.rollback_receipt: rollback(args.rollback_receipt, Service(checked(args.root))) print('Receipt-backed Arrakis rollback completed; player metadata retained.') + elif args.no_backup: + removed = regenerate_without_backup(value, Service(checked(args.root))) + print(f'Removed {removed} Arrakis chunk files; awaiting Paper readiness.') else: print('Receipt:', apply(value, Service(checked(args.root))))