Compare commits

...
9 Commits
Author SHA1 Message Date
Brian Fopiano e3b595a712 Size palette layer caches
- Hold every depth seed of a layer's thickness
- Widen lock-free recent slots to cover consecutive depth seeds
- Share one generator for seeded palette layer styles
- Test cached depth generators against fresh builds
2026-12-03 10:42:50 -05:00
Brian Fopiano ecc4413d19 Type expression loader explicitly
- Replace var with ResourceLoader<IrisExpression> in style check
2026-12-03 10:22:52 -05:00
_Saros_ c7a2af98a5 Share seed-free expression layer generators
- Reuse one generator for seed-independent expression layers
- Check expression variables and functions for seed use
- Test sharing, seeded nesting and cyclic references
2026-12-03 10:22:16 -05:00
Brian Fopiano 94648946d9 Drop packedCompactPayload
- Remove the line; the compact payload is the only format
2026-12-01 10:37:26 -05:00
Brian Fopiano ba9694083b Adopt packaging standard
- Ship the Bukkit runtime as a compact payload
- Drop packaging lines that now match the plugin defaults
- Verify native providers from PackedJar.readRuntime entries
- Remove the unused xz dependency from buildSrc
- Drop hand-written META-INF/maven excludes in mod builds
- Keep native boundary checks on in the mod adapters
2026-12-01 08:28:43 -05:00
Brian Fopiano 02f6379808 Import SurvivalAnswer from block
- Follow SurvivalAnswer to the VolmLib nativelib block package
2026-11-30 15:40:36 -05:00
Piexel f7084b244f Let the server decide where plants stand
- Ask the native canSurvive rule in BukkitBlockState.canPlaceOnto
- Fall back to the block table when the rule cannot answer
- Clear remembered answers on resource and CraftEngine reloads
- Drop the post stage foliage check that never saw decorations
- Test vanilla placement rules, fallbacks and concurrent lookups
2026-11-30 11:06:48 -05:00
Brian Fopiano 1bc7843a52 Move CodeMC repo to codemc.io
- Replace dead repo.codemc.org host with repo.codemc.io
- Fixes runtime download of paralithic on fresh installs
2026-11-30 08:04:09 -05:00
Brian Fopiano b0b6e54d2d Match bed rule key to version
- Write explodes for 26.1.2 and 26.2 bed rules
- Rename explodes to destroy_on_use on 26.3
- Test bed rules for both fixer versions
2026-11-29 05:06:51 -05:00
20 changed files with 688 additions and 92 deletions

No files matched your search

