From 63bd3e3de8e38ff40016fe74ad39f47656552df6 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 20:45:00 +0200 Subject: [PATCH 1/7] Keep the object scale cache in world state and the structure graph catalog per resource snapshot IrisObjectScale takes the engine and keeps its scaled variants in the world's state store; the structure graph catalog is keyed by the pack's resource snapshot. Both are rebuilt when a resource reload starts a new world or snapshot, so IrisData no longer invalidates them by hand. --- .../structure/StructureGraphCatalog.java | 20 +++-- .../components/FloatingObjectPlacing.java | 12 +-- .../mantle/components/ObjectPlacing.java | 8 +- .../engine/object/prefab/IrisObjectScale.java | 79 +++++-------------- 4 files changed, 40 insertions(+), 79 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java index 42e00e57d..9b6a46333 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java @@ -1,6 +1,7 @@ package art.arcane.iris.engine.framework.structure; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisPackResources; import art.arcane.iris.engine.framework.StructureAssembler; import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; @@ -14,10 +15,14 @@ import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +/** + * Compiled structure graphs, kept per resource snapshot of the pack: every reload of the pack's resources starts a new + * snapshot ({@link IrisData#getPackResources()}), so nothing stale is ever read and nothing is invalidated by hand. + */ public final class StructureGraphCatalog { - private static final Cache> CACHE = + private static final Cache> CACHE = Caffeine.newBuilder().weakKeys().build(); - private static final Cache> RUNTIME_OUTPUT = + private static final Cache> RUNTIME_OUTPUT = Caffeine.newBuilder().weakKeys().build(); private static final List RUNTIME_SAMPLE_SEEDS = List.of( 0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L); @@ -33,17 +38,10 @@ public final class StructureGraphCatalog { return compileAndReport(activeData, activeStructure); } ConcurrentMap catalog = CACHE.get( - activeData, ignored -> new ConcurrentHashMap<>()); + activeData.getPackResources(), ignored -> new ConcurrentHashMap<>()); return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure)); } - public static void invalidate(IrisData data) { - if (data != null) { - CACHE.invalidate(data); - RUNTIME_OUTPUT.invalidate(data); - } - } - public static boolean guaranteesRuntimeOutput(IrisData data, IrisStructure structure) { IrisData activeData = Objects.requireNonNull(data); IrisStructure activeStructure = Objects.requireNonNull(structure); @@ -55,7 +53,7 @@ public final class StructureGraphCatalog { return sampleRuntimeAssembly(activeData, activeStructure); } ConcurrentMap catalog = RUNTIME_OUTPUT.get( - activeData, ignored -> new ConcurrentHashMap<>()); + activeData.getPackResources(), ignored -> new ConcurrentHashMap<>()); return catalog.computeIfAbsent( structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure)); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 249c80a13..d949e55a1 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -184,12 +184,12 @@ public class FloatingObjectPlacing { if (raw == null) { continue; } - IrisObject obj0 = placement.getScale().get(rng, raw); + IrisObject obj0 = placement.getScale().get(rng, raw, engine); if (obj0 == null) { continue; } if (entry != null && entry.hasObjectShrink()) { - obj0 = entry.getShrinkScale().get(rng, obj0); + obj0 = entry.getShrinkScale().get(rng, obj0, engine); if (obj0 == null) { continue; } @@ -232,12 +232,12 @@ public class FloatingObjectPlacing { if (raw == null) { continue; } - IrisObject obj0 = placement.getScale().get(rng, raw); + IrisObject obj0 = placement.getScale().get(rng, raw, engine); if (obj0 == null) { continue; } if (entry != null && entry.hasObjectShrink()) { - obj0 = entry.getShrinkScale().get(rng, obj0); + obj0 = entry.getShrinkScale().get(rng, obj0, engine); if (obj0 == null) { continue; } @@ -317,12 +317,12 @@ public class FloatingObjectPlacing { if (raw == null) { continue; } - IrisObject obj0 = placement.getScale().get(rng, raw); + IrisObject obj0 = placement.getScale().get(rng, raw, engine); if (obj0 == null) { continue; } if (entry != null && entry.hasObjectShrink()) { - obj0 = entry.getShrinkScale().get(rng, obj0); + obj0 = entry.getShrinkScale().get(rng, obj0, engine); if (obj0 == null) { continue; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 8702ababf..7d510ce9a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -663,7 +663,7 @@ public class ObjectPlacing { for (int i = 0; i < density; i++) { attempts++; - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng)); + IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); if (v == null) { nullObjects++; if (traceRegen) { @@ -801,7 +801,7 @@ public class ObjectPlacing { for (int i = 0; i < density; i++) { attempts++; - IrisObject object = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng)); + IrisObject object = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); if (object == null) { nullObjects++; if (traceRegen) { @@ -1034,7 +1034,7 @@ public class ObjectPlacing { int density = objectPlacement.getDensity(rng, minX, minZ, engine.getData()); for (int i = 0; i < density; i++) { - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng)); + IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); if (v == null) { continue; } @@ -1419,7 +1419,7 @@ public class ObjectPlacing { private Set guessPlacedKeys(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) { Set f = new KSet<>(); for (int i = 0; i < objectPlacement.getDensity(rng, x, z, engine.getData()); i++) { - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(engine.getComplex(), rng)); + IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(engine.getComplex(), rng), engine); if (v == null) { continue; } diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java index b49d6de06..be7afb455 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.prefab; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.MaxNumber; import art.arcane.iris.engine.object.annotations.MinNumber; @@ -49,11 +49,6 @@ public class IrisObjectScale { private static final long CACHE_VARIANT_ESTIMATED_BYTES = 256L; private static final long CACHE_ESTIMATED_BYTES_PER_VOXEL = 128L; private static final int CACHE_LOAD_LOCK_COUNT = 256; - private static final ScaleCache CACHE = new ScaleCache(resolveCacheMaximumEstimatedBytes()); - - public static void invalidate(IrisData owner) { - CACHE.invalidate(owner); - } @MinNumber(0.01) @MaxNumber(50) @@ -99,7 +94,8 @@ public class IrisObjectScale { return Math.max(minimumScale, maximumScale); } - public IrisObject get(RNG rng, IrisObject origin) { + /** The scaled variant of {@code origin} this scale picks, built once per world and kept in the world's cache. */ + public IrisObject get(RNG rng, IrisObject origin, Engine engine) { if (origin == null) { return null; } @@ -110,40 +106,33 @@ public class IrisObjectScale { } int variantIndex = request.selectVariant(rng); - CacheKey key = CACHE.key(origin, request, variantIndex); - CacheLookup lookup = CACHE.lookup(key); - if (lookup.variant() != null) { - return lookup.variant(); + ScaleCache cache = cacheOf(engine); + CacheKey key = cache.key(origin, request, variantIndex); + IrisObject cached = cache.lookup(key); + if (cached != null) { + return cached; } - synchronized (CACHE.loadLock(key)) { - CacheLookup afterWait = CACHE.lookup(key); - if (afterWait.variant() != null) { - return afterWait.variant(); + synchronized (cache.loadLock(key)) { + IrisObject afterWait = cache.lookup(key); + if (afterWait != null) { + return afterWait; } IrisObject variant = origin.scaled(request.scaleAt(variantIndex), request.interpolation()); long estimatedBytes = estimateVariant(variant); - return CACHE.putIfCurrent(key, variant, estimatedBytes, lookup.generation()); + return cache.putIfAbsent(key, variant, estimatedBytes); } } + static ScaleCache cacheOf(Engine engine) { + return engine.getGeneration().state(ScaleCache.class, world -> new ScaleCache(resolveCacheMaximumEstimatedBytes())); + } + public boolean canScaleBeyond() { return shouldScale() && getMaxScale() > 1; } - static int cacheEntryCount() { - return CACHE.size(); - } - - static long cacheEstimatedBytes() { - return CACHE.estimatedBytes(); - } - - static boolean isOriginCached(IrisObject origin) { - return CACHE.containsOrigin(origin); - } - private ScaleRequest snapshotRequest() { IrisObjectPlacementScaleInterpolator configuredInterpolation = interpolation == null ? IrisObjectPlacementScaleInterpolator.NONE @@ -217,7 +206,6 @@ public class IrisObjectScale { } static final class CacheKey extends WeakReference { - private final IrisData owner; private final ScaleRequest request; private final int variantIndex; private final int originRevision; @@ -231,22 +219,16 @@ public class IrisObjectScale { CacheKey(IrisObject origin, ScaleRequest request, int variantIndex, ReferenceQueue collectedOrigins) { super(origin, collectedOrigins); - this.owner = origin.getLoader(); this.request = request; this.variantIndex = variantIndex; this.originRevision = originRevision(origin); int result = System.identityHashCode(origin); - result = (31 * result) + System.identityHashCode(owner); result = (31 * result) + originRevision; result = (31 * result) + request.hashCode(); this.loadHashCode = result; this.hashCode = (31 * result) + variantIndex; } - boolean belongsTo(IrisData candidate) { - return owner == candidate; - } - boolean hasOrigin(IrisObject candidate) { return get() == candidate; } @@ -262,7 +244,6 @@ public class IrisObjectScale { IrisObject origin = get(); return origin != null && origin == other.get() - && owner == other.owner && originRevision == other.originRevision && request.equals(other.request) && variantIndex == other.variantIndex; @@ -300,16 +281,12 @@ public class IrisObjectScale { } } - record CacheLookup(IrisObject variant, long generation) { - } - static final class ScaleCache { private final long maximumEstimatedBytes; private final LinkedHashMap entries; private final Object[] loadLocks; private final ReferenceQueue collectedOrigins; private long estimatedBytes; - private long generation; ScaleCache(long maximumEstimatedBytes) { if (maximumEstimatedBytes <= 0L) { @@ -332,20 +309,19 @@ public class IrisObjectScale { return loadLocks[key.loadHashCode() & (loadLocks.length - 1)]; } - synchronized CacheLookup lookup(CacheKey key) { + synchronized IrisObject lookup(CacheKey key) { drainCollectedOrigins(); CacheValue value = entries.get(key); - return new CacheLookup(value == null ? null : value.variant(), generation); + return value == null ? null : value.variant(); } - synchronized IrisObject putIfCurrent(CacheKey key, IrisObject variant, - long entryEstimatedBytes, long expectedGeneration) { + synchronized IrisObject putIfAbsent(CacheKey key, IrisObject variant, long entryEstimatedBytes) { drainCollectedOrigins(); CacheValue present = entries.get(key); if (present != null) { return present.variant(); } - if (generation != expectedGeneration || entryEstimatedBytes > maximumEstimatedBytes) { + if (entryEstimatedBytes > maximumEstimatedBytes) { return variant; } @@ -355,19 +331,6 @@ public class IrisObjectScale { return variant; } - synchronized void invalidate(IrisData owner) { - drainCollectedOrigins(); - generation++; - Iterator> iterator = entries.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry entry = iterator.next(); - if (entry.getKey().belongsTo(owner)) { - estimatedBytes -= entry.getValue().estimatedBytes(); - iterator.remove(); - } - } - } - synchronized int size() { drainCollectedOrigins(); return entries.size(); From 37bc1a0e70c823ce99a94d9f4a32d55086b52c9d Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 20:51:05 +0200 Subject: [PATCH 2/7] ObjectLocating: iris:objects names the biomes and regions that place an object --- .../mantle/components/ObjectLocating.java | 55 +++++++++++++++++++ .../mantle/components/ObjectModule.java | 14 +---- 2 files changed, 58 insertions(+), 11 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java new file mode 100644 index 000000000..2f002ae1e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -0,0 +1,55 @@ +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import com.volmit.service.ObjectsAt; +import com.volmit.world.PackWorld; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * How {@code iris:objects} tells Iris where its objects are: the objects the biome and region of a chunk would place, + * and the biomes and regions whose surface placements name an object. + */ +public final class ObjectLocating implements ObjectsAt { + @Override + public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { + return ObjectModule.placing(engine(world)).guess(chunkX, chunkZ); + } + + @Override + public PlacedBy placedBy(PackWorld world, String objectKey) { + Engine engine = engine(world); + Set biomes = new LinkedHashSet<>(); + for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { + if (biome != null && placesObject(biome.getSurfaceObjects(), objectKey)) { + biomes.add(biome.getLoadKey()); + } + } + + Set regions = new LinkedHashSet<>(); + for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { + if (region != null && placesObject(region.getSurfaceObjects(), objectKey)) { + regions.add(region.getLoadKey()); + } + } + return new PlacedBy(biomes, regions); + } + + private static boolean placesObject(List placements, String objectKey) { + for (IrisObjectPlacement placement : placements) { + if (placement != null && placement.getPlace().contains(objectKey)) { + return true; + } + } + return false; + } + + private static Engine engine(PackWorld world) { + return IrisPackWorld.of(world).engine(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 6e7b4fd5e..c39b696bf 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -21,7 +21,6 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; -import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; @@ -30,15 +29,13 @@ import com.volmit.config.PackSettings; import com.volmit.service.ObjectsAt; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; -import com.volmit.world.PackWorld; - -import java.util.Set; /** * Module {@code iris:objects}: the objects the dimension's regions and biomes place, written into the mantle * once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work * done by {@link ObjectPlacing}, one per engine runtime. Its reach is the pack's largest object placement. It tells - * Iris which objects a chunk would get ({@link ObjectsAt}), for the object search and studio tools. + * Iris which objects a chunk would get and which biomes and regions place an object ({@link ObjectLocating}), for the + * object search and studio tools. */ public final class ObjectModule implements IrisModule { private static final String VERSION = "built-in"; @@ -55,7 +52,7 @@ public final class ObjectModule implements IrisModule { @Override public void register(FeatureRegistry registry) { - registry.registerService(ObjectsAt.class, ObjectModule::objectsAt); + registry.registerService(ObjectsAt.class, new ObjectLocating()); } private static void place(MantleStageContext context) { @@ -67,11 +64,6 @@ public final class ObjectModule implements IrisModule { return placing(IrisPackSettings.of(settings).engine()).reach(); } - /** The keys of the objects the surface placements of the chunk's biome and region would place, guessed without generating it. */ - private static Set objectsAt(PackWorld world, int chunkX, int chunkZ) { - return placing(IrisPackWorld.of(world).engine()).guess(chunkX, chunkZ); - } - /** The engine runtime's object placing, which the module's {@link ObjectsAt} also asks. */ public static ObjectPlacing placing(Engine engine) { return engine.getGeneration().state(ObjectPlacing.class, ObjectPlacing::new); From a1af4a85ff838c946ef078e84d523498386d40c4 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:02:47 +0200 Subject: [PATCH 3/7] iris:loot: Loot and BlockDrops providers, loot table resolution and item drawing moved out of core --- source-patterns.txt | 1 + .../iris/engine/loot/BlockDropping.java | 66 +++++++ .../arcane/iris/engine/loot/LootGiving.java | 114 ++++++++++++ .../arcane/iris/engine/loot/LootItems.java | 151 ++++++++++++++++ .../arcane/iris/engine/loot/LootModule.java | 50 ++++++ .../arcane/iris/engine/loot/LootTables.java | 162 ++++++++++++++++++ .../mantle/components/ObjectLocating.java | 18 ++ .../engine/object/loot/IrisBlockDrops.java | 37 ++-- .../iris/engine/object/loot/IrisLoot.java | 2 +- .../engine/object/loot/IrisLootTable.java | 2 +- .../object/loot/IrisVanillaLootTable.java | 2 +- 11 files changed, 590 insertions(+), 15 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/loot/BlockDropping.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootGiving.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootItems.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootModule.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootTables.java diff --git a/source-patterns.txt b/source-patterns.txt index b09f3c28b..f4f3d130d 100644 --- a/source-patterns.txt +++ b/source-patterns.txt @@ -16,3 +16,4 @@ art/arcane/iris/engine/framework/StructureVerticalBounds.java art/arcane/iris/engine/framework/PlacedObject.java art/arcane/iris/engine/framework/PlacedStructurePiece.java art/arcane/iris/builtin/** +art/arcane/iris/engine/loot/** diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java new file mode 100644 index 000000000..e1ff26a61 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -0,0 +1,66 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.loot.IrisBlockDrops; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.item.ItemDrop; +import com.volmit.service.BlockDrops; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.List; + +/** + * How {@code iris:loot} drops items for broken blocks: the block drops of the biome, the region and the dimension, the + * biome's first and the biome able to keep the others from dropping. + */ +public final class BlockDropping implements BlockDrops { + @Override + public Result drops(PackWorld world, Broken broken) { + Engine engine = IrisPackWorld.of(world).engine(); + int x = broken.position().x(); + int y = broken.position().y(); + int z = broken.position().z(); + PlatformBlockState block = IrisPlatforms.get().registries().block(broken.block().key()); + + IrisBiome biome = engine.getBiome(x, y, z); + List providers = dropsFor(biome.getBlockDrops(), block, engine); + if (providers.stream().noneMatch(IrisBlockDrops::isSkipParents)) { + IrisRegion region = engine.getRegion(x, z); + providers.addAll(dropsFor(region.getBlockDrops(), block, engine)); + providers.addAll(dropsFor(engine.getDimension().getBlockDrops(), block, engine)); + } + + LootItems items = new LootItems(world.resources().items(), false); + List drops = new ArrayList<>(); + providers.forEach(provider -> provider.fillDrops(items, drops)); + return new Result(drops, providers.stream().anyMatch(IrisBlockDrops::isReplaceVanillaDrops)); + } + + private static List dropsFor(KList candidates, PlatformBlockState block, Engine engine) { + return new KList<>(candidates.stream().filter(drops -> drops.shouldDropFor(block, engine.getData())).toList()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java new file mode 100644 index 000000000..f747148a8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -0,0 +1,114 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.framework.PlacedObject; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.engine.object.loot.IrisVanillaLootTable; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.item.ItemDrop; +import com.volmit.service.Loot; +import com.volmit.world.PackWorld; + +import java.util.List; + +/** + * How {@code iris:loot} fills containers: the tables of the object placed around a container, then those of the + * dimension, region and biomes at its column, and the items each table gives. Draws are deterministic per container, so + * a container always holds the same loot. + */ +public final class LootGiving implements Loot { + @Override + public List tables(PackWorld world, Site site) { + Engine engine = engine(world); + int x = site.position().x(); + int z = site.position().z(); + int relativeY = site.position().y(); + RNG rng = LootResolver.containerRng(lootSeed(engine), x, relativeY + engine.getMinHeight(), z); + + List tables = new KList<>(); + boolean objectLootDefined = site.nativeLootDefined(); + IrisObjectPlacement placement = site.container() == null ? null : placementAt(engine, x, relativeY, z); + if (placement != null) { + objectLootDefined = objectLootDefined || placement.getLoot().isNotEmpty() || placement.getVanillaLoot().isNotEmpty(); + IrisLootTable table = placement.getTable(platformState(site), engine.getData(), rng); + if (table != null) { + tables.add(table); + if (placement.isOverrideGlobalLoot()) { + return sourcesOf(engine, site, List.of(table)); + } + } + } + + LootTables.resolveEnvironmentSources(tables, engine, rng, x, relativeY, z, objectLootDefined, table -> table); + return sourcesOf(engine, site, tables); + } + + @Override + public List items(PackWorld world, Site site, String key) { + Engine engine = engine(world); + IrisLootTable table = engine.getData().getLootLoader().load(key); + if (table == null) { + return List.of(); + } + int worldY = site.position().y() + engine.getMinHeight(); + return new LootItems(world.resources().items(), site.debug()) + .draw(table, lootSeed(engine), site.position().x(), worldY, site.position().z()); + } + + private static IrisObjectPlacement placementAt(Engine engine, int x, int relativeY, int z) { + PlacedObject placed = engine.getObjectPlacement(x, relativeY, z); + return placed == null ? null : placed.getPlacement(); + } + + private static List sourcesOf(Engine engine, Site site, List tables) { + int worldY = site.position().y() + engine.getMinHeight(); + List sources = new KList<>(); + for (IrisLootTable table : tables) { + if (table instanceof IrisVanillaLootTable vanilla) { + long seed = LootTables.seed(lootSeed(engine), vanilla, site.position().x(), worldY, site.position().z()); + sources.add(new PlatformTable(vanilla.getLootTableKey(), seed)); + continue; + } + if (table != null && table.getLoadKey() != null) { + sources.add(new Table(table.getLoadKey())); + } + } + return sources; + } + + private static PlatformBlockState platformState(Site site) { + return IrisPlatforms.get().registries().block(site.container().key()); + } + + private static long lootSeed(Engine engine) { + return engine.getSeedManager().getLoot(); + } + + private static Engine engine(PackWorld world) { + return IrisPackWorld.of(world).engine(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/LootItems.java b/src/main/java/art/arcane/iris/engine/loot/LootItems.java new file mode 100644 index 000000000..d1b3247d5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootItems.java @@ -0,0 +1,151 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.object.entity.IrisAttributeModifier; +import art.arcane.iris.engine.object.loot.IrisEnchantment; +import art.arcane.iris.engine.object.loot.InventorySlotType; +import art.arcane.iris.engine.object.loot.IrisLoot; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.item.ItemAttribute; +import com.volmit.item.ItemDrop; +import com.volmit.item.ItemEnchantment; +import com.volmit.item.ItemRegistry; + +import java.util.ArrayList; +import java.util.List; +import java.util.OptionalInt; + +/** + * Turns loot entries into the items they give: every random choice is made here, in the order Iris always made them + * (amount, enchantments, attribute modifiers, damage), so that a container's loot stays what it was. What the platform + * must do with the result is the host's. + */ +public final class LootItems { + private static final String AIR = "air"; + private static final String MINECRAFT_PREFIX = "minecraft:"; + private static final int MIN_AMOUNT = 1; + + private final ItemRegistry items; + private final boolean debug; + + /** @param debug whether the items say where they came from */ + public LootItems(ItemRegistry items, boolean debug) { + this.items = items; + this.debug = debug; + } + + /** + * The items {@code table} gives at the spot {@code x}, {@code y}, {@code z} (world coordinates): picks entries + * from the table's own random stream until it has the number of items the table asks for or runs out of tries. + */ + public List draw(IrisLootTable table, long lootSeed, int x, int y, int z) { + List drops = new ArrayList<>(); + List entries = table.getLoot(); + if (entries.isEmpty() || table.getMaxTries() <= 0) { + return drops; + } + + RNG rng = LootTables.rng(lootSeed, table, x, y, z); + int wanted = Math.max(0, LootResolver.inclusive(rng, table.getMinPicked(), table.getMaxPicked())); + int tries = 0; + while (drops.size() < wanted && tries++ < table.getMaxTries()) { + int index = rng.nextInt(entries.size()); + IrisLoot entry = entries.get(index); + if (entry == null || entry.getSlotTypes() != InventorySlotType.STORAGE) { + continue; + } + ItemDrop drop = drawEntry(entry, table, rng, lootSeed, index, x, y, z); + if (drop != null) { + drops.add(drop); + } + } + return drops; + } + + /** The item {@code entry} gives when nothing else decides whether it does, such as a block's drop or a mob's equipment; null for no item. */ + public ItemDrop give(IrisLoot entry, RNG rng) { + return resolve(entry, rng, null); + } + + private ItemDrop drawEntry(IrisLoot entry, IrisLootTable table, RNG rng, long lootSeed, int index, int x, int y, int z) { + long combinedRarity = LootResolver.combinedRarity(entry.getRarity(), table.getRarity()); + if (!LootTables.spatialOneIn(lootSeed, table, index, x, y, z, combinedRarity)) { + return null; + } + return resolve(entry, rng, table); + } + + private ItemDrop resolve(IrisLoot entry, RNG rng, IrisLootTable table) { + String type = entry.getTypeKey(); + OptionalInt maxDurability = items.maxDurability(type); + if (maxDurability.isEmpty() || isAir(type)) { + return null; + } + + int amount = Math.max(MIN_AMOUNT, LootResolver.inclusive(rng, entry.getMinAmount(), entry.getMaxAmount())); + List enchantments = drawEnchantments(entry, rng); + List attributes = drawAttributes(entry, rng); + Double damage = maxDurability.getAsInt() > 0 ? 1D - rng.d(entry.getMinDurability(), entry.getMaxDurability()) : null; + return new ItemDrop(type, amount, entry.getDisplayName(), entry.getLore(), enchantments, attributes, + entry.isUnbreakable(), entry.getItemFlags(), entry.getCustomModel(), damage, entry.getLeatherColor(), + entry.getDyeColorKey(), entry.getCustomNbt(), debug ? sourceOf(entry, table) : null); + } + + private static List drawEnchantments(IrisLoot entry, RNG rng) { + List enchantments = new ArrayList<>(); + for (IrisEnchantment enchantment : entry.getEnchantments()) { + String key = enchantment.getEnchantment(); + if (key == null || key.isBlank() || rng.nextDouble() >= enchantment.getChance()) { + continue; + } + enchantments.add(new ItemEnchantment(key, Math.max(1, enchantment.getLevel(rng)))); + } + return enchantments; + } + + private static List drawAttributes(IrisLoot entry, RNG rng) { + List attributes = new ArrayList<>(); + for (IrisAttributeModifier modifier : entry.getAttributes()) { + if (rng.nextDouble() >= modifier.getChance()) { + continue; + } + String attribute = modifier.getAttribute(); + if (attribute == null || attribute.isBlank()) { + continue; + } + attributes.add(new ItemAttribute(attribute, modifier.getName(), modifier.getOperation(), modifier.getAmount(rng))); + } + return attributes; + } + + private static ItemDrop.Source sourceOf(IrisLoot entry, IrisLootTable table) { + if (table == null) { + return new ItemDrop.Source(null, 0, entry.getRarity()); + } + return new ItemDrop.Source(table.getName(), table.getRarity(), entry.getRarity()); + } + + private static boolean isAir(String type) { + String key = type.startsWith(MINECRAFT_PREFIX) ? type.substring(MINECRAFT_PREFIX.length()) : type; + return AIR.equalsIgnoreCase(key); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/src/main/java/art/arcane/iris/engine/loot/LootModule.java new file mode 100644 index 000000000..ff32bc104 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -0,0 +1,50 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import com.volmit.FeatureRegistry; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.service.BlockDrops; +import com.volmit.service.Loot; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:loot}: the loot tables of the pack and the items they and the block drops of the dimension, regions + * and biomes give. It has no generation stage; Iris asks it through {@link Loot} when a container is filled and through + * {@link BlockDrops} when a player breaks a block. + */ +public final class LootModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:loot", "Loot", VERSION); + } + + @Override + public void install(StageGraph graph) { + } + + @Override + public void register(FeatureRegistry registry) { + registry.registerService(Loot.class, new LootGiving()); + registry.registerService(BlockDrops.class, new BlockDropping()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/LootTables.java b/src/main/java/art/arcane/iris/engine/loot/LootTables.java new file mode 100644 index 000000000..021c3c2b1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootTables.java @@ -0,0 +1,162 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.object.loot.IrisLootMode; +import art.arcane.iris.engine.object.loot.IrisLootReference; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; + +import java.util.List; +import java.util.Objects; +import java.util.function.Function; + +/** + * Which loot tables a place in the world draws from, and the random streams that draw from them: the part of loot + * that reads the pack's tables, loot references and layout. The streams themselves are + * {@link LootResolver}'s; here a table is named by its {@linkplain #identity identity}. + */ +public final class LootTables { + private LootTables() { + } + + /** What names a table in the random streams: its key, else its name. */ + public static String identity(IrisLootTable table) { + if (table == null) { + return ""; + } + String loadKey = table.getLoadKey(); + if (loadKey != null && !loadKey.isBlank()) { + return loadKey; + } + String name = table.getName(); + return name == null ? "" : name; + } + + public static RNG rng(long lootSeed, IrisLootTable table, int x, int y, int z) { + return LootResolver.tableRng(lootSeed, identity(table), x, y, z); + } + + public static long seed(long lootSeed, IrisLootTable table, int x, int y, int z) { + return LootResolver.tableSeed(lootSeed, identity(table), x, y, z); + } + + public static boolean spatialOneIn(long lootSeed, IrisLootTable table, int entryIndex, int x, int y, int z, long rarity) { + return LootResolver.spatialOneIn(lootSeed, identity(table), entryIndex, x, y, z, rarity); + } + + /** + * Adds the tables of the dimension, the region, the surface biome and (below the surface) the cave biome at a + * column to {@code sources}, as their loot references say, then scales their number by the areas' multipliers. + * {@code mapper} turns a table into the caller's own source; a null result skips it. + */ + public static void resolveEnvironmentSources( + List sources, + Engine engine, + RNG rng, + int x, + int relativeY, + int z, + boolean objectLootDefined, + Function mapper + ) { + IrisRegion region = engine.getComplex().getRegionStream().get(x, z); + IrisBiome surfaceBiome = engine.getComplex().getTrueBiomeStream().get(x, z); + double terrainHeight = engine.getComplex().getHeightStream().get(x, z); + IrisBiome contextualBiome = relativeY < terrainHeight + ? engine.getCaveBiome(x, relativeY, z) + : surfaceBiome; + if (contextualBiome == null) { + contextualBiome = surfaceBiome; + } + + boolean distinctContextualBiome = !sameBiome(surfaceBiome, contextualBiome); + double multiplier = engine.getDimension().getLoot().getMultiplier() + * region.getLoot().getMultiplier() + * surfaceBiome.getLoot().getMultiplier(); + if (distinctContextualBiome) { + multiplier *= contextualBiome.getLoot().getMultiplier(); + } + + boolean fallback = !objectLootDefined; + injectReference(sources, engine.getDimension().getLoot(), engine, mapper, fallback); + injectReference(sources, region.getLoot(), engine, mapper, fallback); + injectReference(sources, surfaceBiome.getLoot(), engine, mapper, fallback); + if (distinctContextualBiome) { + injectReference(sources, contextualBiome.getLoot(), engine, mapper, fallback); + } + LootResolver.scaleSources(sources, multiplier, rng); + } + + /** Adds {@code additions} to {@code sources} the way {@code mode} says; {@code fallback} is whether nothing else defined a table. */ + public static void injectSources( + List sources, + List additions, + IrisLootMode mode, + boolean fallback + ) { + if (mode == IrisLootMode.FALLBACK && !fallback) { + return; + } + if (mode == IrisLootMode.CLEAR) { + sources.clear(); + return; + } + if (mode == IrisLootMode.REPLACE) { + sources.clear(); + } + sources.addAll(additions); + } + + static boolean sameBiome(IrisBiome first, IrisBiome second) { + if (first == second) { + return true; + } + if (first == null || second == null) { + return false; + } + return Objects.equals(first.getLoadKey(), second.getLoadKey()); + } + + private static void injectReference( + List sources, + IrisLootReference reference, + Engine engine, + Function mapper, + boolean fallback + ) { + KList tables = reference.getLootTables(engine.getComplex()); + KList additions = new KList<>(); + for (IrisLootTable table : tables) { + if (table == null) { + continue; + } + T source = mapper.apply(table); + if (source != null) { + additions.add(source); + } + } + injectSources(sources, additions, reference.getMode(), fallback); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java index 2f002ae1e..b022b03f3 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -1,3 +1,21 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + package art.arcane.iris.engine.mantle.components; import art.arcane.iris.core.modules.IrisPackWorld; diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java index fa2aa2f57..c3c26608c 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java @@ -22,6 +22,7 @@ import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.loot.LootItems; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.Required; @@ -33,8 +34,9 @@ import lombok.Data; import lombok.NoArgsConstructor; import art.arcane.iris.spi.PlatformBlockState; import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; +import com.volmit.item.ItemDrop; + +import java.util.List; @Snippet("block-drops") @Accessors(chain = true) @@ -43,7 +45,7 @@ import org.bukkit.inventory.ItemStack; @Desc("Represents a block drop list") @Data public class IrisBlockDrops { - private final transient AtomicCache> data = new AtomicCache<>(); + private final transient AtomicCache> data = new AtomicCache<>(); @Required @ArrayType(min = 1, type = IrisBlockData.class) @Desc("The blocks that drop loot") @@ -58,23 +60,23 @@ public class IrisBlockDrops { @Desc("Removes the default vanilla block drops and only drops the given items & any parent loot tables specified for this block type.") private boolean replaceVanillaDrops = false; - public boolean shouldDropFor(BlockData data, IrisData rdata) { - KList list = this.data.aquire(() -> { - KList b = new KList<>(); + public boolean shouldDropFor(PlatformBlockState broken, IrisData rdata) { + KList list = this.data.aquire(() -> { + KList b = new KList<>(); for (IrisBlockData i : getBlocks()) { PlatformBlockState state = i.getBlockData(rdata); if (state != null) { - b.add((BlockData) state.nativeHandle()); + b.add(state); } } return b.removeDuplicates(); }); - for (BlockData i : list) { - if (exactBlocks ? i.equals(data) : i.getMaterial().equals(data.getMaterial())) { + for (PlatformBlockState i : list) { + if (exactBlocks ? i.key().equals(broken.key()) : materialOf(i).equals(materialOf(broken))) { return true; } } @@ -82,11 +84,22 @@ public class IrisBlockDrops { return false; } - public void fillDrops(boolean debug, KList d) { + /** Adds the items of the drops that pass their rarity to {@code d}. */ + public void fillDrops(LootItems items, List d) { for (IrisLoot i : getDrops()) { - if (LootResolver.oneIn(RNG.r, i.getRarity())) { - d.add(i.get(debug, RNG.r)); + if (!LootResolver.oneIn(RNG.r, i.getRarity())) { + continue; + } + ItemDrop drop = items.give(i, RNG.r); + if (drop != null) { + d.add(drop); } } } + + private static String materialOf(PlatformBlockState state) { + String key = state.key(); + int properties = key.indexOf('['); + return properties < 0 ? key : key.substring(0, properties); + } } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java index 8ad144f9c..30251684e 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java @@ -184,7 +184,7 @@ public class IrisLoot { public ItemStack get(boolean debug, IrisLootTable table, RNG rng, long lootSeed, int entryIndex, int x, int y, int z) { long combinedRarity = LootResolver.combinedRarity(rarity, table.getRarity()); - if (!LootResolver.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) { + if (!art.arcane.iris.engine.loot.LootTables.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) { return null; } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java index ba9342ca5..9b85aac40 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java @@ -80,7 +80,7 @@ public class IrisLootTable extends IrisRegistrant { return lootf; } - RNG rng = LootResolver.tableRng(lootSeed, this, x, y, z); + RNG rng = art.arcane.iris.engine.loot.LootTables.rng(lootSeed, this, x, y, z); int m = 0; int c = 0; int mx = Math.max(0, LootResolver.inclusive(rng, getMinPicked(), getMaxPicked())); diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java index c66c624f1..e61521405 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java @@ -78,7 +78,7 @@ public class IrisVanillaLootTable extends IrisLootTable { IrisLogging.warn("Unknown vanilla loot table " + lootTableKey); return new KList<>(); } - RNG rng = LootResolver.tableRng(lootSeed, this, x, y, z); + RNG rng = art.arcane.iris.engine.loot.LootTables.rng(lootSeed, this, x, y, z); return new KList<>(table.populateLoot(rng, new LootContext.Builder(new Location(world, x, y, z)).build())); } From e94d8e00f7867a63dfbb38254f69ee1d4ae37b50 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:05:41 +0200 Subject: [PATCH 4/7] iris:objects grows saplings into trees and names the objects it places as trees (TreeGrowing) --- .../mantle/components/ObjectModule.java | 4 +- .../engine/mantle/components/TreeGrowing.java | 249 ++++++++++++++++++ 2 files changed, 252 insertions(+), 1 deletion(-) create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index c39b696bf..99796dc12 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -27,6 +27,7 @@ import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.config.PackSettings; import com.volmit.service.ObjectsAt; +import com.volmit.service.SaplingGrowth; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; @@ -35,7 +36,7 @@ import com.volmit.stage.StageGraph; * once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work * done by {@link ObjectPlacing}, one per engine runtime. Its reach is the pack's largest object placement. It tells * Iris which objects a chunk would get and which biomes and regions place an object ({@link ObjectLocating}), for the - * object search and studio tools. + * object search and studio tools, and grows the trees of saplings ({@link TreeGrowing}). */ public final class ObjectModule implements IrisModule { private static final String VERSION = "built-in"; @@ -53,6 +54,7 @@ public final class ObjectModule implements IrisModule { @Override public void register(FeatureRegistry registry) { registry.registerService(ObjectsAt.class, new ObjectLocating()); + registry.registerService(SaplingGrowth.class, new TreeGrowing()); } private static void place(MantleStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java new file mode 100644 index 000000000..1bcfe3226 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -0,0 +1,249 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.placement.IObjectPlacer; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisTreeSize; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeModes; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.placement.PlacedBlock; +import com.volmit.service.SaplingGrowth; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import org.bukkit.TreeType; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * How {@code iris:objects} grows trees: when a sapling grows, the tree comes from the tree placements of the biome and + * region at the sapling (the region's too when the dimension uses all of them), placed like any object but into a list + * of blocks the host then places. The same placements tell which objects are trees. + */ +public final class TreeGrowing implements SaplingGrowth { + private static final IrisTreeSize SAPLING_SIZE = new IrisTreeSize(1, 1); + + @Override + public Optional grow(PackWorld world, Sapling sapling, Surroundings surroundings) { + Engine engine = IrisPackWorld.of(world).engine(); + if (!engine.getDimension().getTreeSettings().isEnabled()) { + return Optional.empty(); + } + + IrisObjectPlacement placement = pickPlacement(engine, sapling); + if (placement == null) { + return Optional.empty(); + } + + IrisData data = engine.getData(); + IrisObject object = data.getObjectLoader().load(placement.getPlace().getRandom(RNG.r)); + GrowthPlacer placer = new GrowthPlacer(engine, surroundings); + BlockPosition center = sapling.center(); + object.place(center.x(), center.y() + object.getH() / 2, center.z(), placer, placement, RNG.r, data); + return Optional.of(new Growth(object.getLoadKey(), placer.placed())); + } + + @Override + public TreeObjects treeObjects(PackWorld world) { + Engine engine = IrisPackWorld.of(world).engine(); + Set objects = new HashSet<>(); + Set procedural = new HashSet<>(); + + for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { + if (region != null) { + collectPlacements(region.getObjects(), objects); + collectProceduralTrees(region.getProceduralObjects(), procedural); + } + } + for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { + if (biome != null) { + collectPlacements(biome.getObjects(), objects); + collectProceduralTrees(biome.getProceduralObjects(), procedural); + } + } + return new TreeObjects(objects, procedural); + } + + /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species; null for none. */ + private static IrisObjectPlacement pickPlacement(Engine engine, Sapling sapling) { + TreeType species = TreeType.valueOf(sapling.species()); + KList placements = new KList<>(); + boolean useAll = engine.getDimension().getTreeSettings().getMode().equals(IrisTreeModes.ALL); + + BlockPosition at = sapling.at(); + placements.addAll(matching(engine.getBiome(at.x(), at.y(), at.z()).getObjects(), species)); + if (useAll || placements.isEmpty()) { + placements.addAll(matching(engine.getRegion(at.x(), at.z()).getObjects(), species)); + } + return placements.isNotEmpty() ? placements.getRandom() : null; + } + + private static KList matching(KList objects, TreeType species) { + KList matches = new KList<>(); + for (IrisObjectPlacement placement : objects) { + if (placement.matches(SAPLING_SIZE, species)) { + matches.add(placement); + } + } + return matches; + } + + private static void collectPlacements(Iterable placements, Set objectKeys) { + if (placements == null) { + return; + } + for (IrisObjectPlacement placement : placements) { + if (placement == null + || placement.getTrees() == null + || placement.getTrees().isEmpty() + || placement.getPlace() == null) { + continue; + } + for (String objectKey : placement.getPlace()) { + if (objectKey != null && !objectKey.isBlank()) { + objectKeys.add(objectKey); + } + } + } + } + + private static void collectProceduralTrees(IrisProceduralObjects proceduralObjects, Set objectKeys) { + if (proceduralObjects == null || proceduralObjects.getTrees() == null) { + return; + } + for (IrisProceduralTree tree : proceduralObjects.getTrees()) { + if (tree == null || tree.getName() == null || tree.getName().isBlank()) { + continue; + } + int variants = Math.max(1, tree.getVariants()); + for (int index = 0; index < variants; index++) { + objectKeys.add(tree.getVariantLoadKey(index)); + } + } + } + + /** Places an object into a list of blocks, reading the world around the sapling through the host. */ + private static final class GrowthPlacer implements IObjectPlacer { + private final Engine engine; + private final Surroundings surroundings; + private final PlatformBlockStates states = new PlatformBlockStates(key -> IrisPlatforms.get().registries().block(key)); + private final List placed = new ArrayList<>(); + + private GrowthPlacer(Engine engine, Surroundings surroundings) { + this.engine = engine; + this.surroundings = surroundings; + } + + private List placed() { + return placed; + } + + @Override + public int getHighest(int x, int z, IrisData data) { + return surroundings.highest(x, z, false); + } + + @Override + public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { + return surroundings.highest(x, z, ignoreFluid); + } + + @Override + public void set(int x, int y, int z, PlatformBlockState state) { + placed.add(new PlacedBlock(new BlockPosition(x, y, z), states.toApi(state), Optional.empty())); + } + + @Override + public PlatformBlockState get(int x, int y, int z) { + BlockState block = surroundings.blockAt(x, y, z); + return states.toPlatform(block); + } + + @Override + public boolean isPreventingDecay() { + return true; + } + + @Override + public boolean isCarved(int x, int y, int z) { + return false; + } + + @Override + public boolean isSurfaceSolid(int x, int y, int z) { + return isSolid(x, y, z); + } + + @Override + public boolean isSolid(int x, int y, int z) { + return get(x, y, z).isSolid(); + } + + @Override + public boolean isUnderwater(int x, int z) { + return false; + } + + @Override + public int getFluidHeight() { + return engine.getDimension().getFluidHeight(); + } + + @Override + public boolean isDebugSmartBore() { + return false; + } + + @Override + public void setTile(int xx, int yy, int zz, TileData tile) { + } + + @Override + public void setData(int xx, int yy, int zz, T data) { + } + + @Override + public T getData(int xx, int yy, int zz, Class t) { + return null; + } + + @Override + public Engine getEngine() { + return engine; + } + } +} From 910eab1f7992c8c0413a688deedac388a37eb9ad Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:16:35 +0200 Subject: [PATCH 5/7] iris:spawn: EntitySpawns provider; entity, item and attribute Bukkit behaviour moved out of the model classes --- source-patterns.txt | 1 + .../object/entity/IrisAttributeModifier.java | 88 ---- .../iris/engine/object/entity/IrisEffect.java | 35 -- .../iris/engine/object/entity/IrisEntity.java | 395 ------------------ .../engine/object/entity/IrisEntitySpawn.java | 173 -------- .../object/entity/spawn/IrisSurface.java | 28 -- .../engine/object/loot/IrisEnchantment.java | 40 -- .../iris/engine/object/loot/IrisLoot.java | 188 +-------- .../engine/object/loot/IrisLootTable.java | 34 -- .../object/loot/IrisVanillaLootTable.java | 44 +- .../engine/object/marker/IrisCommand.java | 18 +- .../iris/engine/spawn/EntityResolution.java | 128 ++++++ .../iris/engine/spawn/EntitySpawning.java | 269 ++++++++++++ .../arcane/iris/engine/spawn/SpawnModule.java | 48 +++ 14 files changed, 453 insertions(+), 1036 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java create mode 100644 src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java create mode 100644 src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java diff --git a/source-patterns.txt b/source-patterns.txt index f4f3d130d..31bac204e 100644 --- a/source-patterns.txt +++ b/source-patterns.txt @@ -17,3 +17,4 @@ art/arcane/iris/engine/framework/PlacedObject.java art/arcane/iris/engine/framework/PlacedStructurePiece.java art/arcane/iris/builtin/** art/arcane/iris/engine/loot/** +art/arcane/iris/engine/spawn/** diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java index fe7b4fe91..52e4d068c 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java @@ -23,25 +23,12 @@ import art.arcane.iris.engine.object.annotations.MaxNumber; import art.arcane.iris.engine.object.annotations.MinNumber; import art.arcane.iris.engine.object.annotations.Required; import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.math.RNG; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import org.bukkit.NamespacedKey; -import org.bukkit.Registry; -import org.bukkit.attribute.Attributable; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeModifier; -import org.bukkit.attribute.AttributeModifier.Operation; -import org.bukkit.inventory.EquipmentSlotGroup; -import org.bukkit.inventory.meta.ItemMeta; -import java.util.Locale; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; @Snippet("attribute-modifier") @Accessors(chain = true) @@ -50,8 +37,6 @@ import java.util.concurrent.ConcurrentHashMap; @Desc("Represents an attribute modifier for an item or an entity. This allows you to create modifications to basic game attributes such as MAX_HEALTH or ARMOR_VALUE.") @Data public class IrisAttributeModifier { - private static final Set WARNED_ATTRIBUTES = ConcurrentHashMap.newKeySet(); - @Required @Desc("The Attribute type key such as max_health or minecraft:armor. This type is pulled from the game attributes. Zombie & Horse attributes will not work on non-zombie/horse entities.\nUsing an attribute on an item will have affects when held, or worn. There is no way to specify further granularity as the game picks this depending on the item type.") private String attribute = null; @@ -75,80 +60,7 @@ public class IrisAttributeModifier { @Desc("The chance that this attribute is applied (0 to 1). If the chance is 0.5 (50%), then Iris will only apply this attribute 50% of the time.") private double chance = 1; - public void apply(RNG rng, ItemMeta meta) { - if (rng.nextDouble() < getChance()) { - Attribute resolved = resolveAttribute(); - if (resolved == null) { - return; - } - meta.addAttributeModifier(resolved, createModifier(rng)); - } - } - - public void apply(RNG rng, Attributable meta) { - if (rng.nextDouble() < getChance()) { - Attribute resolved = resolveAttribute(); - if (resolved == null) { - return; - } - meta.getAttribute(resolved).addModifier(createModifier(rng)); - } - } - public double getAmount(RNG rng) { return rng.d(getMinAmount(), getMaxAmount()); } - - private Attribute resolveAttribute() { - if (attribute == null || attribute.isBlank()) { - return null; - } - String value = attribute.trim().toLowerCase(Locale.ROOT); - Attribute resolved; - if (value.contains(":")) { - NamespacedKey key = NamespacedKey.fromString(value); - resolved = key == null ? null : Registry.ATTRIBUTE.get(key); - } else { - resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value)); - if (resolved == null && value.startsWith("generic_")) { - resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring("generic_".length()))); - } - if (resolved == null && value.startsWith("generic.")) { - resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring("generic.".length()))); - } - } - if (resolved == null && WARNED_ATTRIBUTES.add(value)) { - IrisLogging.warn("Unknown attribute '" + attribute + "' in attribute-modifier '" + name + "'"); - } - return resolved; - } - - private Operation resolveOperation() { - if (operation == null || operation.isBlank()) { - return Operation.ADD_NUMBER; - } - try { - return Operation.valueOf(operation.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException e) { - return Operation.ADD_NUMBER; - } - } - - private AttributeModifier createModifier(RNG rng) { - NamespacedKey key = NamespacedKey.minecraft(generateModifierKey()); - return new AttributeModifier(key, getAmount(rng), resolveOperation(), EquipmentSlotGroup.ANY); - } - - private String generateModifierKey() { - String source = getName() == null ? "modifier" : getName(); - String normalized = source.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9/._-]", "_"); - if (normalized.isBlank()) { - normalized = "modifier"; - } - if (normalized.length() > 32) { - normalized = normalized.substring(0, 32); - } - String random = UUID.randomUUID().toString().replace("-", ""); - return normalized + "_" + random; - } } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java index 93e9baa77..b07f836ad 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java @@ -285,39 +285,4 @@ public class IrisEffect { } }); } - - public void apply(Entity p) { - if (!shouldApplyNow()) { - return; - } - - J.runEntity(p, () -> { - Sound soundType = getSound(); - Particle particleType = getParticleEffect(); - if (soundType != null) { - Location part = p.getLocation().clone().add(RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance)); - p.getWorld().playSound(part, soundType, (float) volume, (float) RNG.r.d(minPitch, maxPitch)); - } - - if (particleType != null) { - Location part = p.getLocation().clone().add(0, 0.25, 0).add(new Vector(1, 1, 1).multiply(RNG.r.d())).subtract(new Vector(1, 1, 1).multiply(RNG.r.d())); - part.add(RNG.r.d(), 0, RNG.r.d()); - if (extra != 0) { - p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(particleOffset), - part.getZ(), - particleCount, - randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, - randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, - randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ, - extra); - } else { - p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(particleOffset), part.getZ(), - particleCount, - randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, - randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, - randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ); - } - } - }); - } } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java index 5821b383b..709d4c2b1 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java @@ -19,70 +19,20 @@ package art.arcane.iris.engine.object.entity; import art.arcane.iris.engine.object.entity.spawn.IrisSurface; -import art.arcane.iris.engine.object.loot.InventorySlotType; import art.arcane.iris.engine.object.loot.IrisLoot; import art.arcane.iris.engine.object.loot.IrisLootReference; -import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.marker.IrisCommand; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.IrisServices; -import art.arcane.iris.core.IrisSettings; -import art.arcane.iris.core.link.Identifier; import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.core.service.EntityRiseSVC; -import art.arcane.iris.core.service.ExternalDataSVC; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.engine.platform.EngineBukkitOps; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.RegistryListEntityType; import art.arcane.iris.engine.object.annotations.RegistryListSpecialEntity; import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.platform.bukkit.BukkitPlatform; -import art.arcane.iris.util.common.data.registry.RegistryUtil; -import art.arcane.iris.platform.bukkit.BukkitWorld; -import art.arcane.iris.spi.PlatformWorld; import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.common.format.C; -import art.arcane.volmlib.util.math.M; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.common.plugin.Chunks; -import art.arcane.iris.util.common.scheduling.J; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.Sound; -import org.bukkit.attribute.Attributable; -import org.bukkit.entity.Ageable; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Mob; -import org.bukkit.entity.Panda; -import org.bukkit.entity.Villager; -import org.bukkit.entity.Panda.Gene; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.loot.LootContext; -import org.bukkit.loot.LootTable; -import org.bukkit.loot.Lootable; -import org.bukkit.util.Vector; - -import java.util.Collection; -import java.util.Locale; -import java.util.Random; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -import static art.arcane.iris.util.common.data.registry.Particles.ITEM; @SuppressWarnings("ALL") @Accessors(chain = true) @@ -194,355 +144,10 @@ public class IrisEntity extends IrisRegistrant { @Desc("Run raw commands when this entity is spawned. Use {x}, {y}, and {z} for location. /summon pig {x} {y} {z}") private KList rawCommands = new KList<>(); - public EntityType getBukkitType() { - if (type == null || type.isBlank()) { - return EntityType.UNKNOWN; - } - - NamespacedKey key = NamespacedKey.fromString(type.trim().toLowerCase(Locale.ROOT)); - - if (key == null) { - return EntityType.UNKNOWN; - } - - EntityType entityType = RegistryUtil.lookup(EntityType.class).get(key); - return entityType == null ? EntityType.UNKNOWN : entityType; - } - - public CreatureSpawnEvent.SpawnReason getBukkitReason() { - if (reason == null || reason.isBlank()) { - return CreatureSpawnEvent.SpawnReason.NATURAL; - } - - try { - return CreatureSpawnEvent.SpawnReason.valueOf(reason.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException e) { - return CreatureSpawnEvent.SpawnReason.NATURAL; - } - } - - public Gene getBukkitPandaMainGene() { - return resolveGene(pandaMainGene); - } - - public Gene getBukkitPandaHiddenGene() { - return resolveGene(pandaHiddenGene); - } - - private static Gene resolveGene(String gene) { - if (gene == null || gene.isBlank()) { - return Gene.NORMAL; - } - - try { - return Gene.valueOf(gene.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException e) { - return Gene.NORMAL; - } - } - - public Entity spawn(Engine gen, Location at) { - return spawn(gen, at, new RNG(at.hashCode())); - } - - public Entity spawn(Engine gen, Location at, RNG rng) { - if (!Chunks.isSafe(at)) { - return null; - } - if (isSpawnEffectRiseOutOfGround()) { - AtomicReference f = new AtomicReference<>(at); - try { - J.sfut(() -> { - if (Chunks.hasPlayersNearby(f.get())) { - Location b = f.get().clone(); - Location start = new Location(b.getWorld(), b.getX(), b.getY() - 5, b.getZ()); - f.set(start); - } - }).get(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - IrisLogging.reportError("Iris entity spawn preparation was interrupted.", e); - } catch (ExecutionException e) { - IrisLogging.reportError("Iris entity spawn preparation failed.", e); - } - at = f.get(); - } - - Entity ee = doSpawn(at); - - if (ee == null && !Chunks.isSafe(at)) { - return null; - } - - if (isSpecialType() && !applySettingsToCustomMobAnyways) { - return ee; - } - - if (ee == null) { - return null; - } - - Entity e = ee; - e.setCustomName(getCustomName() != null ? C.translateAlternateColorCodes('&', getCustomName()) : null); - e.setCustomNameVisible(isCustomNameVisible()); - e.setGlowing(isGlowing()); - e.setGravity(isGravity()); - e.setInvulnerable(isInvulnerable()); - e.setSilent(isSilent()); - e.setPersistent(isKeepEntity() || IrisSettings.get().getWorld().isForcePersistEntities()); - - int gg = 0; - for (IrisEntity i : passengers) { - Entity passenger = i.spawn(gen, at, rng.nextParallelRNG(234858 + gg++)); - if (passenger == null) { - continue; - } - - if (Bukkit.isPrimaryThread()) { - e.addPassenger(passenger); - } else { - J.runEntity(e, () -> e.addPassenger(passenger)); - } - } - - if (e instanceof Attributable) { - Attributable a = (Attributable) e; - - for (IrisAttributeModifier i : getAttributes()) { - i.apply(rng, a); - } - } - - if (e instanceof Lootable) { - Lootable l = (Lootable) e; - - if (getLoot().getTables().isNotEmpty()) { - BukkitOps.bindLoot(this, gen, l, at, rng); - } - } - - if (e instanceof LivingEntity) { - LivingEntity l = (LivingEntity) e; - l.setAI(isAi()); - l.setCanPickupItems(isPickupItems()); - - if (getLeashHolder() != null) { - l.setLeashHolder(getLeashHolder().spawn(gen, at, rng.nextParallelRNG(234548))); - } - - l.setRemoveWhenFarAway(isRemovable()); - - if (getHelmet() != null && LootResolver.oneIn(rng, getHelmet().getRarity())) { - l.getEquipment().setHelmet(getHelmet().get(gen.isStudio(), rng)); - } - - if (getChestplate() != null && LootResolver.oneIn(rng, getChestplate().getRarity())) { - l.getEquipment().setChestplate(getChestplate().get(gen.isStudio(), rng)); - } - - if (getLeggings() != null && LootResolver.oneIn(rng, getLeggings().getRarity())) { - l.getEquipment().setLeggings(getLeggings().get(gen.isStudio(), rng)); - } - - if (getBoots() != null && LootResolver.oneIn(rng, getBoots().getRarity())) { - l.getEquipment().setBoots(getBoots().get(gen.isStudio(), rng)); - } - - if (getMainHand() != null && LootResolver.oneIn(rng, getMainHand().getRarity())) { - l.getEquipment().setItemInMainHand(getMainHand().get(gen.isStudio(), rng)); - } - - if (getOffHand() != null && LootResolver.oneIn(rng, getOffHand().getRarity())) { - l.getEquipment().setItemInOffHand(getOffHand().get(gen.isStudio(), rng)); - } - } - - if (e instanceof Ageable && isBaby()) { - ((Ageable) e).setBaby(); - } - - if (e instanceof Panda) { - ((Panda) e).setMainGene(getBukkitPandaMainGene()); - ((Panda) e).setHiddenGene(getBukkitPandaHiddenGene()); - } - - if (e instanceof Villager) { - Villager villager = (Villager) e; - villager.setRemoveWhenFarAway(false); - BukkitOps.persistVillager(villager); - } - - if (e instanceof Mob) { - Mob m = (Mob) e; - m.setAware(isAware()); - } - - if (spawnEffect != null) { - spawnEffect.apply(e); - } - - if (rawCommands.isNotEmpty()) { - final Location fat = at; - final PlatformWorld commandWorld = new BukkitWorld(fat.getWorld()); - rawCommands.forEach(r -> r.run(commandWorld, fat.getBlockX(), fat.getBlockY(), fat.getBlockZ())); - } - - Location finalAt1 = at; - - J.runEntity(e, () -> { - if (isSpawnEffectRiseOutOfGround() && e instanceof LivingEntity && Chunks.hasPlayersNearby(finalAt1)) { - LivingEntity living = (LivingEntity) e; - Location start = finalAt1.clone(); - boolean originalInvulnerable = e.isInvulnerable(); - boolean originalAi = living.hasAI(); - boolean originalCollidable = living.isCollidable(); - int originalNoDamageTicks = living.getNoDamageTicks(); - EntityRiseSVC.stamp(e, originalInvulnerable, originalAi, originalCollidable); - e.setInvulnerable(true); - living.setAI(false); - living.setCollidable(false); - living.setNoDamageTicks(100000); - Runnable restore = () -> restoreRiseState(e, living, originalInvulnerable, originalAi, - originalCollidable, originalNoDamageTicks); - AtomicInteger t = new AtomicInteger(0); - Runnable[] loop = new Runnable[1]; - loop[0] = () -> { - if (t.get() > 100 || e.isDead()) { - restore.run(); - return; - } - - t.incrementAndGet(); - if (e.getLocation().getBlock().getType().isSolid() || living.getEyeLocation().getBlock().getType().isSolid()) { - e.teleport(start.add(new Vector(0, 0.1, 0))); - ItemStack itemCrackData = new ItemStack(living.getEyeLocation().clone().subtract(0, 2, 0).getBlock().getBlockData().getMaterial()); - e.getWorld().spawnParticle(ITEM, living.getEyeLocation(), 6, 0.2, 0.4, 0.2, 0.06f, itemCrackData); - if (M.r(0.2)) { - e.getWorld().playSound(e.getLocation(), Sound.BLOCK_CHORUS_FLOWER_GROW, 0.8f, 0.1f); - } - if (!J.runEntity(e, loop[0], 1, restore)) { - restore.run(); - } - } else { - restore.run(); - } - }; - if (!J.runEntity(e, loop[0], 0, restore)) { - restore.run(); - } - } - }); - - - return e; - } - - private static void restoreRiseState(Entity entity, LivingEntity living, boolean invulnerable, - boolean ai, boolean collidable, int noDamageTicks) { - living.setNoDamageTicks(noDamageTicks); - living.setCollidable(collidable); - living.setAI(ai); - entity.setInvulnerable(invulnerable); - EntityRiseSVC.clearStamp(entity); - } - - private int surfaceY(Location l) { - int m = l.getBlockY(); - - while (m-- > 0) { - Location ll = l.clone(); - ll.setY(m); - - if (ll.getBlock().getType().isSolid()) { - return m; - } - } - - return 0; - } - - private Entity doSpawn(Location at) { - if (!Chunks.isSafe(at)) { - return null; - } - - if (EntityType.UNKNOWN.equals(getBukkitType()) && !isSpecialType()) { - return null; - } - - if (!Bukkit.isPrimaryThread()) { - // Someone called spawn (worldedit maybe?) on a non server thread - // Due to the structure of iris, we will call it sync and busy wait until it's done. - AtomicReference ae = new AtomicReference<>(); - - try { - if (!J.runAt(at, () -> ae.set(doSpawn(at)))) { - return null; - } - } catch (Throwable e) { - return null; - } - PrecisionStopwatch p = PrecisionStopwatch.start(); - - while (ae.get() == null) { - J.sleep(25); - - if (p.getMilliseconds() > 500) { - return null; - } - } - - return ae.get(); - } - - if (isSpecialType()) { - return IrisServices.get(ExternalDataSVC.class).spawnMob(at, Identifier.fromString(specialType)); - } - - - return BukkitPlatform.spawnEntity(at, getBukkitType(), getBukkitReason()); - } - public boolean isSpecialType() { return specialType != null && !specialType.equals(""); } - private static final class BukkitOps { - private static void persistVillager(Villager villager) { - villager.setPersistent(true); - } - - private static void bindLoot(IrisEntity entity, Engine gen, Lootable l, Location finalAt, RNG rng) { - l.setLootTable(new LootTable() { - @Override - public NamespacedKey getKey() { - return new NamespacedKey("iris", "loot-" + entity.hashCode()); - } - - @Override - public Collection populateLoot(Random random, LootContext context) { - KList items = new KList<>(); - - for (String fi : entity.getLoot().getTables()) { - IrisLootTable i = gen.getData().getLootLoader().load(fi); - items.addAll(i.getLoot(gen.isStudio(), gen.getSeedManager().getLoot(), InventorySlotType.STORAGE, finalAt.getWorld(), finalAt.getBlockX(), finalAt.getBlockY(), finalAt.getBlockZ())); - } - - return items; - } - - @Override - public void fillInventory(Inventory inventory, Random random, LootContext context) { - for (ItemStack i : populateLoot(random, context)) { - inventory.addItem(i); - } - - EngineBukkitOps.scramble(gen, inventory, rng); - } - }); - } - } - @Override public String getFolderName() { return "entities"; diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java index 726b501b3..b68abf83c 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java @@ -21,34 +21,18 @@ package art.arcane.iris.engine.object.entity; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.platform.bukkit.BukkitWorldBinding; -import art.arcane.iris.platform.bukkit.BukkitPlatform; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.MinNumber; import art.arcane.iris.engine.object.annotations.RegistryListResource; import art.arcane.iris.engine.object.annotations.Required; import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.util.common.format.C; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.math.Vector3d; -import art.arcane.volmlib.util.matter.MatterMarker; -import art.arcane.volmlib.util.matter.slices.MarkerMatter; -import art.arcane.iris.util.common.scheduling.J; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.entity.Entity; @Snippet("entity-spawn") @Accessors(chain = true) @@ -75,164 +59,7 @@ public class IrisEntitySpawn implements IRare { private transient IrisSpawner referenceSpawner; private transient IrisMarker referenceMarker; - public int spawn(Engine gen, Chunk c, RNG rng) { - int spawns = LootResolver.inclusive(rng, minSpawns, maxSpawns); - int s = 0; - - if (spawns > 0) { - for (int id = 0; id < spawns; id++) { - int x = (c.getX() * 16) + rng.i(16); - int z = (c.getZ() * 16) + rng.i(16); - World world = BukkitWorldBinding.tryBind(gen.getWorld()) ? BukkitWorldBinding.world(gen.getWorld()) : null; - int h = gen.getHeight(x, z, true) + (world == null ? -64 : world.getMinHeight()); - int hf = gen.getHeight(x, z, false) + (world == null ? -64 : world.getMinHeight()); - Location l = switch (getReferenceSpawner().getGroup()) { - case NORMAL -> new Location(c.getWorld(), x, hf + 1, z); - case CAVE -> findCaveSpawnLocation(gen, c, rng); - case UNDERWATER, BEACH -> new Location(c.getWorld(), x, rng.i(h + 1, hf), z); - }; - - if (l != null) { - if (referenceSpawner.getAllowedLightLevels().getMin() > 0 || referenceSpawner.getAllowedLightLevels().getMax() < 15) { - if (referenceSpawner.getAllowedLightLevels().contains(l.getBlock().getLightLevel())) { - if (spawn100(gen, l) != null) { - s++; - } - } - } else { - if (spawn100(gen, l) != null) { - s++; - } - } - } - } - } - - return s; - } - - public int spawn(Engine gen, IrisPosition c, RNG rng) { - int spawns = LootResolver.inclusive(rng, minSpawns, maxSpawns); - int s = 0; - - if (!BukkitWorldBinding.tryBind(gen.getWorld())) { - return 0; - } - - World world = BukkitWorldBinding.world(gen.getWorld()); - if (spawns > 0) { - - if (referenceMarker != null && referenceMarker.shouldExhaust()) { - if (J.isFolia()) { - J.a(() -> gen.getMantle().getMantle().remove(c.getX(), c.getY() - gen.getWorld().minHeight(), c.getZ(), MatterMarker.class)); - } else { - gen.getMantle().getMantle().remove(c.getX(), c.getY() - gen.getWorld().minHeight(), c.getZ(), MatterMarker.class); - } - } - - for (int id = 0; id < spawns; id++) { - Location l = BukkitPlatform.toLocation(c, world).add(0, 1, 0); - - if (referenceSpawner.getAllowedLightLevels().getMin() > 0 || referenceSpawner.getAllowedLightLevels().getMax() < 15) { - if (referenceSpawner.getAllowedLightLevels().contains(l.getBlock().getLightLevel())) { - if (spawn100(gen, l, true) != null) { - s++; - } - } - } else { - if (spawn100(gen, l, true) != null) { - s++; - } - } - } - } - - return s; - } - public IrisEntity getRealEntity(Engine g) { return ent.aquire(() -> g.getData().getEntityLoader().load(getEntity())); } - - public Entity spawn(Engine g, Location at) { - if (getRealEntity(g) == null) { - return null; - } - - if (LootResolver.oneIn(rng.aquire(() -> new RNG(g.getSeedManager().getEntity())), getRarity())) { - return spawn100(g, at); - } - - return null; - } - - static Location findCaveSpawnLocation(Engine engine, Chunk chunk, RNG rng) { - if (J.isFolia()) { - return null; - } - KList markers = engine.getMantle().findMarkers(chunk.getX(), chunk.getZ(), MarkerMatter.CAVE_FLOOR); - return selectCaveSpawnLocation(markers, chunk.getWorld(), rng); - } - - static Location selectCaveSpawnLocation(KList markers, World world, RNG rng) { - return markers.convert((marker) -> BukkitPlatform.toLocation(marker, world).add(0, 1, 0)).getRandom(rng); - } - - private Entity spawn100(Engine g, Location at) { - return spawn100(g, at, false); - } - - private Entity spawn100(Engine g, Location at, boolean ignoreSurfaces) { - try { - IrisEntity irisEntity = getRealEntity(g); - if (irisEntity == null) { // No entity - IrisLogging.debug(" You are trying to spawn an entity that does not exist!"); - return null; - } - - if (!ignoreSurfaces && !irisEntity.getSurface().matches(at.clone().subtract(0, 1, 0).getBlock())) { - return null; - } - - Vector3d boundingBox = BukkitPlatform.entityBoundingBox(irisEntity.getBukkitType()); - if (!ignoreSurfaces && boundingBox != null) { - boolean isClearForSpawn = isAreaClearForSpawn(at, boundingBox); - if (!isClearForSpawn) { - return null; - } - } - - Entity e = irisEntity.spawn(g, at.add(0.5, 0.5, 0.5), rng.aquire(() -> new RNG(g.getSeedManager().getEntity()))); - if (e != null) { - IrisLogging.debug("Spawned " + C.DARK_AQUA + "Entity<" + getEntity() + "> " + C.GREEN + e.getType() + C.LIGHT_PURPLE + " @ " + C.GRAY + e.getLocation().getX() + ", " + e.getLocation().getY() + ", " + e.getLocation().getZ()); - } - - return e; - } catch (Throwable e) { - IrisLogging.reportError(e); - IrisLogging.error(" Failed to retrieve real entity @ " + at + " (entity: " + getEntity() + ")"); - return null; - } - } - - private boolean isAreaClearForSpawn(Location center, Vector3d boundingBox) { - World world = center.getWorld(); - int startX = center.getBlockX() - (int) (boundingBox.x / 2); - int endX = center.getBlockX() + (int) (boundingBox.x / 2); - int startY = center.getBlockY(); - int endY = center.getBlockY() + (int) boundingBox.y; - int startZ = center.getBlockZ() - (int) (boundingBox.z / 2); - int endZ = center.getBlockZ() + (int) (boundingBox.z / 2); - - for (int x = startX; x <= endX; x++) { - for (int y = startY; y <= endY; y++) { - for (int z = startZ; z <= endZ; z++) { - if (world.getBlockAt(x, y, z).getType() != Material.AIR) { - return false; - } - } - } - } - return true; - } } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java index 5924802b6..8a7677d15 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java @@ -19,9 +19,6 @@ package art.arcane.iris.engine.object.entity.spawn; import art.arcane.iris.engine.object.annotations.Desc; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.data.Waterlogged; @Desc("The type of surface entities should spawn on") public enum IrisSurface { @@ -40,29 +37,4 @@ public enum IrisSurface { @Desc("Within lava") LAVA; - - /** - * Check if this Iris surface matches the blockstate provided - * - * @param state The blockstate - * @return True if it matches - */ - public boolean matches(Block state) { - Material type = state.getType(); - if (type.isSolid()) { - return this == LAND || this == OVERWORLD || (this == ANIMAL - && (type == Material.GRASS_BLOCK || type == Material.DIRT - || type == Material.DIRT_PATH || type == Material.COARSE_DIRT - || type == Material.ROOTED_DIRT || type == Material.PODZOL - || type == Material.MYCELIUM || type == Material.SNOW_BLOCK)); - } - if (type == Material.LAVA) return this == LAVA; - if (type == Material.WATER || type == Material.SEAGRASS - || type == Material.TALL_SEAGRASS || type == Material.KELP_PLANT - || type == Material.KELP || - (state instanceof Waterlogged && ((Waterlogged) state).isWaterlogged())) - return this == WATER || this == OVERWORLD; - - return false; - } } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java index bd104ca0a..b3253cc09 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java @@ -31,13 +31,7 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import org.bukkit.NamespacedKey; -import org.bukkit.Registry; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.meta.EnchantmentStorageMeta; -import org.bukkit.inventory.meta.ItemMeta; -import java.util.Locale; @Snippet("enchantment") @@ -65,40 +59,6 @@ public class IrisEnchantment { @Desc("The chance that this enchantment is applied (0 to 1)") private double chance = 1; - public void apply(RNG rng, ItemMeta meta) { - try { - Enchantment enchant = resolve(); - if (enchant == null) { - IrisLogging.warn("Unknown Enchantment: " + getEnchantment()); - return; - } - if (rng.nextDouble() < chance) { - if (meta instanceof EnchantmentStorageMeta) { - ((EnchantmentStorageMeta) meta).addStoredEnchant(enchant, getLevel(rng), true); - return; - } - meta.addEnchant(enchant, getLevel(rng), true); - } - } catch (Throwable e) { - IrisLogging.reportError(e); - - } - } - - /** - * Resolves the authored key against the live enchantment registry. Accepts a bare path - * ({@code sharpness}) or a full namespaced key ({@code mymod:vorpal}) - parity with the modded resolver. - */ - private Enchantment resolve() { - String raw = getEnchantment(); - if (raw == null || raw.isBlank()) { - return null; - } - String value = raw.trim().toLowerCase(Locale.ROOT).replace(' ', '_'); - NamespacedKey key = value.indexOf(':') >= 0 ? NamespacedKey.fromString(value) : NamespacedKey.minecraft(value); - return key == null ? null : Registry.ENCHANTMENT.get(key); - } - public int getLevel(RNG rng) { return LootResolver.inclusive(rng, getMinLevel(), getMaxLevel()); } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java index 30251684e..57f699664 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java @@ -19,13 +19,6 @@ package art.arcane.iris.engine.object.loot; import art.arcane.iris.engine.object.entity.IrisAttributeModifier; -import art.arcane.iris.platform.bukkit.BukkitBlockResolution; - -import art.arcane.iris.spi.IrisServices; -import art.arcane.iris.core.link.Identifier; -import art.arcane.iris.core.service.ExternalDataSVC; -import art.arcane.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.MaxNumber; @@ -33,32 +26,14 @@ import art.arcane.iris.engine.object.annotations.MinNumber; import art.arcane.iris.engine.object.annotations.RegistryListItemType; import art.arcane.iris.engine.object.annotations.Required; import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.platform.bukkit.BukkitPlatform; -import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; -import art.arcane.iris.util.common.format.C; -import art.arcane.volmlib.util.format.Form; -import art.arcane.volmlib.util.math.RNG; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; import lombok.experimental.Accessors; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.inventory.meta.components.CustomModelDataComponent; -import org.bukkit.material.Colorable; - -import java.awt.Color; -import java.util.List; -import java.util.Optional; @Snippet("loot") @Accessors(chain = true) @@ -71,7 +46,6 @@ import java.util.Optional; public class IrisLoot { public static final int MAX_AMOUNT = 64; - private final transient AtomicCache dyeColorResolved = new AtomicCache<>(); @Desc("The target inventory slot types to fill this loot with. World generation only ever fills STORAGE; the other values are inert during worldgen.") private InventorySlotType slotTypes = InventorySlotType.STORAGE; @MinNumber(1) @@ -123,175 +97,17 @@ public class IrisLoot { @Desc("Defines a custom NBT Tag for the item.") private KMap customNbt; - public Material getType() { - return BukkitBlockResolution.getMaterial(type); - } - /** - * The authored item key, exactly as written in the pack. Platform-neutral: {@link #getType()} resolves it against - * Bukkit, mod loaders resolve it against their own item registry. + * The authored item key, exactly as written in the pack. Each platform resolves it against its own item registry. */ public String getTypeKey() { return type; } /** - * The authored dye colour name, or null when unset. Platform-neutral counterpart to {@link #getDyeColor()}. + * The authored dye colour name, or null when unset. */ public String getDyeColorKey() { return dyeColor; } - - public DyeColor getDyeColor() { - if (dyeColor == null) { - return null; - } - return dyeColorResolved.aquire(() -> { - try { - return DyeColor.valueOf(dyeColor); - } catch (IllegalArgumentException e) { - return null; - } - }); - } - - private KList getResolvedItemFlags() { - KList resolved = new KList<>(); - for (String flag : itemFlags) { - if (flag == null) { - continue; - } - try { - resolved.add(ItemFlag.valueOf(flag)); - } catch (IllegalArgumentException ignored) { - } - } - return resolved; - } - - public ItemStack get(boolean debug, RNG rng) { - try { - ItemStack is = getItemStack(rng); - if (is == null) - return new ItemStack(Material.AIR); - is.setItemMeta(applyProperties(is, rng, debug, null)); - return BukkitPlatform.applyCustomNbt(is, customNbt); - } catch (Throwable e) { - IrisLogging.reportError(e); - return new ItemStack(Material.AIR); - } - } - - public ItemStack get(boolean debug, IrisLootTable table, RNG rng, long lootSeed, int entryIndex, int x, int y, int z) { - long combinedRarity = LootResolver.combinedRarity(rarity, table.getRarity()); - if (!art.arcane.iris.engine.loot.LootTables.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) { - return null; - } - - try { - ItemStack is = getItemStack(rng); - if (is == null) - return null; - is.setItemMeta(applyProperties(is, rng, debug, table)); - return BukkitPlatform.applyCustomNbt(is, customNbt); - } catch (Throwable e) { - IrisLogging.reportError(e); - } - - return null; - } - - // TODO Better Third Party Item Acquisition - private ItemStack getItemStack(RNG rng) { - if (!type.startsWith("minecraft:") && type.contains(":")) { - Optional opt = IrisServices.get(ExternalDataSVC.class).getItemStack(Identifier.fromString(type), customNbt); - if (opt.isEmpty()) { - IrisLogging.warn("Unknown Material: " + type); - return new ItemStack(Material.AIR); - } - ItemStack is = opt.get(); - is.setAmount(Math.max(1, LootResolver.inclusive(rng, getMinAmount(), getMaxAmount()))); - return is; - } - return new ItemStack(getType(), Math.max(1, LootResolver.inclusive(rng, getMinAmount(), getMaxAmount()))); - } - - private ItemMeta applyProperties(ItemStack is, RNG rng, boolean debug, IrisLootTable table) { - ItemMeta m = is.getItemMeta(); - if (m == null) { - return null; - } - - for (IrisEnchantment i : getEnchantments()) { - i.apply(rng, m); - } - - for (IrisAttributeModifier i : getAttributes()) { - i.apply(rng, m); - } - - m.setUnbreakable(isUnbreakable()); - for (ItemFlag i : getResolvedItemFlags()) { - m.addItemFlags(i); - } - - if (getCustomModel() != null) { - CustomModelDataComponent customModelData = m.getCustomModelDataComponent(); - customModelData.setFloats(List.of(getCustomModel().floatValue())); - m.setCustomModelDataComponent(customModelData); - } - - if (is.getType().getMaxDurability() > 0 && m instanceof Damageable d) { - int max = is.getType().getMaxDurability(); - d.setDamage((int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(getMinDurability(), getMaxDurability())) * max)))); - } - - if (getLeatherColor() != null && m instanceof LeatherArmorMeta leather) { - Color c = Color.decode(getLeatherColor()); - leather.setColor(org.bukkit.Color.fromRGB(c.getRed(), c.getGreen(), c.getBlue())); - } - - if (getDyeColor() != null && m instanceof Colorable colorable) { - colorable.setColor(getDyeColor()); - } - - if (displayName != null) { - m.setDisplayName(C.translateAlternateColorCodes('&', displayName)); - } - - KList lore = new KList<>(); - - getLore().forEach((i) -> - { - String mf = C.translateAlternateColorCodes('&', i); - - if (mf.length() > 24) { - for (String g : Form.wrapWords(mf, 24).split("\\Q\n\\E")) { - lore.add(g.trim()); - } - } else { - lore.add(mf); - } - }); - - if (debug) { - if (table == null) { - if (lore.isNotEmpty()) { - lore.add(C.GRAY + "--------------------"); - } - lore.add(C.GRAY + "1 in " + (getRarity()) + " Chance (" + Form.pc(1D / (getRarity()), 5) + ")"); - } else { - if (lore.isNotEmpty()) { - lore.add(C.GRAY + "--------------------"); - } - - lore.add(C.GRAY + "From: " + table.getName() + " (" + Form.pc(1D / table.getRarity(), 5) + ")"); - lore.add(C.GRAY + "1 in " + (table.getRarity() * getRarity()) + " Chance (" + Form.pc(1D / (table.getRarity() * getRarity()), 5) + ")"); - } - } - - m.setLore(lore); - - return m; - } } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java index 9b85aac40..d92ff93ee 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java @@ -19,22 +19,17 @@ package art.arcane.iris.engine.object.loot; import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.MaxNumber; import art.arcane.iris.engine.object.annotations.MinNumber; import art.arcane.iris.engine.object.annotations.Required; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.inventory.ItemStack; @Accessors(chain = true) @NoArgsConstructor @@ -74,35 +69,6 @@ public class IrisLootTable extends IrisRegistrant { @ArrayType(min = 1, type = IrisLoot.class) private KList loot = new KList<>(); - public KList getLoot(boolean debug, long lootSeed, InventorySlotType slot, World world, int x, int y, int z) { - KList lootf = new KList<>(); - if (loot.isEmpty() || maxTries <= 0) { - return lootf; - } - - RNG rng = art.arcane.iris.engine.loot.LootTables.rng(lootSeed, this, x, y, z); - int m = 0; - int c = 0; - int mx = Math.max(0, LootResolver.inclusive(rng, getMinPicked(), getMaxPicked())); - - while (m < mx && c++ < getMaxTries()) { - int num = rng.nextInt(loot.size()); - - IrisLoot l = loot.get(num); - - if (l != null && l.getSlotTypes() == slot) { - ItemStack item = l.get(debug, this, rng, lootSeed, num, x, y, z); - - if (item != null && item.getType() != Material.AIR) { - lootf.add(item); - m++; - } - } - } - - return lootf; - } - @Override public String getFolderName() { return "loot"; diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java index e61521405..d4a207804 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java @@ -1,20 +1,9 @@ package art.arcane.iris.engine.object.loot; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; import lombok.Data; import lombok.EqualsAndHashCode; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.World; -import org.bukkit.inventory.ItemStack; -import org.bukkit.loot.LootContext; -import org.bukkit.loot.LootTable; import java.io.File; @@ -25,22 +14,13 @@ public class IrisVanillaLootTable extends IrisLootTable { * The vanilla loot table key ("minecraft:chests/simple_dungeon"), not the LootTable itself. A * raw org.bukkit.loot.LootTable field - and the constructor lombok would generate for it - makes * every reflective walk over the IrisLootTable hierarchy (Gson, schema generation, the purity - * gate) resolve a Bukkit class. The table is resolved lazily at pull time, which only ever - * happens on Bukkit. The key text is identical to what {@code LootTable.getKey().toString()} - * produced before, so {@code LootResolver.tableIdentity} (which falls back to + * gate) resolve a Bukkit class. The host resolves the table when it pulls loot from it. The key text is + * identical to what {@code LootTable.getKey().toString()} produced before, so + * {@code LootTables.identity} (which falls back to * {@link #getName()}) yields the same loot seed. */ private final String lootTableKey; - /** - * The resolved table, looked up once. Every chest pull resolved it again - a NamespacedKey parse plus a registry - * lookup per container, and a dungeon room is a lot of containers. - *

- * Transient for the same reason the field above is a String: it keeps the Bukkit type argument out of the Gson - * field walk and out of the pack purity gate, both of which resolve generic field types for the fields they visit. - */ - private final transient AtomicCache resolvedTable = new AtomicCache<>(); - @Override public String getName() { return "Vanilla " + lootTableKey; @@ -71,24 +51,6 @@ public class IrisVanillaLootTable extends IrisLootTable { return new KList<>(); } - @Override - public KList getLoot(boolean debug, long lootSeed, InventorySlotType slot, World world, int x, int y, int z) { - LootTable table = resolveTable(); - if (table == null) { - IrisLogging.warn("Unknown vanilla loot table " + lootTableKey); - return new KList<>(); - } - RNG rng = art.arcane.iris.engine.loot.LootTables.rng(lootSeed, this, x, y, z); - return new KList<>(table.populateLoot(rng, new LootContext.Builder(new Location(world, x, y, z)).build())); - } - - private LootTable resolveTable() { - return resolvedTable.aquire(() -> { - NamespacedKey key = NamespacedKey.fromString(lootTableKey); - return key == null ? null : Bukkit.getLootTable(key); - }); - } - @Override public String getFolderName() { throw new UnsupportedOperationException("VanillaLootTables do not have a folder name"); diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java b/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java index f7e6cf5af..5062b80b5 100644 --- a/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java +++ b/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java @@ -24,9 +24,8 @@ import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.Required; import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformWorld; -import art.arcane.iris.util.common.scheduling.J; +import art.arcane.iris.util.common.scheduling.ConsoleCommands; import art.arcane.volmlib.util.collection.KList; import lombok.Data; import lombok.NoArgsConstructor; @@ -68,19 +67,6 @@ public class IrisCommand { return; } - for (String command : commands) { - command = (command.startsWith("/") ? command.replaceFirst("/", "") : command) - .replaceAll("\\Q{x}\\E", String.valueOf(x)) - .replaceAll("\\Q{y}\\E", String.valueOf(y)) - .replaceAll("\\Q{z}\\E", String.valueOf(z)); - final String finalCommand = command; - int safeDelay = (int) Math.max(0, Math.min(Integer.MAX_VALUE, delay)); - if (repeat) { - int safeRepeatDelay = (int) Math.max(1, Math.min(Integer.MAX_VALUE, repeatDelay)); - J.s(() -> J.sr(() -> IrisPlatforms.get().dispatchConsoleCommand(finalCommand), safeRepeatDelay), safeDelay); - } else { - J.s(() -> IrisPlatforms.get().dispatchConsoleCommand(finalCommand), safeDelay); - } - } + ConsoleCommands.run(commands, delay, repeat, repeatDelay, x, y, z); } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java new file mode 100644 index 000000000..a5277349e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java @@ -0,0 +1,128 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.loot.LootItems; +import art.arcane.iris.engine.object.entity.IrisAttributeModifier; +import art.arcane.iris.engine.object.entity.IrisEffect; +import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.engine.object.loot.IrisLoot; +import art.arcane.iris.engine.object.marker.IrisCommand; +import art.arcane.iris.spi.PlatformWorld; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.entity.EntitySpec; +import com.volmit.item.ItemAttribute; +import com.volmit.item.ItemDrop; + +import java.util.ArrayList; +import java.util.List; + +/** + * Turns an entity of the pack into the {@link EntitySpec} the host spawns, making every random choice in the order Iris + * always made them: the passengers, the attribute modifiers, the leash holder and then the six pieces of equipment. + */ +final class EntityResolution { + private static final long PASSENGER_STREAM_BASE = 234858L; + private static final long LEASH_HOLDER_STREAM = 234548L; + + private final LootItems items; + private final PlatformWorld world; + + /** @param world the world the entity appears in, whose time and weather decide which of its commands run */ + EntityResolution(LootItems items, PlatformWorld world) { + this.items = items; + this.world = world; + } + + EntitySpec resolve(IrisEntity entity, RNG rng) { + List passengers = new ArrayList<>(); + long passengerIndex = 0; + for (IrisEntity passenger : entity.getPassengers()) { + passengers.add(resolve(passenger, rng.nextParallelRNG(PASSENGER_STREAM_BASE + passengerIndex++))); + } + + List attributes = drawAttributes(entity, rng); + List lootTables = List.copyOf(entity.getLoot().getTables()); + long lootShuffleSeed = lootTables.isEmpty() ? 0L : rng.nextLong(); + EntitySpec leashHolder = entity.getLeashHolder() == null ? null : resolve(entity.getLeashHolder(), rng.nextParallelRNG(LEASH_HOLDER_STREAM)); + EntitySpec.Equipment equipment = new EntitySpec.Equipment( + equip(entity.getHelmet(), rng), equip(entity.getChestplate(), rng), equip(entity.getLeggings(), rng), + equip(entity.getBoots(), rng), equip(entity.getMainHand(), rng), equip(entity.getOffHand(), rng)); + + return new EntitySpec( + entity.getType() == null ? "" : entity.getType(), + entity.getSpecialType() == null ? "" : entity.getSpecialType(), + entity.getReason(), + entity.getCustomName() == null ? "" : entity.getCustomName(), + flagsOf(entity), equipment, passengers, attributes, lootTables, lootShuffleSeed, leashHolder, + spawnEffectOf(entity), entity.isSpawnEffectRiseOutOfGround(), entity.getPandaMainGene(), + entity.getPandaHiddenGene(), entity.isApplySettingsToCustomMobAnyways(), commandsOf(entity)); + } + + private static EntitySpec.Flags flagsOf(IrisEntity entity) { + return new EntitySpec.Flags(entity.isCustomNameVisible(), entity.isAware(), entity.isAi(), entity.isGlowing(), + entity.isGravity(), entity.isInvulnerable(), entity.isSilent(), entity.isPickupItems(), entity.isRemovable(), + entity.isKeepEntity(), entity.isBaby()); + } + + private static List drawAttributes(IrisEntity entity, RNG rng) { + List attributes = new ArrayList<>(); + for (IrisAttributeModifier modifier : entity.getAttributes()) { + if (rng.nextDouble() >= modifier.getChance()) { + continue; + } + String attribute = modifier.getAttribute(); + if (attribute == null || attribute.isBlank()) { + continue; + } + attributes.add(new ItemAttribute(attribute, modifier.getName(), modifier.getOperation(), modifier.getAmount(rng))); + } + return attributes; + } + + private ItemDrop equip(IrisLoot piece, RNG rng) { + if (piece == null || !LootResolver.oneIn(rng, piece.getRarity())) { + return null; + } + return items.give(piece, rng); + } + + /** The entity's spawn effect when it shows this time: an effect only shows now and then, as its interval and chance say. */ + private static EntitySpec.SpawnEffect spawnEffectOf(IrisEntity entity) { + IrisEffect effect = entity.getSpawnEffect(); + if (effect == null || !effect.shouldApplyNow()) { + return null; + } + return new EntitySpec.SpawnEffect(effect.getSoundKey(), effect.getSoundDistance(), effect.getMinPitch(), + effect.getMaxPitch(), effect.getVolume(), effect.getParticleEffectKey(), effect.getParticleOffset(), + effect.getParticleCount(), effect.getParticleAltX(), effect.getParticleAltY(), effect.getParticleAltZ(), + effect.isRandomAltX(), effect.isRandomAltY(), effect.isRandomAltZ(), effect.getExtra()); + } + + private List commandsOf(IrisEntity entity) { + List commands = new ArrayList<>(); + for (IrisCommand command : entity.getRawCommands()) { + if (command.isValid(world)) { + commands.add(new EntitySpec.Command(command.getCommands(), command.getDelay(), command.isRepeat(), command.getRepeatDelay())); + } + } + return commands; + } +} diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java new file mode 100644 index 000000000..5c9bec4f1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -0,0 +1,269 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.loot.LootItems; +import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.engine.object.entity.IrisEntitySpawn; +import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +import art.arcane.iris.engine.object.entity.spawn.IrisSurface; +import art.arcane.iris.engine.object.marker.IrisMarker; +import art.arcane.iris.engine.object.value.IRare; +import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.iris.engine.object.value.IrisRange; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.util.common.scheduling.J; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.slices.MarkerMatter; +import com.volmit.entity.EntitySpec; +import com.volmit.service.EntitySpawns; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * How {@code iris:spawn} spawns entities: the spawners of the dimension, region and surface biome that may fire in a + * chunk, or the spawners of a marker, each with the entities it spawns and the places it picks for them. What the + * platform decides (light, the surface, free space, the entity itself) is the host's, the plan only names it. + */ +public final class EntitySpawning implements EntitySpawns { + private static final int BLOCKS_TO_CHUNK_CENTRE = 8; + private static final int CHUNK_SIZE = 16; + private static final String CAVE_FLOOR_MARKER = "cave_floor"; + private static final String CAVE_CEILING_MARKER = "cave_ceiling"; + private static final int AIR_ABOVE_MARKER = 1; + + @Override + public Optional plan(PackWorld world, Site site) { + Engine engine = engine(world); + return switch (site) { + case Chunk chunk -> planChunk(world, engine, chunk); + case Marker marker -> planMarker(world, engine, marker); + }; + } + + @Override + public void spawned(PackWorld world, Plan plan, int count) { + if (count <= 0) { + return; + } + IrisSpawner spawner = engine(world).getData().getSpawnerLoader().load(plan.spawner()); + if (spawner != null) { + spawner.spawn(engine(world), plan.chunkX(), plan.chunkZ()); + } + } + + @Override + public Optional entity(PackWorld world, String key) { + IrisEntity entity = engine(world).getData().getEntityLoader().load(key); + if (entity == null) { + return Optional.empty(); + } + return Optional.of(resolution(world, engine(world)).resolve(entity, entityRandom(world).rng())); + } + + @Override + public Optional marker(PackWorld world, String tag) { + if (tag.equals(CAVE_FLOOR_MARKER) || tag.equals(CAVE_CEILING_MARKER)) { + return Optional.empty(); + } + Engine engine = engine(world); + IrisMarker marker = engine.getData().getMarkerLoader().load(tag); + if (marker == null) { + return Optional.empty(); + } + + List spawners = new ArrayList<>(); + for (String key : marker.getSpawners()) { + if (engine.getData().getSpawnerLoader().load(key) == null) { + IrisLogging.error("Cannot load spawner: " + key + " for marker " + tag); + continue; + } + spawners.add(key); + } + return Optional.of(new MarkerRule(spawners, marker.isEmptyAbove(), marker.isRemoveOnChange())); + } + + private Optional planChunk(PackWorld world, Engine engine, Chunk chunk) { + Predicate canSpawn = spawner -> spawner.canSpawn(engine, chunk.chunkX(), chunk.chunkZ()); + int blockX = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkX()); + int blockZ = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkZ()); + IrisBiome centreBiome = engine.getSurfaceBiome(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE); + IrisRegion region = engine.getRegion(blockX, blockZ); + IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ); + + List candidates = Stream.concat( + shuffled(engine, engine.getDimension().getEntitySpawners()).stream() + .filter(canSpawn).filter(spawner -> spawner.isValid(centreBiome)), + Stream.concat( + shuffled(engine, region.getEntitySpawners()).stream().filter(canSpawn), + shuffled(engine, biome.getEntitySpawners()).stream().filter(canSpawn))) + .filter(spawner -> chunk.livingEntities() < spawner.getMaxEntitiesPerChunk()) + .toList(); + + List spawns = candidates.stream().flatMap(spawner -> spawnsOf(spawner, chunk.initial())).collect(Collectors.toList()); + Candidate chosen = IRare.expandWeighted(spawns).getRandom(); + if (chosen == null) { + return Optional.empty(); + } + return planChunkSpawn(world, engine, chunk, chosen); + } + + private Optional planChunkSpawn(PackWorld world, Engine engine, Chunk chunk, Candidate chosen) { + IrisSpawner spawner = chosen.spawner(); + IrisEntitySpawn spawn = chosen.spawn(); + int count = LootResolver.inclusive(RNG.r, spawn.getMinSpawns(), spawn.getMaxSpawns()); + List attempts = new ArrayList<>(); + for (int i = 0; i < count; i++) { + int x = (chunk.chunkX() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); + int z = (chunk.chunkZ() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); + BlockPosition at = spawnPosition(engine, spawner, chunk.chunkX(), chunk.chunkZ(), x, z); + if (at != null) { + addAttempt(attempts, world, engine, chosen, at, true); + } + } + return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(spawner.getLoadKey(), chunk.chunkX(), chunk.chunkZ(), false, attempts)); + } + + /** Where a spawner of its group puts an entity at the column; null when it has no place for one. */ + private static BlockPosition spawnPosition(Engine engine, IrisSpawner spawner, int chunkX, int chunkZ, int x, int z) { + int height = engine.getHeight(x, z, true); + int heightWithFluid = engine.getHeight(x, z, false); + return switch (spawner.getGroup()) { + case NORMAL -> new BlockPosition(x, heightWithFluid + 1, z); + case CAVE -> caveSpawnPosition(engine, chunkX, chunkZ); + case UNDERWATER, BEACH -> new BlockPosition(x, RNG.r.i(height + 1, heightWithFluid), z); + }; + } + + static BlockPosition caveSpawnPosition(Engine engine, int chunkX, int chunkZ) { + if (J.isFolia()) { + return null; + } + KList floors = engine.getMantle().findMarkers(chunkX, chunkZ, MarkerMatter.CAVE_FLOOR); + IrisPosition floor = floors.getRandom(RNG.r); + return floor == null ? null : new BlockPosition(floor.getX(), floor.getY() - engine.getMinHeight() + AIR_ABOVE_MARKER, floor.getZ()); + } + + private Optional planMarker(PackWorld world, Engine engine, Marker marker) { + IrisSpawner spawner = engine.getData().getSpawnerLoader().load(marker.spawner()); + IrisMarker irisMarker = engine.getData().getMarkerLoader().load(marker.marker()); + if (spawner == null) { + return Optional.empty(); + } + + KList candidates = marker.initial() ? spawner.getInitialSpawns() : spawner.getSpawns(); + if (candidates.isEmpty()) { + return Optional.empty(); + } + IrisEntitySpawn spawn = IRare.expandWeighted(candidates).getRandom(); + + BlockPosition position = marker.position(); + int chunkX = PowerOfTwoCoordinates.blockToChunkFloor(position.x()); + int chunkZ = PowerOfTwoCoordinates.blockToChunkFloor(position.z()); + if (!spawner.canSpawn(engine, chunkX, chunkZ)) { + return Optional.empty(); + } + + int count = LootResolver.inclusive(RNG.r, spawn.getMinSpawns(), spawn.getMaxSpawns()); + if (count <= 0) { + return Optional.empty(); + } + boolean exhaustsMarker = irisMarker != null && irisMarker.shouldExhaust(); + List attempts = new ArrayList<>(); + BlockPosition above = new BlockPosition(position.x(), position.y() + AIR_ABOVE_MARKER, position.z()); + for (int i = 0; i < count; i++) { + addAttempt(attempts, world, engine, new Candidate(spawner, spawn), above, false); + } + return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(spawner.getLoadKey(), chunkX, chunkZ, exhaustsMarker, attempts)); + } + + private void addAttempt(List attempts, PackWorld world, Engine engine, Candidate candidate, BlockPosition at, boolean checkSurface) { + IrisEntity entity = candidate.spawn().getRealEntity(engine); + if (entity == null) { + IrisLogging.debug(" You are trying to spawn an entity that does not exist!"); + return; + } + + IrisRange light = candidate.spawner().getAllowedLightLevels(); + EntitySpec spec = resolution(world, engine).resolve(entity, entityRandom(world).rng()); + attempts.add(new Attempt(at, spec, surfaceOf(entity.getSurface()), + (int) Math.ceil(light.getMin()), (int) Math.floor(light.getMax()), checkSurface)); + } + + private static EntityResolution resolution(PackWorld world, Engine engine) { + LootItems items = new LootItems(world.resources().items(), engine.isStudio()); + return new EntityResolution(items, engine.getWorld().platformWorld()); + } + + private static EntityRandom entityRandom(PackWorld world) { + return world.state(EntityRandom.class, EntityRandom::new); + } + + private static Surface surfaceOf(IrisSurface surface) { + return Surface.valueOf(surface.name()); + } + + private static KList shuffled(Engine engine, KList keys) { + return engine.getData().getSpawnerLoader().loadAll(keys).shuffleCopy(RNG.r); + } + + private static Stream spawnsOf(IrisSpawner spawner, boolean initial) { + KList spawns = initial ? spawner.getInitialSpawns() : spawner.getSpawns(); + return spawns.stream().map(spawn -> new Candidate(spawner, spawn)); + } + + /** A spawn of a spawner, which picks as often as the spawn's rarity says. */ + private record Candidate(IrisSpawner spawner, IrisEntitySpawn spawn) implements IRare { + @Override + public int getRarity() { + return spawn.getRarity(); + } + } + + private static Engine engine(PackWorld world) { + return IrisPackWorld.of(world).engine(); + } + + /** The random stream entities are made from, seeded from the world like Iris always seeded it; one per world. */ + private static final class EntityRandom { + private final RNG rng; + + private EntityRandom(PackWorld world) { + this.rng = new RNG(IrisPackWorld.of(world).engine().getSeedManager().getEntity()); + } + + private RNG rng() { + return rng; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java new file mode 100644 index 000000000..d0663b44f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -0,0 +1,48 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import com.volmit.FeatureRegistry; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.service.EntitySpawns; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:spawn}: the spawners, entities and markers of the pack, and the entities that appear in the world + * over time because of them. It has no generation stage; Iris asks it through {@link EntitySpawns} when it looks for + * something to spawn in a chunk or at a marker. + */ +public final class SpawnModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:spawn", "Spawn", VERSION); + } + + @Override + public void install(StageGraph graph) { + } + + @Override + public void register(FeatureRegistry registry) { + registry.registerService(EntitySpawns.class, new EntitySpawning()); + } +} From 8428da4f50a963076e7d3526f7f35594629a57c5 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:24:20 +0200 Subject: [PATCH 6/7] Loot tables, spawners, entities and markers are resource kinds of iris:loot and iris:spawn LootResources and SpawnResources keep the folders and lookups by key; LootValidator is the loot check that was Iris's PackLootValidator. --- .../arcane/iris/engine/loot/LootGiving.java | 2 +- .../arcane/iris/engine/loot/LootModule.java | 6 +- .../iris/engine/loot/LootResources.java | 78 +++++ .../iris/engine/loot/LootValidator.java | 286 ++++++++++++++++++ .../engine/object/entity/IrisEntitySpawn.java | 3 +- .../entity/spawn/IrisSpawnerCooldowns.java | 3 +- .../engine/object/loot/IrisLootReference.java | 3 +- .../engine/object/placement/BlocksModule.java | 3 +- .../object/placement/IrisObjectPlacement.java | 3 +- .../iris/engine/spawn/EntitySpawning.java | 14 +- .../arcane/iris/engine/spawn/SpawnModule.java | 3 +- .../iris/engine/spawn/SpawnResources.java | 111 +++++++ 12 files changed, 499 insertions(+), 16 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootResources.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootValidator.java create mode 100644 src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index f747148a8..3613ff1cb 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -70,7 +70,7 @@ public final class LootGiving implements Loot { @Override public List items(PackWorld world, Site site, String key) { Engine engine = engine(world); - IrisLootTable table = engine.getData().getLootLoader().load(key); + IrisLootTable table = LootResources.table(engine.getData(), key); if (table == null) { return List.of(); } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/src/main/java/art/arcane/iris/engine/loot/LootModule.java index ff32bc104..939bcccb7 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootModule.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -26,8 +26,8 @@ import com.volmit.service.Loot; import com.volmit.stage.StageGraph; /** - * Module {@code iris:loot}: the loot tables of the pack and the items they and the block drops of the dimension, regions - * and biomes give. It has no generation stage; Iris asks it through {@link Loot} when a container is filled and through + * Module {@code iris:loot}: the loot tables of the pack ({@link LootResources}) and the items they and the block drops + * of the dimension, regions and biomes give. It checks the tables and the references to them ({@link LootValidator}). It has no generation stage; Iris asks it through {@link Loot} when a container is filled and through * {@link BlockDrops} when a player breaks a block. */ public final class LootModule implements IrisModule { @@ -44,6 +44,8 @@ public final class LootModule implements IrisModule { @Override public void register(FeatureRegistry registry) { + LootResources.kinds().forEach(registry::registerResourceKind); + registry.registerValidator(new LootValidator()); registry.registerService(Loot.class, new LootGiving()); registry.registerService(BlockDrops.class, new BlockDropping()); } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootResources.java b/src/main/java/art/arcane/iris/engine/loot/LootResources.java new file mode 100644 index 000000000..3c0a8faa1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootResources.java @@ -0,0 +1,78 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; + +import java.util.List; + +/** + * The resource kind of module {@code iris:loot}, which keeps the folder and files Iris packs have always used, and + * lookups by pack key for code that still names loot tables by key. Every lookup goes through the pack's + * {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot. + *

+ * Lookups answer null where Iris's loader did: for a blank key, a key the pack has no file for, and a file that fails + * to load, which was reported when it was read. + */ +public final class LootResources { + /** Loot tables, in {@code loot/}. */ + public static final ResourceKind TABLES = ResourceKind.of("iris:loot/table", "loot", IrisLootTable.class); + + private LootResources() { + } + + /** Every resource kind of the loot module. */ + public static List> kinds() { + return List.of(TABLES); + } + + public static IrisLootTable table(IrisData data, String key) { + if (key == null || key.isBlank()) { + return null; + } + IrisPackResources resources = data.getPackResources(); + try { + return resources.find(TABLES.key(resources.idOf(key))).orElse(null); + } catch (IllegalStateException failedToLoad) { + return null; + } + } + + /** The tables of the pack named by {@code keys}, in order, without the ones the pack lacks. */ + public static KList tables(IrisData data, List keys) { + KList tables = new KList<>(); + for (String key : keys) { + IrisLootTable table = table(data, key); + if (table != null) { + tables.add(table); + } + } + return tables; + } + + /** The key of every loot table of the pack, in key order. */ + public static List tableKeys(IrisData data) { + return data.getPackResources().ids(TABLES.type()).stream().map(ResourceId::path).toList(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java new file mode 100644 index 000000000..e5f256fcb --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java @@ -0,0 +1,286 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.core.modules.IrisValidationContext; +import art.arcane.iris.core.pack.PackIntegerChecks; +import art.arcane.iris.core.pack.PackValidationIo; +import art.arcane.iris.engine.object.loot.IrisLoot; +import art.arcane.iris.engine.object.loot.IrisLootReference; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.volmlib.util.json.JSONArray; +import art.arcane.volmlib.util.json.JSONObject; +import com.volmit.validation.Problem; +import com.volmit.validation.Subject; +import com.volmit.validation.ValidationContext; +import com.volmit.validation.Validator; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Module {@code iris:loot}'s check of a pack: every loot table has sane picks, tries and entries, and every loot + * reference of a dimension, region or biome names a table the pack has. The files are read as written, like the pack + * validator's other file checks, so a malformed table is reported rather than failing the load. + */ +public final class LootValidator implements Validator { + private static final List LOOT_HOST_FOLDERS = List.of("dimensions", "regions", "biomes"); + private static final String JSON_EXTENSION = ".json"; + + @Override + public void validate(ValidationContext pack) { + check(IrisValidationContext.of(pack).data().getDataFolder()).forEach(pack::report); + } + + /** What is wrong with the loot tables and loot references of the pack in {@code packFolder}. */ + public static List check(File packFolder) { + List problems = new ArrayList<>(); + if (packFolder == null || !packFolder.isDirectory()) { + return problems; + } + + File lootFolder = new File(packFolder, LootResources.TABLES.folder()); + Set lootKeys = keysOf(lootFolder); + checkTables(lootFolder, problems); + for (String folderName : LOOT_HOST_FOLDERS) { + checkReferences(new File(packFolder, folderName), folderName, lootKeys, problems); + } + return problems; + } + + private static void checkTables(File lootFolder, List problems) { + if (!lootFolder.isDirectory()) { + return; + } + List lootFiles = PackValidationIo.listJsonRecursive(lootFolder); + lootFiles.sort(Comparator.comparing(File::getPath)); + for (File lootFile : lootFiles) { + String lootKey = PackValidationIo.deriveKey(lootFolder, lootFile); + List errors = new ArrayList<>(); + JSONObject table = readTable(lootFile, lootKey, errors); + if (table != null) { + validateLootTable(lootKey, table, errors); + } + report(problems, Problem::error, Subject.file(LootResources.TABLES.folder() + "/" + lootKey + JSON_EXTENSION), errors); + } + } + + private static void checkReferences(File resourceFolder, String folderName, Set lootKeys, List problems) { + if (!resourceFolder.isDirectory()) { + return; + } + List resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); + resourceFiles.sort(Comparator.comparing(File::getPath)); + for (File resourceFile : resourceFiles) { + JSONObject resource = PackValidationIo.readJson(resourceFile); + if (resource == null || !resource.has("loot")) { + continue; + } + String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile); + List errors = new ArrayList<>(); + List warnings = new ArrayList<>(); + validateLootReference(hostType(folderName), resourceKey, resource.opt("loot"), lootKeys, errors, warnings); + Subject subject = Subject.file(folderName + "/" + resourceKey + JSON_EXTENSION); + report(problems, Problem::error, subject, errors); + report(problems, Problem::warning, subject, warnings); + } + } + + private static void report(List problems, java.util.function.BiFunction severity, + Subject subject, List messages) { + for (String message : messages) { + problems.add(severity.apply(subject, message)); + } + } + + private static Set keysOf(File folder) { + Set keys = new HashSet<>(); + if (!folder.isDirectory()) { + return keys; + } + for (File file : PackValidationIo.listJsonRecursive(folder)) { + String key = PackValidationIo.deriveKey(folder, file); + if (key != null && !key.isBlank()) { + keys.add(key); + } + } + return keys; + } + + private static JSONObject readTable(File file, String key, List errors) { + try { + return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8)); + } catch (IOException | RuntimeException e) { + String reason = e.getMessage(); + if (reason == null || reason.isBlank()) { + reason = e.getClass().getSimpleName(); + } + errors.add("Loot table '" + key + "' has invalid JSON: " + reason); + return null; + } + } + + private static String hostType(String folderName) { + return switch (folderName) { + case "dimensions" -> "Dimension"; + case "regions" -> "Region"; + case "biomes" -> "Biome"; + default -> "Resource"; + }; + } + + private static void validateLootTable(String lootKey, JSONObject table, List blockingErrors) { + String path = "Loot table '" + lootKey + "'"; + Integer rarity = PackIntegerChecks.integerField(table, "rarity", 1, path, blockingErrors); + Integer minimumPicked = PackIntegerChecks.integerField(table, "minPicked", 1, path, blockingErrors); + Integer maximumPicked = PackIntegerChecks.integerField(table, "maxPicked", 5, path, blockingErrors); + Integer maximumTries = PackIntegerChecks.integerField(table, "maxTries", 10, path, blockingErrors); + PackIntegerChecks.requireMinimum(path + ".rarity", rarity, 1, blockingErrors); + PackIntegerChecks.requireMinimum(path + ".minPicked", minimumPicked, 0, blockingErrors); + PackIntegerChecks.requireMinimum(path + ".maxPicked", maximumPicked, 1, blockingErrors); + PackIntegerChecks.requireMinimum(path + ".maxTries", maximumTries, 1, blockingErrors); + PackIntegerChecks.requireMaximum(path + ".minPicked", minimumPicked, IrisLootTable.MAX_PICKED, blockingErrors); + PackIntegerChecks.requireMaximum(path + ".maxPicked", maximumPicked, IrisLootTable.MAX_PICKED, blockingErrors); + PackIntegerChecks.requireMaximum(path + ".maxTries", maximumTries, IrisLootTable.MAX_TRIES, blockingErrors); + PackIntegerChecks.requireOrdered(path + ".minPicked", minimumPicked, path + ".maxPicked", maximumPicked, blockingErrors); + + JSONArray entries = table.optJSONArray("loot"); + if (entries == null || entries.length() == 0) { + blockingErrors.add(path + ".loot must be a non-empty array."); + return; + } + for (int entryIndex = 0; entryIndex < entries.length(); entryIndex++) { + JSONObject entry = entries.optJSONObject(entryIndex); + String entryPath = path + ".loot[" + entryIndex + "]"; + if (entry == null) { + blockingErrors.add(entryPath + " must be an object."); + continue; + } + String type = entry.optString("type", "").trim(); + if (type.isEmpty()) { + blockingErrors.add(entryPath + ".type must not be blank."); + } + Integer entryRarity = PackIntegerChecks.integerField(entry, "rarity", 1, entryPath, blockingErrors); + Integer minimumAmount = PackIntegerChecks.integerField(entry, "minAmount", 1, entryPath, blockingErrors); + Integer maximumAmount = PackIntegerChecks.integerField(entry, "maxAmount", 1, entryPath, blockingErrors); + PackIntegerChecks.requireMinimum(entryPath + ".rarity", entryRarity, 1, blockingErrors); + PackIntegerChecks.requireMinimum(entryPath + ".minAmount", minimumAmount, 1, blockingErrors); + PackIntegerChecks.requireMinimum(entryPath + ".maxAmount", maximumAmount, 1, blockingErrors); + PackIntegerChecks.requireMaximum(entryPath + ".minAmount", minimumAmount, IrisLoot.MAX_AMOUNT, blockingErrors); + PackIntegerChecks.requireMaximum(entryPath + ".maxAmount", maximumAmount, IrisLoot.MAX_AMOUNT, blockingErrors); + PackIntegerChecks.requireOrdered(entryPath + ".minAmount", minimumAmount, + entryPath + ".maxAmount", maximumAmount, blockingErrors); + validateLootEnchantments(entryPath, entry.opt("enchantments"), blockingErrors); + } + } + + private static void validateLootEnchantments(String entryPath, Object rawEnchantments, + List blockingErrors) { + if (rawEnchantments == null || rawEnchantments == JSONObject.NULL) { + return; + } + if (!(rawEnchantments instanceof JSONArray enchantments)) { + blockingErrors.add(entryPath + ".enchantments must be an array."); + return; + } + for (int enchantmentIndex = 0; enchantmentIndex < enchantments.length(); enchantmentIndex++) { + JSONObject enchantment = enchantments.optJSONObject(enchantmentIndex); + String enchantmentPath = entryPath + ".enchantments[" + enchantmentIndex + "]"; + if (enchantment == null) { + blockingErrors.add(enchantmentPath + " must be an object."); + continue; + } + if (enchantment.optString("enchantment", "").isBlank()) { + blockingErrors.add(enchantmentPath + ".enchantment must not be blank."); + } + Integer minimumLevel = PackIntegerChecks.integerField(enchantment, "minLevel", 1, enchantmentPath, blockingErrors); + Integer maximumLevel = PackIntegerChecks.integerField(enchantment, "maxLevel", 1, enchantmentPath, blockingErrors); + PackIntegerChecks.requireMinimum(enchantmentPath + ".minLevel", minimumLevel, 1, blockingErrors); + PackIntegerChecks.requireMinimum(enchantmentPath + ".maxLevel", maximumLevel, 1, blockingErrors); + PackIntegerChecks.requireOrdered(enchantmentPath + ".minLevel", minimumLevel, + enchantmentPath + ".maxLevel", maximumLevel, blockingErrors); + if (enchantment.has("chance")) { + Object rawChance = enchantment.opt("chance"); + if (!(rawChance instanceof Number number) + || !Double.isFinite(number.doubleValue()) + || number.doubleValue() < 0D + || number.doubleValue() > 1D) { + blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1."); + } + } + } + } + + private static void validateLootReference(String resourceType, String resourceKey, Object rawLoot, + Set lootKeys, List blockingErrors, List warnings) { + String path = resourceType + " '" + resourceKey + "'.loot"; + if (!(rawLoot instanceof JSONObject reference)) { + blockingErrors.add(path + " must be an object."); + return; + } + boolean clearMode = false; + if (reference.has("mode")) { + Object rawMode = reference.opt("mode"); + if (!(rawMode instanceof String mode) + || !Set.of("ADD", "CLEAR", "REPLACE", "FALLBACK").contains(mode)) { + blockingErrors.add(path + ".mode must be ADD, CLEAR, REPLACE, or FALLBACK."); + } else { + clearMode = "CLEAR".equals(mode); + } + } + if (reference.has("multiplier")) { + Object rawMultiplier = reference.opt("multiplier"); + if (!(rawMultiplier instanceof Number multiplier) + || !Double.isFinite(multiplier.doubleValue()) + || multiplier.doubleValue() < 0D + || multiplier.doubleValue() > IrisLootReference.MAX_MULTIPLIER) { + blockingErrors.add(path + ".multiplier must be a finite number from 0 to " + + (int) IrisLootReference.MAX_MULTIPLIER + "."); + } + } + if (!reference.has("tables")) { + return; + } + JSONArray tables = reference.optJSONArray("tables"); + if (tables == null) { + blockingErrors.add(path + ".tables must be an array."); + return; + } + if (clearMode && tables.length() > 0) { + warnings.add(path + " uses mode CLEAR and lists " + tables.length() + + " table(s); CLEAR clears parent tables and contributes no tables of its own, so these entries are dead. Use REPLACE to substitute them."); + } + for (int tableIndex = 0; tableIndex < tables.length(); tableIndex++) { + Object rawTableKey = tables.opt(tableIndex); + if (!(rawTableKey instanceof String tableKey) || tableKey.isBlank()) { + blockingErrors.add(path + ".tables[" + tableIndex + "] must name a loot table."); + } else if (!lootKeys.contains(tableKey)) { + blockingErrors.add(path + ".tables[" + tableIndex + + "] references missing loot table '" + tableKey + "'."); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java index b68abf83c..1332e3bf0 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.entity; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.engine.object.value.IRare; @@ -60,6 +61,6 @@ public class IrisEntitySpawn implements IRare { private transient IrisMarker referenceMarker; public IrisEntity getRealEntity(Engine g) { - return ent.aquire(() -> g.getData().getEntityLoader().load(getEntity())); + return ent.aquire(() -> SpawnResources.entity(g.getData(), getEntity())); } } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java index b53c9ee57..7fdcb744a 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java @@ -1,5 +1,6 @@ package art.arcane.iris.engine.object.entity.spawn; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.engine.framework.Engine; import art.arcane.volmlib.util.collection.KMap; import lombok.EqualsAndHashCode; @@ -23,7 +24,7 @@ public class IrisSpawnerCooldowns { public void cleanup(Engine engine) { cooldowns.values().removeIf(cd -> { - IrisSpawner sp = engine.getData().getSpawnerLoader().load(cd.getSpawner()); + IrisSpawner sp = SpawnResources.spawner(engine.getData(), cd.getSpawner()); return sp == null || cd.canSpawn(sp.getMaximumRate()); }); } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java index c2e7b563f..598555154 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.loot; +import art.arcane.iris.engine.loot.LootResources; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; @@ -59,7 +60,7 @@ public class IrisLootReference { KList t = new KList<>(); for (String i : tables) { - t.add(g.getData().getLootLoader().load(i)); + t.add(LootResources.table(g.getData(), i)); } return t; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 95acd4342..925db6a1a 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.blocks.ObjectMarkers; import art.arcane.iris.builtin.blocks.WrittenBlocks; @@ -196,7 +197,7 @@ public final class BlocksModule implements IrisModule { RNG markerRandom = new RNG(context.random().nextLong()); int salt = 0; for (IrisObjectMarker markerConfig : config.getMarkers()) { - IrisMarker marker = placement.object().getLoader().getMarkerLoader().load(markerConfig.getMarker()); + IrisMarker marker = SpawnResources.marker(placement.object().getLoader(), markerConfig.getMarker()); int markerSalt = salt++; if (marker == null) { continue; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java index 23b508538..f63e0fa69 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.engine.loot.LootResources; import art.arcane.iris.core.modules.ModuleSettings; import art.arcane.iris.engine.object.loot.IObjectLoot; import art.arcane.iris.engine.object.loot.IrisLootTable; @@ -301,7 +302,7 @@ public class IrisObjectPlacement { TableCache cache = new TableCache(); cache.merge(getCache(manager, getVanillaLoot(), IrisObjectPlacement::getVanillaTable)); - cache.merge(getCache(manager, getLoot(), manager.getLootLoader()::load)); + cache.merge(getCache(manager, getLoot(), key -> LootResources.table(manager, key))); return cache; }); diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index 5c9bec4f1..e4aea6f93 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -76,7 +76,7 @@ public final class EntitySpawning implements EntitySpawns { if (count <= 0) { return; } - IrisSpawner spawner = engine(world).getData().getSpawnerLoader().load(plan.spawner()); + IrisSpawner spawner = SpawnResources.spawner(engine(world).getData(), plan.spawner()); if (spawner != null) { spawner.spawn(engine(world), plan.chunkX(), plan.chunkZ()); } @@ -84,7 +84,7 @@ public final class EntitySpawning implements EntitySpawns { @Override public Optional entity(PackWorld world, String key) { - IrisEntity entity = engine(world).getData().getEntityLoader().load(key); + IrisEntity entity = SpawnResources.entity(engine(world).getData(), key); if (entity == null) { return Optional.empty(); } @@ -97,14 +97,14 @@ public final class EntitySpawning implements EntitySpawns { return Optional.empty(); } Engine engine = engine(world); - IrisMarker marker = engine.getData().getMarkerLoader().load(tag); + IrisMarker marker = SpawnResources.marker(engine.getData(), tag); if (marker == null) { return Optional.empty(); } List spawners = new ArrayList<>(); for (String key : marker.getSpawners()) { - if (engine.getData().getSpawnerLoader().load(key) == null) { + if (SpawnResources.spawner(engine.getData(), key) == null) { IrisLogging.error("Cannot load spawner: " + key + " for marker " + tag); continue; } @@ -175,8 +175,8 @@ public final class EntitySpawning implements EntitySpawns { } private Optional planMarker(PackWorld world, Engine engine, Marker marker) { - IrisSpawner spawner = engine.getData().getSpawnerLoader().load(marker.spawner()); - IrisMarker irisMarker = engine.getData().getMarkerLoader().load(marker.marker()); + IrisSpawner spawner = SpawnResources.spawner(engine.getData(), marker.spawner()); + IrisMarker irisMarker = SpawnResources.marker(engine.getData(), marker.marker()); if (spawner == null) { return Optional.empty(); } @@ -234,7 +234,7 @@ public final class EntitySpawning implements EntitySpawns { } private static KList shuffled(Engine engine, KList keys) { - return engine.getData().getSpawnerLoader().loadAll(keys).shuffleCopy(RNG.r); + return SpawnResources.spawners(engine.getData(), keys).shuffleCopy(RNG.r); } private static Stream spawnsOf(IrisSpawner spawner, boolean initial) { diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java index d0663b44f..c941d7702 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -25,7 +25,7 @@ import com.volmit.service.EntitySpawns; import com.volmit.stage.StageGraph; /** - * Module {@code iris:spawn}: the spawners, entities and markers of the pack, and the entities that appear in the world + * Module {@code iris:spawn}: the spawners, entities and markers of the pack ({@link SpawnResources}), and the entities that appear in the world * over time because of them. It has no generation stage; Iris asks it through {@link EntitySpawns} when it looks for * something to spawn in a chunk or at a marker. */ @@ -43,6 +43,7 @@ public final class SpawnModule implements IrisModule { @Override public void register(FeatureRegistry registry) { + SpawnResources.kinds().forEach(registry::registerResourceKind); registry.registerService(EntitySpawns.class, new EntitySpawning()); } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java new file mode 100644 index 000000000..b5c25a6b2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java @@ -0,0 +1,111 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +import art.arcane.iris.engine.object.marker.IrisMarker; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; + +import java.util.List; + +/** + * The resource kinds of module {@code iris:spawn}, which keep the folders and files Iris packs have always used, and + * lookups by pack key for code that still names spawners, entities and markers by key. Every lookup goes through the + * pack's {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot. + *

+ * Lookups answer null where Iris's loaders did: for a blank key, a key the pack has no file for, and a file that fails + * to load, which was reported when it was read. + */ +public final class SpawnResources { + /** Spawners, in {@code spawners/}. */ + public static final ResourceKind SPAWNERS = ResourceKind.of("iris:spawn/spawner", "spawners", IrisSpawner.class); + /** Entities, in {@code entities/}. */ + public static final ResourceKind ENTITIES = ResourceKind.of("iris:spawn/entity", "entities", IrisEntity.class); + /** Markers, in {@code markers/}. */ + public static final ResourceKind MARKERS = ResourceKind.of("iris:spawn/marker", "markers", IrisMarker.class); + + private SpawnResources() { + } + + /** Every resource kind of the spawn module. */ + public static List> kinds() { + return List.of(SPAWNERS, ENTITIES, MARKERS); + } + + public static IrisSpawner spawner(IrisData data, String key) { + return find(data, SPAWNERS, key); + } + + public static IrisEntity entity(IrisData data, String key) { + return find(data, ENTITIES, key); + } + + public static IrisMarker marker(IrisData data, String key) { + return find(data, MARKERS, key); + } + + /** The spawners of the pack named by {@code keys}, in order, without the ones the pack lacks. */ + public static KList spawners(IrisData data, List keys) { + KList spawners = new KList<>(); + for (String key : keys) { + IrisSpawner spawner = spawner(data, key); + if (spawner != null) { + spawners.add(spawner); + } + } + return spawners; + } + + /** The key of every entity of the pack, in key order. */ + public static List entityKeys(IrisData data) { + return keys(data, ENTITIES); + } + + /** The key of every spawner of the pack, in key order. */ + public static List spawnerKeys(IrisData data) { + return keys(data, SPAWNERS); + } + + /** The key of every marker of the pack, in key order. */ + public static List markerKeys(IrisData data) { + return keys(data, MARKERS); + } + + private static T find(IrisData data, ResourceKind kind, String key) { + if (key == null || key.isBlank()) { + return null; + } + IrisPackResources resources = data.getPackResources(); + try { + return resources.find(kind.key(resources.idOf(key))).orElse(null); + } catch (IllegalStateException failedToLoad) { + return null; + } + } + + /** A key's id has the key as its path, so the path names the resource again wherever a key is expected. */ + private static List keys(IrisData data, ResourceKind kind) { + return data.getPackResources().ids(kind.type()).stream().map(ResourceId::path).toList(); + } +} From 4735477918967b304ea130827b65789a71b1e49a Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:26:05 +0200 Subject: [PATCH 7/7] README: iris:loot, iris:spawn and the new services of iris:objects; tree species by name --- README.md | 8 ++++++++ .../arcane/iris/engine/mantle/components/TreeGrowing.java | 8 +++----- .../iris/engine/object/placement/IrisObjectPlacement.java | 5 +++++ 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 8de696f27..b51dcd8c5 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,14 @@ provides `ObjectsAt` (the objects a chunk would get, for the object search and s provides `StructureLocator` (`StructureLocating`: the pack's structure keys for Iris's structure index, the ones a world places, and their nearest start for the find commands). `iris:structure` also has a lifecycle hook that drops a world's structure index when the world stops, which includes every reload of the pack's structure files. +`iris:objects` also provides `SaplingGrowth` (`TreeGrowing`: the tree a sapling grows into, as placed blocks, and which +objects are trees) and says which biomes and regions place an object (`ObjectLocating`, for the object search). +`iris:loot` owns the loot table resource kind (`LootResources`, folder `loot`), checks the tables and the references to +them (`LootValidator`), and provides `Loot` (`LootGiving`: which tables a container draws from and the `ItemDrop`s a +table gives) and `BlockDrops` (`BlockDropping`). `iris:spawn` owns spawners, entities and markers (`SpawnResources`, +folders `spawners`, `entities`, `markers`) and provides `EntitySpawns` (`EntitySpawning`: what to spawn in a chunk or at +a marker, as `EntitySpec`s; `EntityResolution` makes the entity's random choices). Iris's Bukkit code creates the items +and entities from those values (`BukkitItemStacks`, `BukkitEntitySpawner`). `iris:decorant` keeps its per-world `Decorating` in the world's state store (`context.world().state(...)`); the other built-ins still reach the same store through `IrisChunk.state(...)` / `engine.getGeneration().state(...)`. diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 1bcfe3226..40dee1a6d 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -41,7 +41,6 @@ import com.volmit.placement.PlacedBlock; import com.volmit.service.SaplingGrowth; import com.volmit.world.BlockPosition; import com.volmit.world.PackWorld; -import org.bukkit.TreeType; import java.util.ArrayList; import java.util.HashSet; @@ -100,19 +99,18 @@ public final class TreeGrowing implements SaplingGrowth { /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species; null for none. */ private static IrisObjectPlacement pickPlacement(Engine engine, Sapling sapling) { - TreeType species = TreeType.valueOf(sapling.species()); KList placements = new KList<>(); boolean useAll = engine.getDimension().getTreeSettings().getMode().equals(IrisTreeModes.ALL); BlockPosition at = sapling.at(); - placements.addAll(matching(engine.getBiome(at.x(), at.y(), at.z()).getObjects(), species)); + placements.addAll(matching(engine.getBiome(at.x(), at.y(), at.z()).getObjects(), sapling.species())); if (useAll || placements.isEmpty()) { - placements.addAll(matching(engine.getRegion(at.x(), at.z()).getObjects(), species)); + placements.addAll(matching(engine.getRegion(at.x(), at.z()).getObjects(), sapling.species())); } return placements.isNotEmpty() ? placements.getRandom() : null; } - private static KList matching(KList objects, TreeType species) { + private static KList matching(KList objects, String species) { KList matches = new KList<>(); for (IrisObjectPlacement placement : objects) { if (placement.matches(SAPLING_SIZE, species)) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java index f63e0fa69..3b6559a38 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -272,6 +272,11 @@ public class IrisObjectPlacement { return g.getData().getObjectLoader().load(place.get(random.nextInt(place.size()))); } + /** Whether a tree placement grows the species the platform calls {@code species} for a sapling area of {@code size}. */ + public boolean matches(IrisTreeSize size, String species) { + return matches(size, TreeType.valueOf(species)); + } + public boolean matches(IrisTreeSize size, TreeType type) { for (IrisTree i : getTrees()) { if (i.matches(size, type)) {