@@ -0,0 +1,262 @@
package art.arcane.iris.probe;
import art.arcane.volmlib.nativelib.common.block.GroundSurvival;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.ModdedBlockState;
import art.arcane.volmlib.nativelib.block.SurvivalAnswer;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** Both platforms ask the server's own canSurvive rule where a plant may stand, against the real block tags. */
public final class HeadlessGroundSurvivalTest {
private static final Logger NATIVE_LOG = Logger.getLogger("VolmLib-Native");
@BeforeClass
public static void bootstrap() {
HeadlessNativeBootstrap.initialize();
}
@Test
public void grassStandsOnSoilButNotOnStone() {
assertPlacement(true, Blocks.SHORT_GRASS, Blocks.GRASS_BLOCK);
assertPlacement(true, Blocks.SHORT_GRASS, Blocks.PODZOL);
assertPlacement(false, Blocks.SHORT_GRASS, Blocks.STONE);
assertPlacement(false, Blocks.POPPY, Blocks.STONE);
assertPlacement(false, Blocks.FERN, Blocks.OAK_LEAVES);
}
@Test
public void cactusNeedsSandOrCactus() {
for (Block ground : new Block[]{Blocks.CACTUS, Blocks.SAND, Blocks.RED_SAND}) {
assertPlacement(true, Blocks.CACTUS, ground);
}
assertPlacement(false, Blocks.CACTUS, Blocks.STONE);
}
@Test
public void sugarCaneNeedsItsSubstrate() {
for (Block ground : new Block[]{Blocks.SUGAR_CANE, Blocks.GRASS_BLOCK, Blocks.DIRT, Blocks.COARSE_DIRT,
Blocks.PODZOL, Blocks.MYCELIUM, Blocks.ROOTED_DIRT, Blocks.MOSS_BLOCK, Blocks.PALE_MOSS_BLOCK,
Blocks.MUD, Blocks.MUDDY_MANGROVE_ROOTS, Blocks.SAND, Blocks.RED_SAND, Blocks.SUSPICIOUS_SAND}) {
assertPlacement(true, Blocks.SUGAR_CANE, ground);
}
for (Block ground : new Block[]{Blocks.STONE, Blocks.GRAVEL, Blocks.CLAY, Blocks.DIRT_PATH,
Blocks.FARMLAND, Blocks.AIR, Blocks.WATER}) {
assertPlacement(false, Blocks.SUGAR_CANE, ground);
}
}
@Test
public void netherGroundCoverAcceptsNyliumAndSoulSoilButRejectsBarrenBlocks() {
for (Block plant : new Block[]{Blocks.CRIMSON_ROOTS, Blocks.WARPED_ROOTS, Blocks.NETHER_SPROUTS}) {
for (Block ground : new Block[]{Blocks.CRIMSON_NYLIUM, Blocks.WARPED_NYLIUM, Blocks.SOUL_SOIL}) {
assertPlacement(true, plant, ground);
}
for (Block ground : new Block[]{Blocks.NETHERRACK, Blocks.STONE, Blocks.GRAVEL, Blocks.AIR}) {
assertPlacement(false, plant, ground);
}
}
}
@Test
public void blocksThatRestOnNoGroundStillFit() {
assertPlacement(true, Blocks.WALL_TORCH, Blocks.STONE);
assertPlacement(true, Blocks.VINE, Blocks.SAND);
assertPlacement(true, Blocks.COCOA, Blocks.STONE);
}
@Test
public void deadBushStaysOffGrassAsPacksExpect() {
assertPlacement(true, Blocks.DEAD_BUSH, Blocks.SAND);
assertPlacement(false, Blocks.DEAD_BUSH, Blocks.GRASS_BLOCK);
}
@Test
public void nothingStandsOnAir() {
assertPlacement(false, Blocks.VINE, Blocks.AIR);
assertPlacement(false, Blocks.SHORT_GRASS, Blocks.CAVE_AIR);
}
@Test
public void plantsThatReadMoreOfTheLevelAreAnsweredByTheirOwnRule() {
List<LogRecord> warnings = warningsDuring(() -> {
assertPlacement(true, Blocks.BAMBOO, Blocks.GRASS_BLOCK);
assertPlacement(false, Blocks.BAMBOO, Blocks.STONE);
assertPlacement(true, Blocks.KELP, Blocks.STONE);
assertPlacement(false, Blocks.KELP, Blocks.MAGMA_BLOCK);
assertPlacement(true, Blocks.SEAGRASS, Blocks.SAND);
assertPlacement(false, Blocks.SEAGRASS, Blocks.MAGMA_BLOCK);
assertPlacement(true, Blocks.LILY_PAD, Blocks.WATER);
assertPlacement(false, Blocks.LILY_PAD, Blocks.STONE);
assertPlacement(true, Blocks.SWEET_BERRY_BUSH, Blocks.GRASS_BLOCK);
assertPlacement(false, Blocks.SWEET_BERRY_BUSH, Blocks.STONE);
assertPlacement(true, Blocks.BROWN_MUSHROOM, Blocks.STONE);
assertPlacement(true, Blocks.RED_MUSHROOM, Blocks.MYCELIUM);
assertPlacement(false, Blocks.BROWN_MUSHROOM, Blocks.GLASS);
assertPlacement(true, Blocks.CRIMSON_FUNGUS, Blocks.CRIMSON_NYLIUM);
assertPlacement(false, Blocks.WARPED_FUNGUS, Blocks.NETHERRACK);
assertPlacement(true, Blocks.WHEAT, Blocks.FARMLAND);
assertPlacement(false, Blocks.CARROTS, Blocks.DIRT);
});
assertEquals(messages(warnings), 0, warnings.size());
}
@Test
public void everyVanillaBlockIsAnsweredWithoutFailingOpen() {
GroundSurvival survival = new GroundSurvival();
List<LogRecord> warnings = warningsDuring(() -> {
for (Block plant : BuiltInRegistries.BLOCK) {
if (needsARunningPaperServer(plant)) {
continue;
}
for (Block ground : new Block[]{Blocks.GRASS_BLOCK, Blocks.STONE, Blocks.WATER}) {
survival.canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState());
}
}
});
assertEquals(messages(warnings), 0, warnings.size());
}
@Test
public void aRuleThatThrowsIsLeftUnansweredAndWarnsOncePerBlock() {
BlockState firstState = throwingStateOf(Blocks.SHORT_GRASS);
BlockState secondState = throwingStateOf(Blocks.SHORT_GRASS);
GroundSurvival survival = new GroundSurvival();
List<LogRecord> warnings = warningsDuring(() -> {
for (BlockState plant : new BlockState[]{firstState, secondState}) {
for (Block ground : new Block[]{Blocks.STONE, Blocks.SAND, Blocks.GRASS_BLOCK}) {
assertEquals(SurvivalAnswer.UNANSWERED, survival.canSurviveOn(plant, ground.defaultBlockState()));
}
}
});
assertEquals(messages(warnings), 1, warnings.size());
}
@Test
public void aRuleThatThrowsFallsBackToThePlacementTable() {
ModdedBlockState grass = ModdedBlockState.deferred(throwingStateOf(Blocks.SHORT_GRASS), Map.of(), "iris:test");
warningsDuring(() -> {
assertTrue(grass.canPlaceOnto(wrap(Blocks.GRASS_BLOCK)));
assertFalse(grass.canPlaceOnto(wrap(Blocks.STONE)));
});
}
@Test
public void aRuleThatOnlyAnswersForSomeGroundsDoesNotPassAsAWallBlock() {
BlockState plant = mock(BlockState.class);
when(plant.getBlock()).thenReturn(Blocks.SHORT_GRASS);
when(plant.canSurvive(any(), any())).thenAnswer(asked -> {
LevelReader level = asked.getArgument(0);
BlockPos plantPos = asked.getArgument(1);
if (level.getBlockState(plantPos.below()).is(Blocks.STONE)) {
return false;
}
throw new IllegalStateException("custom rule failed");
});
GroundSurvival survival = new GroundSurvival();
warningsDuring(() -> assertEquals(SurvivalAnswer.UNANSWERED,
survival.canSurviveOn(plant, Blocks.STONE.defaultBlockState())));
}
@Test
public void generatorThreadsAskingAtOnceGetTheSameAnswers() {
Block[] plants = {Blocks.SHORT_GRASS, Blocks.CACTUS, Blocks.SUGAR_CANE, Blocks.VINE, Blocks.BROWN_MUSHROOM};
Block[] grounds = {Blocks.GRASS_BLOCK, Blocks.SAND, Blocks.STONE, Blocks.WATER};
GroundSurvival alone = new GroundSurvival();
GroundSurvival shared = new GroundSurvival();
List<Integer> threads = Arrays.asList(new Integer[16]);
threads.parallelStream().forEach(ignored -> {
for (Block plant : plants) {
for (Block ground : grounds) {
assertEquals(plant + " on " + ground,
alone.canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState()),
shared.canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState()));
}
}
});
}
// Paper's chorus plant reads Paper's global configuration, which only a running server loads.
private static boolean needsARunningPaperServer(Block plant) {
return plant == Blocks.CHORUS_PLANT;
}
private static BlockState throwingStateOf(Block block) {
BlockState state = mock(BlockState.class);
when(state.getBlock()).thenReturn(block);
when(state.isSingletonState()).thenReturn(true);
when(state.canSurvive(any(), any())).thenThrow(new IllegalStateException("custom rule failed"));
return state;
}
private static void assertPlacement(boolean expected, Block plant, Block ground) {
String pair = plant + " on " + ground;
assertEquals("modded " + pair, expected, moddedPlacement(plant, ground));
assertEquals("bukkit native " + pair, expected ? SurvivalAnswer.SURVIVES : SurvivalAnswer.FAILS,
new GroundSurvival().canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState()));
}
private static boolean moddedPlacement(Block plant, Block ground) {
return wrap(plant).canPlaceOnto(wrap(ground));
}
private static ModdedBlockState wrap(Block block) {
return ModdedBlockState.deferred(block.defaultBlockState(), Map.of(), "iris:test");
}
private static List<LogRecord> warningsDuring(Runnable checks) {
List<LogRecord> warnings = new CopyOnWriteArrayList<>();
Handler capture = new Handler() {
@Override
public void publish(LogRecord record) {
if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
warnings.add(record);
}
}
@Override
public void flush() {
}
@Override
public void close() {
}
};
NATIVE_LOG.addHandler(capture);
try {
checks.run();
} finally {
NATIVE_LOG.removeHandler(capture);
}
return warnings;
}
private static String messages(List<LogRecord> warnings) {
StringBuilder text = new StringBuilder();
for (LogRecord warning : warnings) {
text.append(warning.getMessage()).append(" (").append(warning.getThrown()).append(")\n");
}
return text.toString();
}
}
@@ -58,6 +58,7 @@ import art.arcane.iris.platform.agent.AttachSignal;
import art.arcane.iris.platform.bootstrap.Bindings;
import art.arcane.iris.platform.bootstrap.ServerProperties;
import art.arcane.iris.platform.bootstrap.SlimJar;
import art.arcane.iris.platform.bukkit.BlockRulesSVC;
import art.arcane.iris.platform.bukkit.BoardSVC;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.platform.bukkit.api.IrisApiEventSVC;
@@ -681,6 +682,7 @@ public final class IrisRuntime implements IrisPluginRuntime {
new GlobalCacheSVC(),
new LogFilterSVC(),
new ExternalDataSVC(),
new BlockRulesSVC(),
new EditSVC(),
new ObjectSVC(),
new ObjectStudioSaveService(),
@@ -0,0 +1,24 @@
package art.arcane.iris.platform.bukkit;
import art.arcane.iris.platform.bukkit.nms.INMS;
import art.arcane.iris.platform.bukkit.plugin.IrisService;
import io.papermc.paper.event.server.ServerResourcesReloadedEvent;
import org.bukkit.event.EventHandler;
/** Lets the server's placement rules apply again after a resource reload, which may have changed the block tags they read. */
public class BlockRulesSVC implements IrisService {
@Override
public void onEnable() {
}
@Override
public void onDisable() {
}
@EventHandler
public void onResourcesReloaded(ServerResourcesReloadedEvent event) {
if (INMS.isBound()) {
INMS.get().forgetBlockRules();
}
}
}
+2 -2
View File
@@ -104,7 +104,7 @@ repositories {
name = 'FabricMC'
url = uri('https://maven.fabricmc.net/')
}
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
maven { url = uri('https://jitpack.io') }
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
}
@@ -331,7 +331,6 @@ tasks.named('shadowJar', ShadowJar).configure {
if ((int) irisModTarget.java == 21) {
exclude(java21RuntimeExclusions)
}
exclude('META-INF/maven/**')
exclude('META-INF/proguard/**')
exclude('META-INF/*.SF')
exclude('META-INF/*.DSA')
@@ -415,6 +414,7 @@ tasks.named('assemble').configure {
}
pluginPackaging {
nativeBoundaryChecks = true
artifacts {
create('distribution') {
taskName = irisModTarget.fabricRemap ? 'remapJar' : 'shadowJar'
+2 -2
View File
@@ -121,7 +121,7 @@ repositories {
maven fg.forgeMaven
maven fg.minecraftLibsMaven
mavenCentral()
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
maven { url = uri('https://jitpack.io') }
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
}
@@ -320,7 +320,6 @@ tasks.named('shadowJar', ShadowJar).configure {
if ((int) irisModTarget.java == 21) {
exclude(java21RuntimeExclusions)
}
exclude('META-INF/maven/**')
exclude('META-INF/proguard/**')
exclude('META-INF/*.SF')
exclude('META-INF/*.DSA')
@@ -377,6 +376,7 @@ tasks.named('assemble').configure {
}
pluginPackaging {
nativeBoundaryChecks = true
artifacts {
create('distribution') {
taskName = 'shadowJar'
+2 -2
View File
@@ -105,7 +105,7 @@ repositories {
name = 'NeoForged'
url = uri('https://maven.neoforged.net/releases/')
}
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
maven { url = uri('https://jitpack.io') }
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
}
@@ -304,7 +304,6 @@ tasks.named('shadowJar', ShadowJar).configure {
if ((int) irisModTarget.java == 21) {
exclude(java21RuntimeExclusions)
}
exclude('META-INF/maven/**')
exclude('META-INF/proguard/**')
exclude('META-INF/*.SF')
exclude('META-INF/*.DSA')
@@ -361,6 +360,7 @@ tasks.named('assemble').configure {
}
pluginPackaging {
nativeBoundaryChecks = true
artifacts {
create('distribution') {
taskName = 'shadowJar'
+7 -8
View File
@@ -1,5 +1,4 @@
import art.arcane.volmit.packaging.PackedJar
import art.arcane.volmit.packaging.PackagingMode
import art.arcane.volmit.packaging.NativeDevelopmentTargets
import io.papermc.paperweight.userdev.PaperweightUser
import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension
@@ -654,7 +653,7 @@ allprojects {
repositories {
mavenCentral()
maven { url = uri('https://repo.papermc.io/repository/maven-public/') }
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
maven {
url = uri('https://jitpack.io')
@@ -759,11 +758,6 @@ pluginPackaging {
packedJarAccessors = ['art/arcane/iris/platform/bukkit/plugin/VolmitPlugin#getJarFile']
packedPayloadOnlyPrefixes = ['iris-language-guides/', 'META-INF/iris/generation-kernels/abi-', 'iris/icons/views/', 'iris/datapack/']
packedMaximumBootstrapClasses = 90
stripDirectories = true
stripLocalVariables = true
releaseCompression = providers.gradleProperty('compactRelease')
.map { String value -> value.toBoolean() }
.getOrElse(!PackagingMode.resolve(providers).development())
prunePrefixes = ['art/arcane/volmlib/']
keepPrefixes = ['art/arcane/volmlib/util/matter/slices/', 'art/arcane/volmlib/nativelib/']
shrinkRules = [file('packaging/shrink.pro'), nativeRuntimeRules.get().asFile]
@@ -1010,7 +1004,12 @@ tasks.withType(PackedJar).configureEach {
dependsOn(tasks.named('verifyBukkitArtifact'), nativeRuntime)
nativeArtifacts.set(providers.provider { embeddedNatives() })
doLast { PackedJar task ->
NativeRuntimeArtifacts.verifyPacked(task.outputJar.get().asFile, nativeRuntimeModules, embeddedNatives())
File artifact = task.outputJar.get().asFile
Map<String, byte[]> outer = NativeRuntimeArtifacts.entries(artifact)
Map<String, byte[]> runtime = outer.containsKey('META-INF/volmit/runtime.properties')
? PackedJar.readRuntime(artifact.toPath()) : outer
NativeRuntimeArtifacts.verifyPacked(runtime, outer.get(NativeRuntimeArtifacts.MANIFEST), nativeRuntimeModules,
embeddedNatives())
}
}
-1
View File
@@ -35,7 +35,6 @@ dependencies {
implementation(gradleApi())
implementation('org.ow2.asm:asm:9.10.1')
implementation('org.apache.commons:commons-compress:1.28.0')
implementation('org.tukaani:xz:1.10')
implementation('io.papermc.paperweight:paperweight-userdev:2.0.0-beta.21')
testImplementation('junit:junit:4.13.2')
}
@@ -1,5 +1,4 @@
import org.gradle.api.GradleException;
import org.tukaani.xz.XZInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -28,7 +27,6 @@ import java.util.zip.ZipInputStream;
public final class NativeRuntimeArtifacts {
public static final String MANIFEST = "META-INF/iris/native-runtime.properties";
public static final String RESOURCES = "META-INF/iris/native/";
private static final String PAYLOAD = "META-INF/volmit/runtime.jar.xz";
private static final String GROUP = "com.github.VolmitSoftware.VolmLib";
private static final String NATIVE = "art/arcane/volmlib/nativelib/";
@@ -99,35 +97,20 @@ public final class NativeRuntimeArtifacts {
}
}
public static void verifyPacked(File artifact, List<String> modules, Map<String, File> natives) throws IOException {
/** Checks the native providers inside {@code runtime}, the entries the plugin runs from, against the resolved build. */
public static void verifyPacked(Map<String, byte[]> runtime, byte[] outerManifest, List<String> modules,
Map<String, File> natives) throws IOException {
requireModules(natives, modules);
Map<String, byte[]> contents;
try (JarFile jar = new JarFile(artifact)) {
JarEntry payload = jar.getJarEntry(PAYLOAD);
if (payload == null) {
contents = read(Files.newInputStream(artifact.toPath()));
} else {
try (InputStream input = new XZInputStream(jar.getInputStream(payload))) {
contents = read(new ByteArrayInputStream(input.readAllBytes()));
}
JarEntry outer = jar.getJarEntry(MANIFEST);
byte[] embedded = contents.get(MANIFEST);
if (outer != null && embedded != null) {
try (InputStream input = jar.getInputStream(outer)) {
if (!Arrays.equals(input.readAllBytes(), embedded)) {
throw new GradleException("Packed native runtime manifests differ");
}
}
}
}
}
byte[] manifest = contents.get(MANIFEST);
byte[] manifest = runtime.get(MANIFEST);
if (manifest == null) {
throw new GradleException("Missing native runtime dependency manifest");
}
if (outerManifest != null && !Arrays.equals(outerManifest, manifest)) {
throw new GradleException("Packed native runtime manifests differ");
}
verifyManifest(manifest, natives);
for (String module : natives.keySet()) {
byte[] provider = contents.get(RESOURCES + module + ".jar");
byte[] provider = runtime.get(RESOURCES + module + ".jar");
if (provider == null) {
throw new GradleException("Missing embedded native provider: " + module);
}
@@ -137,6 +120,18 @@ public final class NativeRuntimeArtifacts {
}
}
public static Map<String, byte[]> entries(File artifact) throws IOException {
Map<String, byte[]> contents = new TreeMap<>();
try (ZipInputStream archive = new ZipInputStream(Files.newInputStream(artifact.toPath()))) {
for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
if (!entry.isDirectory()) {
contents.put(entry.getName(), archive.readAllBytes());
}
}
}
return contents;
}
private static void verifyManifest(byte[] bytes, Map<String, File> natives) throws IOException {
Properties manifest = new Properties();
manifest.load(new ByteArrayInputStream(bytes));
@@ -163,18 +158,6 @@ public final class NativeRuntimeArtifacts {
}
}
private static Map<String, byte[]> read(InputStream source) throws IOException {
Map<String, byte[]> contents = new TreeMap<>();
try (ZipInputStream archive = new ZipInputStream(source)) {
for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
if (!entry.isDirectory()) {
contents.put(entry.getName(), archive.readAllBytes());
}
}
}
return contents;
}
private static boolean implementation(String name) {
if (!name.startsWith(NATIVE)) {
return false;
@@ -4,13 +4,11 @@ import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.tukaani.xz.LZMA2Options;
import org.tukaani.xz.XZOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
@@ -22,6 +20,7 @@ import java.util.TreeMap;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
@@ -89,15 +88,35 @@ public class NativeRuntimeArtifactsTest {
public void verifiesTheEmbeddedProviderBytesInsideThePackedRuntime() throws Exception {
Map<String, File> natives = natives();
Map<String, byte[]> runtime = runtime(natives, natives);
NativeRuntimeArtifacts.verifyPacked(packed(runtime), MODULES, natives);
NativeRuntimeArtifacts.verifyPacked(jar("ordinary.jar", runtime), MODULES, natives);
byte[] manifest = runtime.get(NativeRuntimeArtifacts.MANIFEST);
NativeRuntimeArtifacts.verifyPacked(runtime, manifest, MODULES, natives);
NativeRuntimeArtifacts.verifyPacked(runtime, null, MODULES, natives);
Map<String, File> rebuilt = new TreeMap<>(natives);
rebuilt.put("native-v26_2_R1", provider("rebuilt.jar", "art/arcane/volmlib/util/collection/KMap"));
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(packed(runtime(natives, rebuilt)),
MODULES, natives));
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(runtime(natives, rebuilt),
manifest, MODULES, natives));
Map<String, byte[]> missing = new TreeMap<>(runtime);
missing.remove(NativeRuntimeArtifacts.RESOURCES + "native-v26_2_R1.jar");
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(packed(missing), MODULES, natives));
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(missing, manifest, MODULES, natives));
}
@Test
public void rejectsAnOuterManifestThatDiffersFromTheRuntimeOne() throws Exception {
Map<String, File> natives = natives();
Map<String, byte[]> runtime = runtime(natives, natives);
byte[] outer = (new String(runtime.get(NativeRuntimeArtifacts.MANIFEST), StandardCharsets.UTF_8) + "extra=1\n")
.getBytes(StandardCharsets.UTF_8);
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(runtime, outer, MODULES, natives));
}
@Test
public void readsEveryFileEntryOfAnOrdinaryJar() throws Exception {
Map<String, byte[]> runtime = runtime(natives(), natives());
Map<String, byte[]> read = NativeRuntimeArtifacts.entries(jar("ordinary.jar", runtime));
assertEquals(runtime.keySet(), read.keySet());
for (Map.Entry<String, byte[]> entry : runtime.entrySet()) {
assertArrayEquals(entry.getValue(), read.get(entry.getKey()));
}
}
private Map<String, File> natives() throws IOException {
@@ -137,17 +156,6 @@ public class NativeRuntimeArtifactsTest {
return contents;
}
private File packed(Map<String, byte[]> runtime) throws IOException {
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
try (XZOutputStream xz = new XZOutputStream(compressed, new LZMA2Options(1))) {
xz.write(Files.readAllBytes(jar("payload.jar", runtime).toPath()));
}
Map<String, byte[]> outer = new TreeMap<>();
outer.put(NativeRuntimeArtifacts.MANIFEST, runtime.get(NativeRuntimeArtifacts.MANIFEST));
outer.put("META-INF/volmit/runtime.jar.xz", compressed.toByteArray());
return jar("packed.jar", outer);
}
private File jar(String name, Map<String, byte[]> contents) throws IOException {
Path file = temporary.newFolder().toPath().resolve(name);
try (JarOutputStream jar = new JarOutputStream(Files.newOutputStream(file))) {
@@ -18,27 +18,37 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.noise.CNG;
/**
* What one engine derives from an {@link IrisBiomePaletteLayer}: the block selection and depth generators of the
* seeds that sample it.
* seeds that sample it. A column walk asks for one layer seed per depth, so the layer table holds the layer's whole
* thickness for a few parent seeds instead of rebuilding a generator on every depth step.
*/
public final class PaletteLayerRuntime {
private static final int LAYER_SEED_CAPACITY = 32;
private static final int LAYER_RECENT_SLOTS = 32;
private static final int MAX_LAYER_RECENT_SLOTS = 4096;
private static final int PARENT_SEEDS_PER_LAYER = 4;
private static final int HEIGHT_SEED_CAPACITY = 32;
private final PackRuntime runtime;
private final SeedTable<CNG> layerGenerators;
private final SeedTable<CNG> heightGenerators;
private final boolean shareGenerator;
public PaletteLayerRuntime(IrisBiomePaletteLayer layer, PackRuntime runtime) {
this.runtime = runtime;
this.layerGenerators = new SeedTable<>(LAYER_SEED_CAPACITY, LAYER_RECENT_SLOTS,
seed -> layer.createLayerGenerator(seed, runtime));
IrisGeneratorStyle style = layer.getStyle();
// A seeded style rolls from its own seed and the world seed, never the caller's, so every depth builds the same noise.
this.shareGenerator = style != null
&& (style.isSeeded() || style.canShareExpressionGenerator(runtime.data()));
int depthSeeds = Math.max(1, Math.max(layer.getMinHeight(), layer.getMaxHeight()));
this.layerGenerators = new SeedTable<>(Math.max(LAYER_SEED_CAPACITY, depthSeeds * PARENT_SEEDS_PER_LAYER),
recentSlots(depthSeeds), seed -> layer.createLayerGenerator(seed, runtime));
this.heightGenerators = new SeedTable<>(HEIGHT_SEED_CAPACITY, IrisBiomePaletteLayer::createHeightGenerator);
}
@@ -48,10 +58,16 @@ public final class PaletteLayerRuntime {
}
public CNG layerGenerator(long seed) {
return layerGenerators.get(seed);
return layerGenerators.get(shareGenerator ? 0L : seed);
}
public CNG heightGenerator(long seed) {
return heightGenerators.get(seed);
}
/** Consecutive depth seeds land in distinct slots when the slot count covers the thickness. */
private static int recentSlots(int depthSeeds) {
int covering = Integer.highestOneBit(Math.min(depthSeeds, MAX_LAYER_RECENT_SLOTS) - 1) << 1;
return Math.clamp(covering, LAYER_RECENT_SLOTS, MAX_LAYER_RECENT_SLOTS);
}
}
@@ -21,6 +21,7 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.image.IrisImageMap;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.ResourceLoader;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.world.history.GenerationKernelRegistry;
@@ -42,7 +43,9 @@ import lombok.experimental.Accessors;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Snippet("style")
@@ -99,6 +102,46 @@ public class IrisGeneratorStyle {
return createNoCache(rng, runtime, 1, 0, false);
}
/**
* Whether this style can share an expression generator across caller seeds within a pack runtime.
*/
public boolean canShareExpressionGenerator(IrisData data) {
return expression != null && canShareExpressionGenerator(data, new HashSet<>());
}
private boolean canShareExpressionGenerator(IrisData data, Set<String> activeExpressions) {
if (getClass() != IrisGeneratorStyle.class || expression == null || data == null
|| fracture != null || cellularFrequency != 0D || cacheSize != 0
|| !activeExpressions.add(expression)) {
return false;
}
try {
ResourceLoader<IrisExpression> loader = data.getExpressionLoader();
IrisExpression source = loader == null ? null : loader.load(expression);
if (source == null || source.getClass() != IrisExpression.class
|| source.getVariables() == null || source.getFunctions() == null) {
return false;
}
for (IrisExpressionLoad variable : source.getVariables()) {
if (variable.getEngineValue() != null || variable.getEngineStreamValue() != null
|| (variable.getStyleValue() != null
&& !variable.getStyleValue().canShareExpressionGenerator(data, activeExpressions))) {
return false;
}
}
for (IrisExpressionFunction function : source.getFunctions()) {
if (function.getEngineStreamValue() != null || function.getStyleValue() == null
|| !function.getStyleValue().canShareExpressionGenerator(data, activeExpressions)) {
return false;
}
}
return true;
} finally {
activeExpressions.remove(expression);
}
}
public CNG createScaledGenerator(RNG rng, PackRuntime runtime, double scaleFactor) {
return createNoCache(rng, runtime).bake().scale(scaleFactor).bake();
}
@@ -300,14 +300,6 @@ public class IrisPostModifier extends EngineAssignedModifier<NativeBlockState> {
setPostBlock(x, h + 1, z, result, originX, originZ, currentData);
}
}
if (B.isFoliage(b) || IrisProceduralBlocks.materialKey(b).equals("minecraft:dead_bush")) {
NativeBlockState onto = getPostBlock(x, h, z, originX, originZ, currentData);
if (!B.canPlaceOnto(b, onto) && !B.isDecorant(b)) {
setPostBlock(x, h + 1, z, AIR.get(), originX, originZ, currentData);
}
}
}
public boolean isAir(int x, int y, int z, int originX, int originZ, Hunk<NativeBlockState> currentData) {
@@ -8,6 +8,7 @@ import art.arcane.iris.integration.ExternalDataSVC;
import art.arcane.iris.generation.cache.Cache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.platform.bukkit.nms.INMS;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.generation.block.IrisCustomData;
@@ -83,6 +84,7 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis
@EventHandler
public void onReload(CraftEngineReloadEvent event) {
forgetServerBlockRules();
if (!updateContent()) {
return;
}
@@ -92,6 +94,13 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis
}
}
// Custom blocks carry their own placement rules, so answers about them can change with a reload.
private static void forgetServerBlockRules() {
if (INMS.isBound()) {
INMS.get().forgetBlockRules();
}
}
@Override
public @NotNull List<BlockProperty> getBlockProperties(@NotNull Identifier blockId) throws MissingResourceException {
ImmutableBlockState blockState = findBlockState(blockId);
@@ -143,7 +143,7 @@ public class DataFixerV1217 extends DataFixerV1213 {
attributes.put("minecraft:gameplay/bed_rule", new JSONObject()
.put("can_set_spawn", "never")
.put("can_sleep", "never")
.put("destroy_on_use", true));
.put("explodes", true));
}
attributes.put("minecraft:gameplay/respawn_anchor_works", json.remove("respawn_anchor_works"));
@@ -49,6 +49,16 @@ public final class DataFixerV263 extends DataFixerV1217 {
return fixed;
}
/** 26.3 renamed the bed rule's explodes flag to destroy_on_use; the old key is ignored there. */
@Override
public void fixDimension(Dimension dimension, JSONObject json) {
super.fixDimension(dimension, json);
JSONObject bedRule = json.getJSONObject("attributes").optJSONObject("minecraft:gameplay/bed_rule");
if (bedRule != null && bedRule.has("explodes")) {
bedRule.put("destroy_on_use", bedRule.remove("explodes"));
}
}
private static void color(JSONObject object, String key) {
if (object.opt(key) instanceof Number value) {
object.put(key, String.format(Locale.ROOT, "#%06x", value.intValue() & 0xFFFFFF));
@@ -25,6 +25,7 @@ import art.arcane.iris.integration.ExternalDataSVC;
import art.arcane.iris.structure.object.IrisObjectRotation;
import art.arcane.volmlib.nativelib.terrain.BlockStateKey;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.nativelib.block.SurvivalAnswer;
import art.arcane.iris.generation.block.IrisCustomData;
import art.arcane.iris.generation.geometry.IrisBlockVector;
import art.arcane.iris.spi.IrisServices;
@@ -429,7 +430,18 @@ public final class BukkitBlockState implements NativeBlockState {
@Override
public boolean canPlaceOnto(NativeBlockState onto) {
return BukkitBlockResolution.canPlaceOnto(data.getMaterial(), ((BlockData) onto.nativeHandle()).getMaterial());
BlockData plant = realBlockOf(data);
BlockData ground = realBlockOf((BlockData) onto.nativeHandle());
SurvivalAnswer serverRule = INMS.isBound() ? INMS.get().canSurviveOn(plant, ground) : SurvivalAnswer.UNANSWERED;
return switch (serverRule) {
case SURVIVES -> true;
case FAILS -> false;
case UNANSWERED -> BukkitBlockResolution.canPlaceOnto(plant.getMaterial(), ground.getMaterial());
};
}
private static BlockData realBlockOf(BlockData data) {
return data instanceof IrisCustomData custom ? custom.getBase() : data;
}
@Override
@@ -2,14 +2,20 @@ package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.iris.generation.noise.IrisExpression;
import art.arcane.iris.generation.noise.IrisExpressionFunction;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.ResourceLoader;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.math.RNG;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
@@ -17,6 +23,9 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -28,6 +37,71 @@ public final class IrisBiomePaletteLayerGeneratorCacheTest {
private static final int SIGNATURE = 7;
private static final long LAYER_SIGNATURE = 2L;
@Test
public void coordinateOnlyLayerSharesOneGeneratorWithoutChangingItsSamples() {
IrisGeneratorStyle color = new IrisGeneratorStyle().setExpression("color");
PackRuntime runtime = runtimeWithExpressions(Map.of(
"material", new IrisExpression()
.setExpression("if(y >= 25 + 19 * cos((x-y)/43), 0.90, color(abs(sin((x-y)/19 + z/33)), 0, 0))")
.setFunctions(new KList<>(new IrisExpressionFunction().setName("color").setArgs(3).setStyleValue(color))),
"color", new IrisExpression().setExpression("if(x < 0.03, 0.70, if(x < 0.07, 0.40, 0.10))")));
IrisGeneratorStyle style = new IrisGeneratorStyle().setExpression("material");
IrisBiomePaletteLayer layer = new IrisBiomePaletteLayer().zero().setStyle(style);
CNG shared = layer.getLayerGenerator(new RNG(17L), 0, runtime);
List<String> blocks = List.of("end_stone", "blackstone", "obsidian", "air");
for (int depth = 0; depth < 79; depth++) {
RNG caller = new RNG(17L + depth * 41L);
long originalSeed = caller.getSeed() + depth + LAYER_SIGNATURE;
CNG original = style.createNoCache(new RNG(originalSeed), runtime);
assertSame(shared, layer.getLayerGenerator(caller, depth, runtime));
for (int x = -32; x < 32; x += 3) {
double z = 41.5D - x;
assertEquals(original.fit(blocks, x, depth, z), shared.fit(blocks, x, depth, z));
assertEquals(original.noise(x, depth, z), shared.noise(x, depth, z), 0D);
}
}
}
@Test
public void nestedSeededNoiseKeepsDistinctLayerGenerators() {
IrisGeneratorStyle style = new IrisGeneratorStyle().setExpression("seeded");
PackRuntime runtime = runtimeWithExpressions(Map.of(
"seeded", new IrisExpression().setExpression("noise(x, z)")
.setFunctions(new KList<>(new IrisExpressionFunction()
.setName("noise").setStyleValue(NoiseStyle.SIMPLEX.style())))));
IrisBiomePaletteLayer layer = new IrisBiomePaletteLayer().zero().setStyle(style);
CNG first = layer.getLayerGenerator(new RNG(17L), 0, runtime);
CNG second = layer.getLayerGenerator(new RNG(29L), 0, runtime);
assertNotSame(first, second);
assertEquals(style.createNoCache(new RNG(17L + LAYER_SIGNATURE), runtime).noise(-23D, 7D, 11D),
first.noise(-23D, 7D, 11D), 0D);
assertEquals(style.createNoCache(new RNG(29L + LAYER_SIGNATURE), runtime).noise(-23D, 7D, 11D),
second.noise(-23D, 7D, 11D), 0D);
}
@Test
public void recursiveAndMissingExpressionReferencesDoNotQualifyForSharing() {
IrisGeneratorStyle recursive = new IrisGeneratorStyle().setExpression("recursive");
IrisGeneratorStyle missing = new IrisGeneratorStyle().setExpression("missing");
PackRuntime runtime = runtimeWithExpressions(Map.of(
"recursive", new IrisExpression().setExpression("again(x, z)")
.setFunctions(new KList<>(new IrisExpressionFunction()
.setName("again").setStyleValue(recursive)))));
assertFalse(recursive.canShareExpressionGenerator(runtime.data()));
assertFalse(missing.canShareExpressionGenerator(runtime.data()));
}
private static PackRuntime runtimeWithExpressions(Map<String, IrisExpression> contents) {
IrisData data = MockPackData.create();
ResourceLoader<IrisExpression> expressions = mock();
when(data.getExpressionLoader()).thenReturn(expressions);
when(expressions.load(any(String.class))).thenAnswer(call -> contents.get(call.getArgument(0)));
return data.standalonePackRuntime();
}
@Test
public void callerSeedsDoNotShareAFirstWinnerGenerator() {
GeneratorFixture fixture = new GeneratorFixture();
@@ -0,0 +1,138 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import org.junit.Test;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
public final class PaletteLayerDepthCacheTest {
private static final long[] PARENT_SEEDS = {0L, 17L, -9_223_372_036_854_775_807L, 8_675_309L, 1_234_567_890_123L};
private static final int[] THICKNESSES = {1, 8, 33, 96, 300};
private static final int LAYER_INDEX = 3;
private static final int COLUMNS = 256;
private static final int BENCH_THICKNESS = 96;
private static final int BENCH_CHUNKS = 8;
@Test
public void deepLayerBuildsEachDepthGeneratorOnce() {
CountingStyle style = new CountingStyle(NoiseStyle.SIMPLEX);
IrisBiomePaletteLayer layer = layer(style, BENCH_THICKNESS);
PackRuntime runtime = MockPackData.create().standalonePackRuntime();
walkChunks(layer, runtime, new RNG(17L), BENCH_THICKNESS, 2);
assertEquals(BENCH_THICKNESS, style.builds.get());
}
@Test
public void seededLayerBuildsOneGeneratorForEveryDepthAndParent() {
CountingStyle style = new CountingStyle(NoiseStyle.SIMPLEX);
style.setSeed(4_242L);
IrisBiomePaletteLayer layer = layer(style, BENCH_THICKNESS);
PackRuntime runtime = MockPackData.create().standalonePackRuntime();
for (long parentSeed : PARENT_SEEDS) {
walkChunks(layer, runtime, new RNG(parentSeed), BENCH_THICKNESS, 1);
}
assertEquals(1, style.builds.get());
}
@Test
public void cachedDepthGeneratorsMatchFreshBuilds() {
assertMatchesFreshBuilds(new IrisGeneratorStyle(NoiseStyle.SIMPLEX));
assertMatchesFreshBuilds(new IrisGeneratorStyle(NoiseStyle.CELLULAR).setFracture(
new IrisGeneratorStyle(NoiseStyle.PERLIN).zoomed(3D)).zoomed(0.5D));
assertMatchesFreshBuilds(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).setSeed(77L));
assertMatchesFreshBuilds(new IrisGeneratorStyle(NoiseStyle.PERLIN).setSeed(-3L)
.setFracture(new IrisGeneratorStyle(NoiseStyle.SIMPLEX)));
}
/** Prints builds and thread CPU time for a deep-layer chunk walk; compare runs on the same machine. */
@Test
public void reportDeepLayerWalkCost() {
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
for (int round = 0; round < 3; round++) {
for (boolean fractured : new boolean[]{false, true}) {
CountingStyle style = new CountingStyle(fractured ? NoiseStyle.CELLULAR : NoiseStyle.SIMPLEX);
if (fractured) {
style.setFracture(new IrisGeneratorStyle(NoiseStyle.PERLIN).zoomed(3D));
}
IrisBiomePaletteLayer layer = layer(style, BENCH_THICKNESS);
PackRuntime runtime = MockPackData.create().standalonePackRuntime();
long start = threads.getCurrentThreadCpuTime();
double sink = walkChunks(layer, runtime, new RNG(17L), BENCH_THICKNESS, BENCH_CHUNKS);
long cpu = threads.getCurrentThreadCpuTime() - start;
System.out.printf("palette depth walk %s: thickness=%d chunks=%d builds=%d cpu=%.1fms (%.2fms/chunk) sink=%.3f%n",
fractured ? "cellular+fracture" : "simplex", BENCH_THICKNESS, BENCH_CHUNKS, style.builds.get(),
cpu / 1e6D, cpu / 1e6D / BENCH_CHUNKS, sink);
}
}
}
private static void assertMatchesFreshBuilds(IrisGeneratorStyle style) {
for (int thickness : THICKNESSES) {
IrisBiomePaletteLayer layer = layer(style, thickness);
PackRuntime runtime = MockPackData.create().standalonePackRuntime();
int blockCount = layer.getBlockData(runtime.data()).size();
for (int pass = 0; pass < 2; pass++) {
for (long parentSeed : PARENT_SEEDS) {
RNG parent = new RNG(parentSeed);
for (int depth = 0; depth < thickness; depth++) {
int signature = LAYER_INDEX + depth;
long seed = parentSeed + signature + thickness + thickness + blockCount;
CNG fresh = style.createNoCache(new RNG(seed), runtime);
CNG cached = layer.getLayerGenerator(parent, signature, runtime);
for (int sample = 0; sample < 6; sample++) {
double x = sample * 37.25D - 91D + depth;
double z = 13.5D - sample * 19D - depth;
assertEquals(fresh.noise(x, depth, z), cached.noise(x, depth, z), 0D);
assertEquals(fresh.noise(x, z), cached.noise(x, z), 0D);
}
}
}
}
}
}
private static double walkChunks(IrisBiomePaletteLayer layer, PackRuntime runtime, RNG parent, int thickness, int chunks) {
double sink = 0D;
for (int chunk = 0; chunk < chunks; chunk++) {
for (int column = 0; column < COLUMNS; column++) {
double x = chunk * 16 + (column & 15);
double z = column >> 4;
for (int depth = 0; depth < thickness; depth++) {
sink += layer.getLayerGenerator(parent, LAYER_INDEX + depth, runtime).noise(x + depth, depth, z - depth);
}
}
}
return sink;
}
private static IrisBiomePaletteLayer layer(IrisGeneratorStyle style, int thickness) {
return new IrisBiomePaletteLayer().zero().setStyle(style).setMinHeight(thickness).setMaxHeight(thickness);
}
private static final class CountingStyle extends IrisGeneratorStyle {
private final AtomicInteger builds = new AtomicInteger();
private CountingStyle(NoiseStyle style) {
super(style);
}
@Override
public CNG createNoCache(RNG rng, PackRuntime runtime) {
builds.incrementAndGet();
return super.createNoCache(rng, runtime);
}
}
}
@@ -1,6 +1,7 @@
package art.arcane.iris.pack.datapack.v1217;
import art.arcane.iris.pack.datapack.IDataFixer.Dimension;
import art.arcane.iris.pack.datapack.v263.DataFixerV263;
import art.arcane.volmlib.util.json.JSONObject;
import org.junit.Test;
@@ -10,6 +11,7 @@ import static org.junit.Assert.assertTrue;
public class DataFixerV1217BedRuleTest {
private final DataFixerV1217 fixer = new DataFixerV1217();
private final DataFixerV1217 fixer263 = new DataFixerV263();
@Test
public void overworldBedsSleepWhenDark() {
@@ -21,25 +23,48 @@ public class DataFixerV1217BedRuleTest {
}
@Test
public void netherBedsAreDestroyedOnUse() {
assertDestroyedOnUse(bedRule(Dimension.NETHER));
public void netherBedsExplodeBefore263() {
assertNoSleep(bedRule(fixer, Dimension.NETHER), "explodes", "destroy_on_use");
}
@Test
public void endBedsAreDestroyedOnUse() {
assertDestroyedOnUse(bedRule(Dimension.END));
public void endBedsExplodeBefore263() {
assertNoSleep(bedRule(fixer, Dimension.END), "explodes", "destroy_on_use");
}
@Test
public void netherBedsAreDestroyedOnUseFrom263() {
assertNoSleep(bedRule(fixer263, Dimension.NETHER), "destroy_on_use", "explodes");
}
@Test
public void endBedsAreDestroyedOnUseFrom263() {
assertNoSleep(bedRule(fixer263, Dimension.END), "destroy_on_use", "explodes");
}
@Test
public void overworldBedsSleepWhenDarkFrom263() {
JSONObject rule = bedRule(fixer263, Dimension.OVERWORLD);
assertEquals("when_dark", rule.getString("can_sleep"));
assertFalse(rule.has("explodes"));
assertFalse(rule.has("destroy_on_use"));
}
private JSONObject bedRule(Dimension dimension) {
return bedRule(fixer, dimension);
}
private static JSONObject bedRule(DataFixerV1217 fixer, Dimension dimension) {
return fixer.createDimension(dimension, -64, 384, 384, null)
.getJSONObject("attributes")
.getJSONObject("minecraft:gameplay/bed_rule");
}
private static void assertDestroyedOnUse(JSONObject rule) {
private static void assertNoSleep(JSONObject rule, String presentKey, String absentKey) {
assertEquals("never", rule.getString("can_sleep"));
assertEquals("never", rule.getString("can_set_spawn"));
assertTrue(rule.getBoolean("destroy_on_use"));
assertFalse(rule.has("explodes"));
assertTrue(rule.getBoolean(presentKey));
assertFalse(rule.has(absentKey));
}
}