mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-12-04 04:02:11 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18bd887c8f | ||
|
|
a5918c17a7 | ||
|
|
00b0509219 |
No files matched your search
-262
@@ -1,262 +0,0 @@
|
||||
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,7 +58,6 @@ 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;
|
||||
@@ -682,7 +681,6 @@ public final class IrisRuntime implements IrisPluginRuntime {
|
||||
new GlobalCacheSVC(),
|
||||
new LogFilterSVC(),
|
||||
new ExternalDataSVC(),
|
||||
new BlockRulesSVC(),
|
||||
new EditSVC(),
|
||||
new ObjectSVC(),
|
||||
new ObjectStudioSaveService(),
|
||||
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,7 +104,7 @@ repositories {
|
||||
name = 'FabricMC'
|
||||
url = uri('https://maven.fabricmc.net/')
|
||||
}
|
||||
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
|
||||
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
|
||||
maven { url = uri('https://jitpack.io') }
|
||||
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
|
||||
}
|
||||
@@ -331,6 +331,7 @@ 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')
|
||||
@@ -414,7 +415,6 @@ tasks.named('assemble').configure {
|
||||
}
|
||||
|
||||
pluginPackaging {
|
||||
nativeBoundaryChecks = true
|
||||
artifacts {
|
||||
create('distribution') {
|
||||
taskName = irisModTarget.fabricRemap ? 'remapJar' : 'shadowJar'
|
||||
|
||||
@@ -121,7 +121,7 @@ repositories {
|
||||
maven fg.forgeMaven
|
||||
maven fg.minecraftLibsMaven
|
||||
mavenCentral()
|
||||
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
|
||||
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
|
||||
maven { url = uri('https://jitpack.io') }
|
||||
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
|
||||
}
|
||||
@@ -320,6 +320,7 @@ 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')
|
||||
@@ -376,7 +377,6 @@ tasks.named('assemble').configure {
|
||||
}
|
||||
|
||||
pluginPackaging {
|
||||
nativeBoundaryChecks = true
|
||||
artifacts {
|
||||
create('distribution') {
|
||||
taskName = 'shadowJar'
|
||||
|
||||
@@ -105,7 +105,7 @@ repositories {
|
||||
name = 'NeoForged'
|
||||
url = uri('https://maven.neoforged.net/releases/')
|
||||
}
|
||||
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
|
||||
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
|
||||
maven { url = uri('https://jitpack.io') }
|
||||
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
|
||||
}
|
||||
@@ -304,6 +304,7 @@ 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')
|
||||
@@ -360,7 +361,6 @@ tasks.named('assemble').configure {
|
||||
}
|
||||
|
||||
pluginPackaging {
|
||||
nativeBoundaryChecks = true
|
||||
artifacts {
|
||||
create('distribution') {
|
||||
taskName = 'shadowJar'
|
||||
|
||||
+8
-7
@@ -1,4 +1,5 @@
|
||||
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
|
||||
@@ -653,7 +654,7 @@ allprojects {
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri('https://repo.papermc.io/repository/maven-public/') }
|
||||
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
|
||||
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
|
||||
|
||||
maven {
|
||||
url = uri('https://jitpack.io')
|
||||
@@ -758,6 +759,11 @@ 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]
|
||||
@@ -1004,12 +1010,7 @@ tasks.withType(PackedJar).configureEach {
|
||||
dependsOn(tasks.named('verifyBukkitArtifact'), nativeRuntime)
|
||||
nativeArtifacts.set(providers.provider { embeddedNatives() })
|
||||
doLast { PackedJar task ->
|
||||
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())
|
||||
NativeRuntimeArtifacts.verifyPacked(task.outputJar.get().asFile, nativeRuntimeModules, embeddedNatives())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ 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,4 +1,5 @@
|
||||
import org.gradle.api.GradleException;
|
||||
import org.tukaani.xz.XZInputStream;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
@@ -27,6 +28,7 @@ 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/";
|
||||
|
||||
@@ -97,20 +99,35 @@ public final class NativeRuntimeArtifacts {
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
public static void verifyPacked(File artifact, List<String> modules, Map<String, File> natives) throws IOException {
|
||||
requireModules(natives, modules);
|
||||
byte[] manifest = runtime.get(MANIFEST);
|
||||
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);
|
||||
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 = runtime.get(RESOURCES + module + ".jar");
|
||||
byte[] provider = contents.get(RESOURCES + module + ".jar");
|
||||
if (provider == null) {
|
||||
throw new GradleException("Missing embedded native provider: " + module);
|
||||
}
|
||||
@@ -120,18 +137,6 @@ 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));
|
||||
@@ -158,6 +163,18 @@ 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,11 +4,13 @@ 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;
|
||||
@@ -20,7 +22,6 @@ 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;
|
||||
@@ -88,35 +89,15 @@ public class NativeRuntimeArtifactsTest {
|
||||
public void verifiesTheEmbeddedProviderBytesInsideThePackedRuntime() throws Exception {
|
||||
Map<String, File> natives = natives();
|
||||
Map<String, byte[]> runtime = runtime(natives, natives);
|
||||
byte[] manifest = runtime.get(NativeRuntimeArtifacts.MANIFEST);
|
||||
NativeRuntimeArtifacts.verifyPacked(runtime, manifest, MODULES, natives);
|
||||
NativeRuntimeArtifacts.verifyPacked(runtime, null, MODULES, natives);
|
||||
NativeRuntimeArtifacts.verifyPacked(packed(runtime), MODULES, natives);
|
||||
NativeRuntimeArtifacts.verifyPacked(jar("ordinary.jar", runtime), 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(runtime(natives, rebuilt),
|
||||
manifest, MODULES, natives));
|
||||
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(packed(runtime(natives, rebuilt)),
|
||||
MODULES, natives));
|
||||
Map<String, byte[]> missing = new TreeMap<>(runtime);
|
||||
missing.remove(NativeRuntimeArtifacts.RESOURCES + "native-v26_2_R1.jar");
|
||||
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()));
|
||||
}
|
||||
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(packed(missing), MODULES, natives));
|
||||
}
|
||||
|
||||
private Map<String, File> natives() throws IOException {
|
||||
@@ -156,6 +137,17 @@ 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))) {
|
||||
|
||||
+1
-1
@@ -482,7 +482,7 @@ List<String> dependencyBuildMetadata = [
|
||||
'META-INF/versions/*/OSGI-INF/**'
|
||||
]
|
||||
|
||||
String languageTomlSupportClassPattern = 'art/arcane/volmlib/util/config/(?:TomlCodec|TomlSegments|ConfigComments|ConfigJson|ConfigExposePolicy|ConfigDoc|ConfigDescription|ConfigDocumentation)(?:\\$[^/]+)?\\.class'
|
||||
String languageTomlSupportClassPattern = 'art/arcane/volmlib/util/config/(?:TomlCodec|ConfigJson|ConfigExposePolicy|ConfigDoc|ConfigDescription|ConfigDocumentation)(?:\\$[^/]+)?\\.class'
|
||||
|
||||
tasks.named('shadowJar', ShadowJar).configure {
|
||||
inputs.property('languageTomlSupportClassPattern', languageTomlSupportClassPattern)
|
||||
|
||||
@@ -18,37 +18,27 @@
|
||||
|
||||
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. 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.
|
||||
* seeds that sample it.
|
||||
*/
|
||||
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;
|
||||
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.layerGenerators = new SeedTable<>(LAYER_SEED_CAPACITY, LAYER_RECENT_SLOTS,
|
||||
seed -> layer.createLayerGenerator(seed, runtime));
|
||||
this.heightGenerators = new SeedTable<>(HEIGHT_SEED_CAPACITY, IrisBiomePaletteLayer::createHeightGenerator);
|
||||
}
|
||||
|
||||
@@ -58,16 +48,10 @@ public final class PaletteLayerRuntime {
|
||||
}
|
||||
|
||||
public CNG layerGenerator(long seed) {
|
||||
return layerGenerators.get(shareGenerator ? 0L : seed);
|
||||
return layerGenerators.get(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);
|
||||
}
|
||||
}
|
||||
@@ -8,14 +8,11 @@ import art.arcane.volmlib.util.io.CountingDataInputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.world.storage.matter.IrisMatterSupport;
|
||||
import art.arcane.iris.world.storage.matter.RetiredMatterSlices;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
@@ -150,7 +147,6 @@ public record ObjectContinuationBundle(List<Fragment> fragments) {
|
||||
Matter matter = new IrisMatter(width, height, depth);
|
||||
int sliceCount = input.readUnsignedByte();
|
||||
matter.getHeader().read(input);
|
||||
HashSet<String> skippedRetired = new HashSet<>();
|
||||
for (int index = 0; index < sliceCount; index++) {
|
||||
int size = input.readInt();
|
||||
long end = input.count() + size;
|
||||
@@ -158,24 +154,9 @@ public record ObjectContinuationBundle(List<Fragment> fragments) {
|
||||
throw new IOException("Invalid object continuation slice size");
|
||||
}
|
||||
String identifier = input.readUTF();
|
||||
if (input.count() > end) {
|
||||
throw new IOException("Object continuation slice size mismatch: " + identifier);
|
||||
}
|
||||
Class<?> type = IrisMatter.getSliceType(identifier);
|
||||
if (type == null) {
|
||||
if (!RetiredMatterSlices.isRetired(identifier)) {
|
||||
throw new IOException("Unknown object continuation slice type: " + identifier);
|
||||
}
|
||||
if (!skippedRetired.add(identifier)) {
|
||||
throw new IOException("Duplicate object continuation slice type: " + identifier);
|
||||
}
|
||||
input.skipTo(end);
|
||||
IrisLogging.warnOnce("object-continuation:retired-slice:" + identifier,
|
||||
"Skipping retired object continuation slice %s written by an older Iris version", identifier);
|
||||
continue;
|
||||
}
|
||||
if (matter.hasSlice(type)) {
|
||||
throw new IOException("Duplicate object continuation slice type: " + identifier);
|
||||
if (type == null || matter.hasSlice(type)) {
|
||||
throw new IOException("Unavailable or duplicate object continuation slice: " + identifier);
|
||||
}
|
||||
MatterSlice<?> slice = matter.createSlice(type, matter);
|
||||
if (slice == null) {
|
||||
|
||||
@@ -21,7 +21,6 @@ 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;
|
||||
@@ -43,9 +42,7 @@ 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")
|
||||
@@ -102,46 +99,6 @@ 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();
|
||||
}
|
||||
|
||||
@@ -269,13 +269,9 @@ public final class DimensionTerrainContext implements DataProvider {
|
||||
Interpolated.of(value -> 0D, value -> focusBiome.getInferredType())
|
||||
);
|
||||
|
||||
boolean sealessRegions = IrisComplex.lacks(preparedBiomeStreams, InferredType.SEA);
|
||||
ProceduralStream<IrisBiome> proceduralBaseBiomeStream = focusBiome == null
|
||||
? bridgeStream
|
||||
.convertAware2D((continent, x, z) -> {
|
||||
InferredType type = sealessRegions
|
||||
? IrisComplex.baseType(preparedBiomeStreams, regionStream.get(x, z), continent)
|
||||
: continent;
|
||||
.convertAware2D((type, x, z) -> {
|
||||
ProceduralStream<IrisBiome> stream = inferredStreams.get(type);
|
||||
return stream != null
|
||||
? stream.get(x, z)
|
||||
@@ -540,17 +536,13 @@ public final class DimensionTerrainContext implements DataProvider {
|
||||
IrisRegion region,
|
||||
InferredType type
|
||||
) {
|
||||
if ((type == InferredType.SEA || type == InferredType.SHORE) && loadInferredBiomes(runtime.data(), biomeKeys(region, type), type).isEmpty()) {
|
||||
return IrisComplex.NO_BIOMES;
|
||||
}
|
||||
return switch (type) {
|
||||
case LAND -> dimension.getLandBiomeStyle()
|
||||
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), runtime).stream()
|
||||
.zoom(dimension.getBiomeZoom())
|
||||
.zoom(dimension.getLandZoom())
|
||||
.zoom(region.getLandBiomeZoom())
|
||||
.selectRarity(IrisComplex.requireLandBiomes(region,
|
||||
loadInferredBiomes(runtime.data(), region.getLandBiomes(), InferredType.LAND)));
|
||||
.selectRarity(loadInferredBiomes(runtime.data(), region.getLandBiomes(), InferredType.LAND));
|
||||
case SEA -> dimension.getSeaBiomeStyle()
|
||||
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), runtime).stream()
|
||||
.zoom(dimension.getBiomeZoom())
|
||||
@@ -566,10 +558,6 @@ public final class DimensionTerrainContext implements DataProvider {
|
||||
};
|
||||
}
|
||||
|
||||
private static KList<String> biomeKeys(IrisRegion region, InferredType type) {
|
||||
return type == InferredType.SEA ? region.getSeaBiomes() : region.getShoreBiomes();
|
||||
}
|
||||
|
||||
private static KList<IrisBiome> loadInferredBiomes(
|
||||
IrisData data,
|
||||
KList<String> keys,
|
||||
|
||||
@@ -154,12 +154,6 @@ public class IrisComplex implements DataProvider {
|
||||
InferredType.SEA,
|
||||
InferredType.SHORE
|
||||
};
|
||||
/**
|
||||
* The biome stream of a sea or shore list a region leaves empty. It answers null everywhere, which tells the
|
||||
* surface resolution to keep the column's own biome instead of converting it.
|
||||
*/
|
||||
static final ProceduralStream<IrisBiome> NO_BIOMES = ProceduralStream.of((x, z) -> null,
|
||||
Interpolated.of(value -> 0D, value -> null));
|
||||
@Getter(AccessLevel.NONE)
|
||||
private final transient ThreadSlots<GridBoundsCache> gridBoundsCache = new ThreadSlots<>(GridBoundsCache::new);
|
||||
@Getter(AccessLevel.NONE)
|
||||
@@ -212,8 +206,6 @@ public class IrisComplex implements DataProvider {
|
||||
private ProceduralStream<Double> regionStyleStream;
|
||||
private ProceduralStream<Double> regionIdentityStream;
|
||||
private ProceduralStream<InferredType> bridgeStream;
|
||||
@Getter(AccessLevel.NONE)
|
||||
private ProceduralStream<InferredType> baseTypeStream;
|
||||
private ProceduralStream<IrisBiome> landBiomeStream;
|
||||
private ProceduralStream<IrisBiome> caveBiomeStream;
|
||||
private ProceduralStream<IrisBiome> seaBiomeStream;
|
||||
@@ -463,15 +455,9 @@ public class IrisComplex implements DataProvider {
|
||||
bridgeStream = focusedBiomes != null ? focusedBiomes.convert(IrisBiome::getInferredType) :
|
||||
ContinentGenerator.create(engine.getDimension(), rng, packRuntime).stream()
|
||||
.convert((v) -> v >= engine.getDimension().getLandChance() ? InferredType.SEA : InferredType.LAND);
|
||||
// A region without sea biomes picks its continental sea from its land biomes.
|
||||
baseTypeStream = focusedBiomes != null || !lacks(inferredBiomeStreams, InferredType.SEA) ? bridgeStream
|
||||
: ProceduralStream.of(
|
||||
(x, z) -> baseType(inferredBiomeStreams, contextRegionStream.get(x, z), bridgeStream.get(x, z)),
|
||||
(x, y, z) -> baseType(inferredBiomeStreams, contextRegionStream.get(x, z), bridgeStream.get(x, y, z)),
|
||||
Interpolated.of(value -> 0D, value -> null));
|
||||
ProceduralStream<IrisBiome> proceduralBaseBiomeStream = focusedBiomes != null ? focusedBiomes
|
||||
: ProceduralStream.of(this::proceduralBaseBiome,
|
||||
(x, y, z) -> implode(inferredByType.get(baseTypeStream.get(x, y, z)).get(x, z), x, z),
|
||||
(x, y, z) -> implode(inferredByType.get(bridgeStream.get(x, y, z)).get(x, z), x, z),
|
||||
Interpolated.of(value -> 0D, value -> null));
|
||||
baseBiomeSource = focusedBiomes != null || !imageMapRuntime.has(IrisImageMapApplication.BIOME)
|
||||
? proceduralBaseBiomeStream : ProceduralStream.of((x, z) -> {
|
||||
@@ -1081,7 +1067,7 @@ public class IrisComplex implements DataProvider {
|
||||
}
|
||||
|
||||
private IrisBiome proceduralBaseBiome(double x, double z) {
|
||||
return implode(inferredByType.get(baseTypeStream.get(x, z)).get(x, z), x, z);
|
||||
return implode(inferredByType.get(bridgeStream.get(x, z)).get(x, z), x, z);
|
||||
}
|
||||
|
||||
private final class BakeSource implements PlaneSource {
|
||||
@@ -1182,53 +1168,9 @@ public class IrisComplex implements DataProvider {
|
||||
InferredType inferredType,
|
||||
IrisBiome emptyBiome
|
||||
) {
|
||||
ProceduralStream<Double> noise = biomePickNoiseStream(engine.getDimension(), region, inferredType);
|
||||
KList<IrisBiome> biomes = loadInferredBiomes(biomeKeys(region, inferredType), inferredType);
|
||||
return switch (inferredType) {
|
||||
case CAVE -> new RarityStream<>(noise, biomes).onNull(emptyBiome);
|
||||
case LAND -> new RarityStream<>(noise, requireLandBiomes(region, biomes));
|
||||
case SEA, SHORE -> biomes.isEmpty() ? NO_BIOMES : new RarityStream<>(noise, biomes);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Every region needs a land biome: the surface falls back to land wherever it leaves sea or shore, and a region
|
||||
* without sea biomes picks its continental sea from land too.
|
||||
*/
|
||||
static KList<IrisBiome> requireLandBiomes(IrisRegion region, KList<IrisBiome> landBiomes) {
|
||||
if (!landBiomes.isEmpty()) {
|
||||
return landBiomes;
|
||||
}
|
||||
String regionKey = region.getLoadKey() == null || region.getLoadKey().isBlank() ? "<unkeyed>" : region.getLoadKey();
|
||||
throw new IllegalStateException(region.getLandBiomes().isEmpty()
|
||||
? "Region '" + regionKey + "' has no landBiomes; every region needs at least one land biome."
|
||||
: "Region '" + regionKey + "' has no landBiomes this Minecraft version can generate; every listed land biome is excluded.");
|
||||
}
|
||||
|
||||
/** Whether any prepared region left the given biome list empty. */
|
||||
static boolean lacks(Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> streams, InferredType inferredType) {
|
||||
for (Map<InferredType, ProceduralStream<IrisBiome>> regionStreams : streams.values()) {
|
||||
if (regionStreams.get(inferredType) == NO_BIOMES) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The biome list a spot's base biome comes from: the continent's choice, or land where the region has no sea. */
|
||||
static InferredType baseType(
|
||||
Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> streams,
|
||||
IrisRegion region,
|
||||
InferredType continent
|
||||
) {
|
||||
return continent == InferredType.SEA && preparedInferredBiomeStream(streams, region, InferredType.SEA) == NO_BIOMES
|
||||
? InferredType.LAND
|
||||
: continent;
|
||||
}
|
||||
|
||||
/** The biome list the given region picks this spot's base biome from. */
|
||||
public InferredType baseTypeIn(IrisRegion region, double x, double z) {
|
||||
return baseTypeStream == bridgeStream ? bridgeStream.get(x, z) : baseType(inferredBiomeStreams, region, bridgeStream.get(x, z));
|
||||
ProceduralStream<IrisBiome> picked = new RarityStream<>(biomePickNoiseStream(engine.getDimension(), region, inferredType),
|
||||
loadInferredBiomes(biomeKeys(region, inferredType), inferredType));
|
||||
return inferredType == InferredType.CAVE ? picked.onNull(emptyBiome) : picked;
|
||||
}
|
||||
|
||||
private ProceduralStream<Double> biomePickNoiseStream(IrisDimension dimension, IrisRegion region, InferredType inferredType) {
|
||||
@@ -1310,7 +1252,7 @@ public class IrisComplex implements DataProvider {
|
||||
if (focusBiome != null) {
|
||||
return new BiomePick(focusBiome, focusBiome.getInferredType());
|
||||
}
|
||||
InferredType type = baseTypeIn(region, x, z);
|
||||
InferredType type = bridgeStream.get(x, z);
|
||||
return new BiomePick(implode(createInferredBiomeStream(region, type).get(x, z), x, z), type);
|
||||
}
|
||||
|
||||
@@ -1982,7 +1924,7 @@ public class IrisComplex implements DataProvider {
|
||||
|
||||
if (height >= fluidHeight - 1 && !biome.isShore()) {
|
||||
if (!aboveShoreBand(height, region, x, z, fluidHeight, shoreSlopes)) {
|
||||
return convertedOrKept(shoreBiomes.get(x, z), biome);
|
||||
return shoreBiomes.get(x, z);
|
||||
}
|
||||
if (!biome.isLand()) {
|
||||
return landBiomes.get(x, z);
|
||||
@@ -1992,21 +1934,16 @@ public class IrisComplex implements DataProvider {
|
||||
}
|
||||
|
||||
if (height < fluidHeight && !biome.isAquatic()) {
|
||||
return convertedOrKept(seaBiomes.get(x, z), biome);
|
||||
return seaBiomes.get(x, z);
|
||||
}
|
||||
|
||||
if (height == fluidHeight && !biome.isShore()) {
|
||||
return convertedOrKept(shoreBiomes.get(x, z), biome);
|
||||
return shoreBiomes.get(x, z);
|
||||
}
|
||||
|
||||
return biome;
|
||||
}
|
||||
|
||||
// A null conversion comes from NO_BIOMES: the region lists no biomes of that type, so the column keeps its own.
|
||||
private static IrisBiome convertedOrKept(IrisBiome converted, IrisBiome biome) {
|
||||
return converted == null ? biome : converted;
|
||||
}
|
||||
|
||||
private double interpolateGenerators(Engine engine, IrisInterpolator interpolator, int interpolatorIndex, IrisGenerator[] generators, double x, double z, long seed) {
|
||||
if (generators.length == 0) {
|
||||
return 0;
|
||||
@@ -2599,7 +2536,7 @@ public class IrisComplex implements DataProvider {
|
||||
|
||||
private List<IrisBiome> childLineage(IrisBiome biome, int x, int z) {
|
||||
IrisBiome[] rootFirst = new IrisBiome[IrisBiome.CHILD_HOPS + 1];
|
||||
IrisBiome current = inferredByType.get(baseTypeStream.get(x, z)).get(x, z);
|
||||
IrisBiome current = inferredByType.get(bridgeStream.get(x, z)).get(x, z);
|
||||
rootFirst[0] = current;
|
||||
int size = 1;
|
||||
for (int hop = 0; hop < IrisBiome.CHILD_HOPS && !current.getChildren().isEmpty(); hop++) {
|
||||
@@ -2948,7 +2885,7 @@ public class IrisComplex implements DataProvider {
|
||||
if (constant != null) {
|
||||
return constant;
|
||||
}
|
||||
InferredType type = pick != null ? pick.type() : complex.baseTypeIn(region, x, z);
|
||||
InferredType type = pick != null ? pick.type() : complex.bridgeStream.get(x, z);
|
||||
constant = constants == null ? null : constants.typed(type, group);
|
||||
if (constant != null) {
|
||||
return constant;
|
||||
|
||||
@@ -300,6 +300,14 @@ 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,7 +8,6 @@ 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;
|
||||
@@ -84,7 +83,6 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis
|
||||
|
||||
@EventHandler
|
||||
public void onReload(CraftEngineReloadEvent event) {
|
||||
forgetServerBlockRules();
|
||||
if (!updateContent()) {
|
||||
return;
|
||||
}
|
||||
@@ -94,13 +92,6 @@ 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);
|
||||
|
||||
@@ -104,13 +104,12 @@ final class PackDimensionValidator {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Sea, shore and cave lists may be empty; land is what every other list falls back to.
|
||||
int landBiomes = countBiomeRefs(regionJson, "landBiomes", biomesFolder, regionKey, warnings);
|
||||
countBiomeRefs(regionJson, "seaBiomes", biomesFolder, regionKey, warnings);
|
||||
countBiomeRefs(regionJson, "shoreBiomes", biomesFolder, regionKey, warnings);
|
||||
countBiomeRefs(regionJson, "caveBiomes", biomesFolder, regionKey, warnings);
|
||||
if (landBiomes == 0) {
|
||||
blockingErrors.add("Region '" + regionKey + "' has no landBiomes; every region needs at least one land biome.");
|
||||
int anyBiome = countBiomeRefs(regionJson, "landBiomes", biomesFolder, regionKey, warnings)
|
||||
+ countBiomeRefs(regionJson, "seaBiomes", biomesFolder, regionKey, warnings)
|
||||
+ countBiomeRefs(regionJson, "shoreBiomes", biomesFolder, regionKey, warnings)
|
||||
+ countBiomeRefs(regionJson, "caveBiomes", biomesFolder, regionKey, warnings);
|
||||
if (anyBiome == 0) {
|
||||
blockingErrors.add("Region '" + regionKey + "' has no resolvable biomes.");
|
||||
}
|
||||
resolvedRegions++;
|
||||
}
|
||||
|
||||
@@ -211,7 +211,6 @@ public final class PackValidator {
|
||||
applyCompatFindings(minecraftVersion, dimensions.anyExcluded(), findings, blockingErrors, warnings);
|
||||
applyRequireAllContent(packFolder.getName(), dimensions.reachedByRequiringDimension(),
|
||||
minecraftVersion, findings, blockingErrors);
|
||||
addDistinct(blockingErrors, excludedLandErrors(data, dimensions.regionKeys(), minecraftVersion));
|
||||
return findings;
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError("Version-content gating failed for pack '" + packFolder.getName() + "'", e);
|
||||
@@ -240,7 +239,6 @@ public final class PackValidator {
|
||||
private static GatedDimensions loadEverything(File packFolder, IrisData data, File[] dimensionFiles) {
|
||||
boolean dimensionExcluded = false;
|
||||
Map<String, Set<String>> reachedByRequiringDimension = new LinkedHashMap<>();
|
||||
Set<String> regionKeys = new LinkedHashSet<>();
|
||||
List<String> folders = data.getLoaders().values().stream().map(ResourceLoader::getFolderName).toList();
|
||||
File dimensionsFolder = new File(packFolder, DIMENSIONS_FOLDER);
|
||||
for (File dimensionFile : dimensionFiles) {
|
||||
@@ -251,8 +249,6 @@ public final class PackValidator {
|
||||
}
|
||||
if (dimension.isCompatExcluded()) {
|
||||
dimensionExcluded = true;
|
||||
} else {
|
||||
regionKeys.addAll(dimension.getRegions());
|
||||
}
|
||||
if (dimension.isRequireAllContent()) {
|
||||
reachedByRequiringDimension.put(dimension.getLoadKey(), PackContentReach.referencedFrom(
|
||||
@@ -275,31 +271,10 @@ public final class PackValidator {
|
||||
for (IrisObjectPlacement placement : placements) {
|
||||
placement.evaluateCompat(data);
|
||||
}
|
||||
return new GatedDimensions(dimensionExcluded, reachedByRequiringDimension, regionKeys);
|
||||
return new GatedDimensions(dimensionExcluded, reachedByRequiringDimension);
|
||||
}
|
||||
|
||||
private record GatedDimensions(boolean anyExcluded, Map<String, Set<String>> reachedByRequiringDimension,
|
||||
Set<String> regionKeys) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A region whose land biomes the version-content gate excluded cannot generate. Regions that list no land biome
|
||||
* at all are already reported by {@link PackDimensionValidator}.
|
||||
*/
|
||||
private static List<String> excludedLandErrors(IrisData data, Collection<String> regionKeys, String minecraftVersion) {
|
||||
List<String> errors = new ArrayList<>();
|
||||
for (String regionKey : regionKeys) {
|
||||
IrisRegion region = data.getRegionLoader().load(regionKey, false);
|
||||
if (region == null || region.isCompatExcluded()) {
|
||||
continue;
|
||||
}
|
||||
List<IrisBiome> land = data.getBiomeLoader().loadAll(region.getLandBiomes());
|
||||
if (!land.isEmpty() && land.stream().allMatch(IrisBiome::isCompatExcluded)) {
|
||||
errors.add("Region '" + regionKey + "' has no landBiomes Minecraft " + versionOrUnknown(minecraftVersion)
|
||||
+ " can generate; every listed land biome is excluded.");
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
private record GatedDimensions(boolean anyExcluded, Map<String, Set<String>> reachedByRequiringDimension) {
|
||||
}
|
||||
|
||||
private static void collectPlacements(IrisRegistrant registrant, Set<IrisObjectPlacement> out) {
|
||||
|
||||
@@ -49,16 +49,6 @@ 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,7 +25,6 @@ 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;
|
||||
@@ -430,18 +429,7 @@ public final class BukkitBlockState implements NativeBlockState {
|
||||
|
||||
@Override
|
||||
public boolean canPlaceOnto(NativeBlockState onto) {
|
||||
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;
|
||||
return BukkitBlockResolution.canPlaceOnto(data.getMaterial(), ((BlockData) onto.nativeHandle()).getMaterial());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -141,7 +141,7 @@ final class BiomeExplorer {
|
||||
|
||||
private void add(double x, double z) {
|
||||
count++;
|
||||
InferredType type = complex.baseTypeIn(region, x, z);
|
||||
InferredType type = complex.getBridgeStream().get(x, z);
|
||||
for (TypedSpread typed : spreads) {
|
||||
if (typed.type() == type) {
|
||||
typed.spread().add(noiseByType.computeIfAbsent(type, shown -> complex.biomePickNoiseStream(region, shown)).get(x, z));
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
package art.arcane.iris.studio.map;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.runtime.IrisComplex;
|
||||
import art.arcane.iris.generation.terrain.IrisRegion;
|
||||
import art.arcane.iris.studio.map.components.MapLayer;
|
||||
@@ -44,7 +43,7 @@ final class PackFileOpener {
|
||||
File file = switch (layer.type()) {
|
||||
case BIOME, HEIGHT, RIVER, OBJECT_LOAD, DECORATOR_LOAD, LAYER_LOAD -> complex.getTrueBiomeStream().get(worldX, worldZ).openInVSCode();
|
||||
case BIOME_LAND -> complex.getLandBiomeStream().get(worldX, worldZ).openInVSCode();
|
||||
case BIOME_SEA -> openBiome(complex.getSeaBiomeStream().get(worldX, worldZ));
|
||||
case BIOME_SEA -> complex.getSeaBiomeStream().get(worldX, worldZ).openInVSCode();
|
||||
case REGION -> complex.getRegionStream().get(worldX, worldZ).openInVSCode();
|
||||
case REGION_PREVIEW -> openPreviewedBiome(engine, layer.previewRegionKey(), worldX, worldZ);
|
||||
case CAVE_LAND -> complex.getCaveBiomeStream().get(worldX, worldZ).openInVSCode();
|
||||
@@ -52,11 +51,6 @@ final class PackFileOpener {
|
||||
return Optional.ofNullable(file).map(File::getName);
|
||||
}
|
||||
|
||||
/** A region without sea biomes has none to open. */
|
||||
private static File openBiome(IrisBiome biome) {
|
||||
return biome == null ? null : biome.openInVSCode();
|
||||
}
|
||||
|
||||
private static File openPreviewedBiome(Engine engine, String regionKey, double worldX, double worldZ) {
|
||||
IrisRegion region = engine.getData().getRegionLoader().load(regionKey);
|
||||
return region == null ? null : engine.getComplex().surfaceBiomeAsIfIn(region, worldX, worldZ).openInVSCode();
|
||||
|
||||
@@ -236,11 +236,12 @@ public final class MapTileRenderer {
|
||||
// The biome view shows each spot's base biome, which its own region picks from the biome list of the spot's type.
|
||||
private static NoiseField baseBiomePickNoise(IrisComplex complex) {
|
||||
ProceduralStream<IrisRegion> regions = complex.getRegionStream();
|
||||
ProceduralStream<InferredType> types = complex.getBridgeStream();
|
||||
Map<IrisRegion, Map<InferredType, ProceduralStream<Double>>> noiseByRegion = new IdentityHashMap<>();
|
||||
return (gridIndex, x, z) -> {
|
||||
IrisRegion region = regions.get(x, z);
|
||||
return noiseByRegion.computeIfAbsent(region, subject -> new EnumMap<>(InferredType.class))
|
||||
.computeIfAbsent(complex.baseTypeIn(region, x, z), type -> complex.biomePickNoiseStream(region, type))
|
||||
.computeIfAbsent(types.get(x, z), type -> complex.biomePickNoiseStream(region, type))
|
||||
.get(x, z);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -176,8 +176,6 @@ public final class IrisRenderer {
|
||||
return Math.max(1, Math.min(resolution, (int) Math.floor(16D / absoluteStep)));
|
||||
}
|
||||
|
||||
private static final int NO_BIOME_COLOR = 0xFF000000;
|
||||
|
||||
private PixelShader shader(RenderType currentType) {
|
||||
IrisComplex complex = renderer.getComplex();
|
||||
return switch (currentType) {
|
||||
@@ -195,9 +193,6 @@ public final class IrisRenderer {
|
||||
IdentityHashMap<IrisBiome, Integer> colors = new IdentityHashMap<>();
|
||||
return (double x, double z) -> {
|
||||
IrisBiome biome = stream.get(x, z);
|
||||
if (biome == null) {
|
||||
return NO_BIOME_COLOR;
|
||||
}
|
||||
Integer color = colors.get(biome);
|
||||
if (color == null) {
|
||||
color = biome.getColor(renderer, currentType).getRGB();
|
||||
|
||||
@@ -697,8 +697,7 @@ public final class GenerationHistory {
|
||||
&& !selected.contains(ownership.resolve(chunkX, chunkZ, outgoing));
|
||||
WorldChunkInventory inventory;
|
||||
if (startupRecovery) {
|
||||
inventory = SavedTerrainRecoveryScan.scan(paths.dimensionRoot(), allocated, retained,
|
||||
paths.irisRoot().resolve(SavedTerrainStatusCache.FILE_NAME));
|
||||
inventory = SavedTerrainRecoveryScan.scan(paths.dimensionRoot(), allocated, retained);
|
||||
} else {
|
||||
try (SavedTerrainChunkReader.StatusReader reader = new SavedTerrainChunkReader.StatusReader(paths.dimensionRoot())) {
|
||||
inventory = allocated.filter((chunkX, chunkZ) -> retained.test(chunkX, chunkZ)
|
||||
|
||||
@@ -3,7 +3,6 @@ package art.arcane.iris.world.history;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.BitSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -21,16 +20,10 @@ final class SavedTerrainRecoveryScan implements AutoCloseable {
|
||||
private final int regionByteLimit;
|
||||
private final SavedTerrainChunkReader.StatusReader[] readers;
|
||||
private final ExecutorService executor;
|
||||
private final SavedTerrainStatusCache cache;
|
||||
private byte[] regionBuffer = new byte[0];
|
||||
|
||||
SavedTerrainRecoveryScan(Path world, Limits limits) {
|
||||
this(world, limits, null);
|
||||
}
|
||||
|
||||
SavedTerrainRecoveryScan(Path world, Limits limits, SavedTerrainStatusCache cache) {
|
||||
this.world = world;
|
||||
this.cache = cache;
|
||||
regionByteLimit = limits.regionBytes();
|
||||
readers = new SavedTerrainChunkReader.StatusReader[limits.workers()];
|
||||
for (int index = 0; index < readers.length; index++) {
|
||||
@@ -42,26 +35,11 @@ final class SavedTerrainRecoveryScan implements AutoCloseable {
|
||||
|
||||
static WorldChunkInventory scan(Path world, WorldChunkInventory inventory,
|
||||
WorldChunkInventory.ChunkPredicate retained) throws IOException {
|
||||
return scan(world, inventory, retained, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans with the status cache at {@code cacheFile}, or without a cache when it is null. The cache is
|
||||
* written once, after the whole scan succeeded.
|
||||
*/
|
||||
static WorldChunkInventory scan(Path world, WorldChunkInventory inventory,
|
||||
WorldChunkInventory.ChunkPredicate retained, Path cacheFile) throws IOException {
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
SavedTerrainStatusCache cache = cacheFile == null ? null : SavedTerrainStatusCache.load(cacheFile, world);
|
||||
WorldChunkInventory result;
|
||||
try (SavedTerrainRecoveryScan scan = new SavedTerrainRecoveryScan(world,
|
||||
Limits.forRuntime(runtime.availableProcessors(), runtime.maxMemory()), cache)) {
|
||||
result = scan.filter(inventory, retained);
|
||||
Limits.forRuntime(runtime.availableProcessors(), runtime.maxMemory()))) {
|
||||
return scan.filter(inventory, retained);
|
||||
}
|
||||
if (cache != null) {
|
||||
cache.save();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
WorldChunkInventory filter(WorldChunkInventory inventory, WorldChunkInventory.ChunkPredicate retained)
|
||||
@@ -103,39 +81,18 @@ final class SavedTerrainRecoveryScan implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
if (pending.isEmpty()) {
|
||||
if (cache != null) {
|
||||
cache.carry(region.x(), region.z());
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
Path file = world.resolve("region/r." + region.x() + "." + region.z() + ".mca");
|
||||
SavedTerrainStatusCache.Header header = cache == null ? null : readHeader(file);
|
||||
SavedTerrainStatusCache.Update update = null;
|
||||
if (header != null) {
|
||||
update = cache.begin(region.x(), region.z(), header, pending, accepted);
|
||||
if (pending.isEmpty()) {
|
||||
update.commit();
|
||||
return accepted;
|
||||
}
|
||||
}
|
||||
int snapshotLimit = Math.min(regionByteLimit, pending.cardinality() * 64 * 1024);
|
||||
Optional<SavedTerrainRegionSnapshot> captured = SavedTerrainRegionSnapshot.read(file, snapshotLimit, regionBuffer);
|
||||
if (captured.isEmpty()) {
|
||||
BitSet terrain = new BitSet(1024);
|
||||
for (int slot = pending.nextSetBit(0); slot >= 0; slot = pending.nextSetBit(slot + 1)) {
|
||||
requireNotInterrupted();
|
||||
if (SavedTerrainChunk.hasTerrain(readers[0].readStatus(region.chunkX(slot), region.chunkZ(slot)))) {
|
||||
terrain.set(slot);
|
||||
accepted.set(slot);
|
||||
}
|
||||
}
|
||||
accepted.or(terrain);
|
||||
if (update != null) {
|
||||
SavedTerrainStatusCache.Header after = readHeader(file);
|
||||
if (after != null && header.sameHeader(after)) {
|
||||
record(update, region, header, pending, terrain);
|
||||
}
|
||||
update.commit();
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
SavedTerrainRegionSnapshot snapshot = captured.get();
|
||||
@@ -149,9 +106,8 @@ final class SavedTerrainRecoveryScan implements AutoCloseable {
|
||||
pending.clear(slot);
|
||||
}
|
||||
}
|
||||
BitSet terrain;
|
||||
if (executor == null || pending.cardinality() < MIN_PARALLEL_CHUNKS) {
|
||||
terrain = decode(new DecodeRegion(region, pending, snapshot), 0, 1);
|
||||
accepted.or(decode(new DecodeRegion(region, pending, snapshot), 0, 1));
|
||||
} else {
|
||||
List<Future<BitSet>> tasks = new ArrayList<>(readers.length);
|
||||
DecodeRegion input = new DecodeRegion(region, pending, snapshot);
|
||||
@@ -159,36 +115,12 @@ final class SavedTerrainRecoveryScan implements AutoCloseable {
|
||||
int worker = index;
|
||||
tasks.add(executor.submit(() -> decode(input, worker, readers.length)));
|
||||
}
|
||||
terrain = await(tasks);
|
||||
accepted.or(await(tasks));
|
||||
}
|
||||
accepted.or(terrain);
|
||||
snapshot.validateUnchanged();
|
||||
if (update != null) {
|
||||
record(update, region, new SavedTerrainStatusCache.Header(header.fileKey(), header.size(),
|
||||
Arrays.copyOf(snapshot.bytes(), SavedTerrainStatusCache.Header.BYTES)), pending, terrain);
|
||||
update.commit();
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
|
||||
private void record(SavedTerrainStatusCache.Update update, Region region, SavedTerrainStatusCache.Header header,
|
||||
BitSet decoded, BitSet terrain) {
|
||||
for (int slot = decoded.nextSetBit(0); slot >= 0; slot = decoded.nextSetBit(slot + 1)) {
|
||||
if (!cache.isExternal(region.chunkX(slot), region.chunkZ(slot))) {
|
||||
update.record(slot, header.location(slot), header.timestamp(slot), terrain.get(slot));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static SavedTerrainStatusCache.Header readHeader(Path file) {
|
||||
try {
|
||||
return SavedTerrainStatusCache.Header.read(file);
|
||||
} catch (IOException ignored) {
|
||||
// The uncached read reports the real problem with this region.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private BitSet decode(DecodeRegion input, int worker, int stride) throws IOException {
|
||||
BitSet accepted = new BitSet(1024);
|
||||
int ordinal = 0;
|
||||
|
||||
@@ -1,379 +0,0 @@
|
||||
package art.arcane.iris.world.history;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.Arrays;
|
||||
import java.util.BitSet;
|
||||
import java.util.Objects;
|
||||
import java.util.zip.CRC32;
|
||||
|
||||
/**
|
||||
* Remembers the decoded "has terrain" bit of each saved chunk between startups. A bit is reused only while the
|
||||
* slot's location word and timestamp in the region header are unchanged, the timestamp is at least two seconds
|
||||
* older than the scan that decoded it, and the chunk is not stored in an external .mcc file. Ownership filtering
|
||||
* is never cached; callers apply it on every scan.
|
||||
*/
|
||||
final class SavedTerrainStatusCache {
|
||||
static final String FILE_NAME = "terrain-status.cache";
|
||||
|
||||
private static final int MAGIC = 0x49545343;
|
||||
private static final int VERSION = 1;
|
||||
private static final int SLOTS = 1024;
|
||||
private static final int HEADER_BYTES = 2 * 4096;
|
||||
private static final long MAX_CACHE_BYTES = 1L << 30;
|
||||
|
||||
private final Path file;
|
||||
private final Path regionDirectory;
|
||||
private final long scanSeconds;
|
||||
private final long previousScanSeconds;
|
||||
private final Long2ObjectOpenHashMap<Region> previous;
|
||||
private final Long2ObjectOpenHashMap<Region> next = new Long2ObjectOpenHashMap<>();
|
||||
private LongOpenHashSet externalChunks;
|
||||
private boolean externalChunksUnknown;
|
||||
|
||||
private SavedTerrainStatusCache(Path file, Path world, long scanSeconds, Contents contents) {
|
||||
this.file = file;
|
||||
regionDirectory = world.toAbsolutePath().normalize().resolve(GenerationHistoryPaths.REGION_DIRECTORY_NAME);
|
||||
this.scanSeconds = scanSeconds;
|
||||
previousScanSeconds = contents.scanSeconds();
|
||||
previous = contents.regions();
|
||||
}
|
||||
|
||||
static SavedTerrainStatusCache load(Path file, Path world) {
|
||||
Objects.requireNonNull(file, "file");
|
||||
Objects.requireNonNull(world, "world");
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
return new SavedTerrainStatusCache(file, world, now, readContents(file));
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the cache update for one region and moves every pending slot whose cached bit is still valid out of
|
||||
* {@code pending}, setting it in {@code accepted} when the chunk has terrain.
|
||||
*/
|
||||
Update begin(int regionX, int regionZ, Header header, BitSet pending, BitSet accepted) {
|
||||
Update update = new Update(regionX, regionZ, header);
|
||||
Region cached = previous.get(ChunkGenerationOwnership.packChunk(regionX, regionZ));
|
||||
if (cached == null || !cached.matches(header)) {
|
||||
return update;
|
||||
}
|
||||
for (int entry = 0; entry < cached.slots().length; entry++) {
|
||||
int slot = cached.slots()[entry];
|
||||
if (header.location(slot) != cached.locations()[entry]
|
||||
|| header.timestamp(slot) != cached.timestamps()[entry]
|
||||
|| !reusable(cached.locations()[entry], cached.timestamps()[entry], previousScanSeconds)
|
||||
|| isExternal(regionX * 32 + (slot & 31), regionZ * 32 + (slot >> 5))) {
|
||||
continue;
|
||||
}
|
||||
boolean terrain = cached.terrain().get(entry);
|
||||
update.keep(slot, cached.locations()[entry], cached.timestamps()[entry], terrain);
|
||||
if (pending.get(slot)) {
|
||||
pending.clear(slot);
|
||||
if (terrain) {
|
||||
accepted.set(slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
return update;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a region's cached entries as they are, for a region the scan did not need to read.
|
||||
*/
|
||||
void carry(int regionX, int regionZ) {
|
||||
long key = ChunkGenerationOwnership.packChunk(regionX, regionZ);
|
||||
Region cached = previous.get(key);
|
||||
if (cached != null) {
|
||||
next.put(key, cached);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the chunk has an external .mcc payload, or when the region directory could not be listed.
|
||||
*/
|
||||
boolean isExternal(int chunkX, int chunkZ) {
|
||||
if (externalChunks == null && !externalChunksUnknown) {
|
||||
try {
|
||||
externalChunks = listExternalChunks(regionDirectory);
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
externalChunksUnknown = true;
|
||||
IrisLogging.warnOnce("saved-terrain-cache-external", () -> "Not using the saved terrain status cache"
|
||||
+ " because " + regionDirectory + " could not be listed: " + failure);
|
||||
}
|
||||
}
|
||||
return externalChunksUnknown
|
||||
|| externalChunks.contains(ChunkGenerationOwnership.packChunk(chunkX, chunkZ));
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the cache with the regions visited by this scan. Regions that were not visited are dropped. Failures
|
||||
* are logged and never reach the caller.
|
||||
*/
|
||||
void save() {
|
||||
try {
|
||||
byte[] encoded = encode(scanSeconds, next);
|
||||
Path directory = file.toAbsolutePath().getParent();
|
||||
Files.createDirectories(directory);
|
||||
Path temporary = Files.createTempFile(directory, "." + file.getFileName() + "-", ".tmp");
|
||||
try {
|
||||
Files.write(temporary, encoded);
|
||||
Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
IrisLogging.warnOnce("saved-terrain-cache-write", () -> "Could not write the saved terrain status cache "
|
||||
+ file + ": " + failure);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean reusable(int location, int timestamp, long decodedAt) {
|
||||
return location != 0 && Integer.toUnsignedLong(timestamp) < decodedAt - 1L;
|
||||
}
|
||||
|
||||
private static LongOpenHashSet listExternalChunks(Path regionDirectory) throws IOException {
|
||||
LongOpenHashSet chunks = new LongOpenHashSet();
|
||||
try (DirectoryStream<Path> entries = Files.newDirectoryStream(regionDirectory, "c.*.*.mcc")) {
|
||||
for (Path entry : entries) {
|
||||
String[] parts = entry.getFileName().toString().split("\\.");
|
||||
if (parts.length != 4) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
chunks.add(ChunkGenerationOwnership.packChunk(Integer.parseInt(parts[1]),
|
||||
Integer.parseInt(parts[2])));
|
||||
} catch (NumberFormatException ignored) {
|
||||
// Not a chunk payload name; the region reader ignores it too.
|
||||
}
|
||||
}
|
||||
} catch (NoSuchFileException ignored) {
|
||||
return chunks;
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
private static Contents readContents(Path file) {
|
||||
try {
|
||||
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return Contents.EMPTY;
|
||||
}
|
||||
if (Files.size(file) > MAX_CACHE_BYTES) {
|
||||
throw new IOException("cache file is too large");
|
||||
}
|
||||
return decode(Files.readAllBytes(file));
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
IrisLogging.warnOnce("saved-terrain-cache-read", () -> "Ignoring the saved terrain status cache "
|
||||
+ file + ": " + failure.getMessage());
|
||||
return Contents.EMPTY;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] encode(long scanSeconds, Long2ObjectOpenHashMap<Region> regions) throws IOException {
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
try (DataOutputStream output = new DataOutputStream(buffer)) {
|
||||
output.writeInt(MAGIC);
|
||||
output.writeInt(VERSION);
|
||||
output.writeLong(scanSeconds);
|
||||
output.writeInt(regions.size());
|
||||
for (Region region : regions.values()) {
|
||||
output.writeInt(region.x());
|
||||
output.writeInt(region.z());
|
||||
output.writeLong(region.size());
|
||||
output.writeUTF(region.fileKey());
|
||||
output.writeShort(region.slots().length);
|
||||
for (int entry = 0; entry < region.slots().length; entry++) {
|
||||
output.writeShort(region.slots()[entry]);
|
||||
output.writeInt(region.locations()[entry]);
|
||||
output.writeInt(region.timestamps()[entry]);
|
||||
output.writeBoolean(region.terrain().get(entry));
|
||||
}
|
||||
}
|
||||
CRC32 checksum = new CRC32();
|
||||
checksum.update(buffer.toByteArray());
|
||||
output.writeLong(checksum.getValue());
|
||||
}
|
||||
return buffer.toByteArray();
|
||||
}
|
||||
|
||||
private static Contents decode(byte[] bytes) throws IOException {
|
||||
if (bytes.length < Long.BYTES) {
|
||||
throw new IOException("cache file is truncated");
|
||||
}
|
||||
CRC32 checksum = new CRC32();
|
||||
checksum.update(bytes, 0, bytes.length - Long.BYTES);
|
||||
if (ByteBuffer.wrap(bytes, bytes.length - Long.BYTES, Long.BYTES).getLong() != checksum.getValue()) {
|
||||
throw new IOException("cache checksum does not match");
|
||||
}
|
||||
DataInputStream input = new DataInputStream(new ByteArrayInputStream(bytes, 0, bytes.length - Long.BYTES));
|
||||
if (input.readInt() != MAGIC) {
|
||||
throw new IOException("not a saved terrain status cache");
|
||||
}
|
||||
int version = input.readInt();
|
||||
if (version != VERSION) {
|
||||
throw new IOException("unsupported cache version " + version);
|
||||
}
|
||||
long scanSeconds = input.readLong();
|
||||
int regionCount = input.readInt();
|
||||
if (regionCount < 0) {
|
||||
throw new IOException("invalid region count");
|
||||
}
|
||||
Long2ObjectOpenHashMap<Region> regions = new Long2ObjectOpenHashMap<>(Math.min(regionCount, 65536));
|
||||
for (int index = 0; index < regionCount; index++) {
|
||||
int x = input.readInt();
|
||||
int z = input.readInt();
|
||||
long size = input.readLong();
|
||||
String fileKey = input.readUTF();
|
||||
int count = input.readUnsignedShort();
|
||||
if (size < HEADER_BYTES || count > SLOTS) {
|
||||
throw new IOException("invalid region entry");
|
||||
}
|
||||
int[] slots = new int[count];
|
||||
int[] locations = new int[count];
|
||||
int[] timestamps = new int[count];
|
||||
BitSet terrain = new BitSet(count);
|
||||
int previousSlot = -1;
|
||||
for (int entry = 0; entry < count; entry++) {
|
||||
int slot = input.readUnsignedShort();
|
||||
if (slot >= SLOTS || slot <= previousSlot) {
|
||||
throw new IOException("invalid chunk slot");
|
||||
}
|
||||
previousSlot = slot;
|
||||
slots[entry] = slot;
|
||||
locations[entry] = input.readInt();
|
||||
timestamps[entry] = input.readInt();
|
||||
terrain.set(entry, input.readBoolean());
|
||||
}
|
||||
if (regions.put(ChunkGenerationOwnership.packChunk(x, z),
|
||||
new Region(x, z, size, fileKey, slots, locations, timestamps, terrain)) != null) {
|
||||
throw new IOException("duplicate region entry");
|
||||
}
|
||||
}
|
||||
if (input.available() != 0) {
|
||||
throw new IOException("unexpected trailing data");
|
||||
}
|
||||
return new Contents(scanSeconds, regions);
|
||||
}
|
||||
|
||||
final class Update {
|
||||
private final int regionX;
|
||||
private final int regionZ;
|
||||
private final Header header;
|
||||
private final int[] locations = new int[SLOTS];
|
||||
private final int[] timestamps = new int[SLOTS];
|
||||
private final BitSet known = new BitSet(SLOTS);
|
||||
private final BitSet terrain = new BitSet(SLOTS);
|
||||
|
||||
private Update(int regionX, int regionZ, Header header) {
|
||||
this.regionX = regionX;
|
||||
this.regionZ = regionZ;
|
||||
this.header = header;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a freshly decoded bit. Call only after the region was confirmed unchanged during decoding.
|
||||
*/
|
||||
void record(int slot, int location, int timestamp, boolean hasTerrain) {
|
||||
if (reusable(location, timestamp, scanSeconds)) {
|
||||
keep(slot, location, timestamp, hasTerrain);
|
||||
} else {
|
||||
known.clear(slot);
|
||||
}
|
||||
}
|
||||
|
||||
void commit() {
|
||||
int count = known.cardinality();
|
||||
int[] slots = new int[count];
|
||||
int[] storedLocations = new int[count];
|
||||
int[] storedTimestamps = new int[count];
|
||||
BitSet storedTerrain = new BitSet(count);
|
||||
int entry = 0;
|
||||
for (int slot = known.nextSetBit(0); slot >= 0; slot = known.nextSetBit(slot + 1)) {
|
||||
slots[entry] = slot;
|
||||
storedLocations[entry] = locations[slot];
|
||||
storedTimestamps[entry] = timestamps[slot];
|
||||
storedTerrain.set(entry, terrain.get(slot));
|
||||
entry++;
|
||||
}
|
||||
next.put(ChunkGenerationOwnership.packChunk(regionX, regionZ), new Region(regionX, regionZ,
|
||||
header.size(), header.fileKey(), slots, storedLocations, storedTimestamps, storedTerrain));
|
||||
}
|
||||
|
||||
private void keep(int slot, int location, int timestamp, boolean hasTerrain) {
|
||||
locations[slot] = location;
|
||||
timestamps[slot] = timestamp;
|
||||
known.set(slot);
|
||||
terrain.set(slot, hasTerrain);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The 8 KiB header of a region file together with the identity of the file it came from.
|
||||
*/
|
||||
record Header(String fileKey, long size, byte[] bytes) {
|
||||
static final int BYTES = HEADER_BYTES;
|
||||
|
||||
static Header read(Path file) throws IOException {
|
||||
Path normalized = file.toAbsolutePath().normalize();
|
||||
BasicFileAttributes attributes = Files.readAttributes(normalized, BasicFileAttributes.class,
|
||||
LinkOption.NOFOLLOW_LINKS);
|
||||
if (!attributes.isRegularFile() || attributes.size() < HEADER_BYTES) {
|
||||
throw new IOException("Saved chunk region header is unavailable: " + normalized);
|
||||
}
|
||||
byte[] bytes = new byte[HEADER_BYTES];
|
||||
try (FileChannel input = FileChannel.open(normalized, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) {
|
||||
if (input.read(buffer) < 0) {
|
||||
throw new IOException("Truncated saved chunk region: " + normalized);
|
||||
}
|
||||
}
|
||||
}
|
||||
Object key = attributes.fileKey();
|
||||
return new Header(key == null ? "" : key.toString(), attributes.size(), bytes);
|
||||
}
|
||||
|
||||
int location(int slot) {
|
||||
return word(slot * Integer.BYTES);
|
||||
}
|
||||
|
||||
int timestamp(int slot) {
|
||||
return word(4096 + slot * Integer.BYTES);
|
||||
}
|
||||
|
||||
boolean sameHeader(Header other) {
|
||||
return fileKey.equals(other.fileKey) && Arrays.equals(bytes, other.bytes);
|
||||
}
|
||||
|
||||
private int word(int offset) {
|
||||
return (bytes[offset] & 255) << 24 | (bytes[offset + 1] & 255) << 16
|
||||
| (bytes[offset + 2] & 255) << 8 | bytes[offset + 3] & 255;
|
||||
}
|
||||
}
|
||||
|
||||
record Region(int x, int z, long size, String fileKey, int[] slots, int[] locations, int[] timestamps,
|
||||
BitSet terrain) {
|
||||
boolean matches(Header header) {
|
||||
return fileKey.equals(header.fileKey()) && header.size() >= size;
|
||||
}
|
||||
}
|
||||
|
||||
private record Contents(long scanSeconds, Long2ObjectOpenHashMap<Region> regions) {
|
||||
static final Contents EMPTY = new Contents(0L, new Long2ObjectOpenHashMap<>());
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package art.arcane.iris.world.storage.matter;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Slice ids that older Iris releases wrote into saved matter and that a newer jar may no longer register.
|
||||
* A reader skips these instead of failing; every other unknown id stays a hard error.
|
||||
*/
|
||||
public final class RetiredMatterSlices {
|
||||
public static final String TREE_CANOPY = "art.arcane.iris.generation.mantle.TreeCanopy";
|
||||
|
||||
private static final Set<String> IDS = Set.of(TREE_CANOPY);
|
||||
|
||||
private RetiredMatterSlices() {
|
||||
}
|
||||
|
||||
public static boolean isRetired(String id) {
|
||||
return IDS.contains(id);
|
||||
}
|
||||
}
|
||||
-74
@@ -2,20 +2,14 @@ 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;
|
||||
@@ -23,9 +17,6 @@ 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;
|
||||
@@ -37,71 +28,6 @@ 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();
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
-153
@@ -1,153 +0,0 @@
|
||||
package art.arcane.iris.generation.mantle;
|
||||
|
||||
import art.arcane.iris.world.storage.matter.IrisMatterSupport;
|
||||
import art.arcane.iris.world.storage.matter.RetiredMatterSlices;
|
||||
import art.arcane.volmlib.util.matter.IrisMatter;
|
||||
import art.arcane.volmlib.util.matter.Matter;
|
||||
import art.arcane.volmlib.util.matter.MatterHeader;
|
||||
import art.arcane.volmlib.util.matter.MatterSlice;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ObjectContinuationRetiredSliceTest {
|
||||
@Test
|
||||
public void retiredUnregisteredSliceIsSkippedAndRestDecodes() throws Exception {
|
||||
IrisMatterSupport.ensureRegistered();
|
||||
byte[] canopy = sliceBytes(TreeCanopy.class, TreeCanopy.INSTANCE);
|
||||
byte[] number = sliceBytes(Integer.class, 42);
|
||||
byte[] payload = payload(List.of(canopy, number));
|
||||
|
||||
Object registered = unregister(RetiredMatterSlices.TREE_CANOPY);
|
||||
try {
|
||||
assertEquals(null, IrisMatter.getSliceType(RetiredMatterSlices.TREE_CANOPY));
|
||||
Matter decoded = fragment(payload).decode();
|
||||
assertFalse(decoded.hasSlice(TreeCanopy.class));
|
||||
assertEquals(Integer.valueOf(42), decoded.getSlice(Integer.class).get(1, 2, 3));
|
||||
} finally {
|
||||
restore(registered);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void duplicateRetiredUnregisteredSliceFails() throws Exception {
|
||||
IrisMatterSupport.ensureRegistered();
|
||||
byte[] canopy = sliceBytes(TreeCanopy.class, TreeCanopy.INSTANCE);
|
||||
byte[] payload = payload(List.of(canopy, canopy));
|
||||
|
||||
Object registered = unregister(RetiredMatterSlices.TREE_CANOPY);
|
||||
try {
|
||||
IOException failure = assertThrows(IOException.class, () -> fragment(payload).decode());
|
||||
assertTrue(failure.getMessage(), failure.getMessage().startsWith("Duplicate object continuation slice type"));
|
||||
} finally {
|
||||
restore(registered);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unknownSliceStillFails() throws Exception {
|
||||
IrisMatterSupport.ensureRegistered();
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
DataOutputStream output = new DataOutputStream(bytes);
|
||||
output.writeUTF("art.arcane.iris.test.NeverRegistered");
|
||||
output.writeInt(7);
|
||||
byte[] payload = payload(List.of(bytes.toByteArray(), sliceBytes(Integer.class, 42)));
|
||||
|
||||
IOException failure = assertThrows(IOException.class, () -> fragment(payload).decode());
|
||||
assertEquals("Unknown object continuation slice type: art.arcane.iris.test.NeverRegistered", failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void duplicateRegisteredSliceFails() throws Exception {
|
||||
IrisMatterSupport.ensureRegistered();
|
||||
byte[] number = sliceBytes(Integer.class, 42);
|
||||
byte[] payload = payload(List.of(number, number));
|
||||
|
||||
IOException failure = assertThrows(IOException.class, () -> fragment(payload).decode());
|
||||
assertEquals("Duplicate object continuation slice type: " + IrisMatter.getSliceId(Integer.class), failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registeredRetiredSliceStillDecodes() throws Exception {
|
||||
IrisMatterSupport.ensureRegistered();
|
||||
byte[] payload = payload(List.of(sliceBytes(TreeCanopy.class, TreeCanopy.INSTANCE)));
|
||||
|
||||
Matter decoded = fragment(payload).decode();
|
||||
assertEquals(TreeCanopy.INSTANCE, decoded.getSlice(TreeCanopy.class).get(1, 2, 3));
|
||||
}
|
||||
|
||||
private static <T> byte[] sliceBytes(Class<T> type, T value) throws IOException {
|
||||
Matter matter = new IrisMatter(16, 16, 16);
|
||||
MatterSlice<T> slice = matter.slice(type);
|
||||
slice.set(1, 2, 3, value);
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
slice.write(new DataOutputStream(bytes));
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] payload(List<byte[]> slices) throws IOException {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
DataOutputStream output = new DataOutputStream(bytes);
|
||||
output.writeInt(16);
|
||||
output.writeInt(16);
|
||||
output.writeInt(16);
|
||||
output.writeByte(slices.size());
|
||||
new MatterHeader().write(output);
|
||||
for (byte[] slice : slices) {
|
||||
output.writeInt(slice.length);
|
||||
output.write(slice);
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
private static ObjectContinuationBundle.Fragment fragment(byte[] payload) {
|
||||
return new ObjectContinuationBundle.Fragment(
|
||||
new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.STATIC, 0, 0, 0),
|
||||
new ObjectContinuationBundle.Bounds(0, 0, 16, 0),
|
||||
List.of(new ObjectContinuationBundle.ChunkPosition(0, 0), new ObjectContinuationBundle.ChunkPosition(1, 0)),
|
||||
payload);
|
||||
}
|
||||
|
||||
private static Field registryField() throws ReflectiveOperationException {
|
||||
Field field = IrisMatter.class.getDeclaredField("sliceRegistry");
|
||||
field.setAccessible(true);
|
||||
return field;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Object unregister(String id) throws ReflectiveOperationException {
|
||||
Field field = registryField();
|
||||
Object registry = field.get(null);
|
||||
Class<?> registryType = registry.getClass();
|
||||
Method byTypeAccessor = registryType.getDeclaredMethod("byType");
|
||||
Method byIdAccessor = registryType.getDeclaredMethod("byId");
|
||||
byTypeAccessor.setAccessible(true);
|
||||
byIdAccessor.setAccessible(true);
|
||||
Map<Class<?>, Object> byType = new HashMap<>((Map<Class<?>, Object>) byTypeAccessor.invoke(registry));
|
||||
Map<String, Object> byId = new HashMap<>((Map<String, Object>) byIdAccessor.invoke(registry));
|
||||
Class<?> type = IrisMatter.getSliceType(id);
|
||||
byType.remove(type);
|
||||
byId.remove(id);
|
||||
Constructor<?> constructor = registryType.getDeclaredConstructor(Map.class, Map.class);
|
||||
constructor.setAccessible(true);
|
||||
field.set(null, constructor.newInstance(Map.copyOf(byType), Map.copyOf(byId)));
|
||||
return registry;
|
||||
}
|
||||
|
||||
private static void restore(Object registry) throws ReflectiveOperationException {
|
||||
registryField().set(null, registry);
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ public class NoiseSeedCohesionTest {
|
||||
private static final double[] COORDINATES = {-29_999_983.25D, -513D, -64D, -1D, 0D, 0.125D, 17D, 64D, 8192D, 29_999_983.25D};
|
||||
private static final double PINNED_SAMPLE_SCALE = 1.0E9D;
|
||||
private static final long PINNED_HASH_WINDOWS = 6074446696529759284L;
|
||||
private static final long PINNED_HASH_MAC = 2357650562814976004L;
|
||||
private static final long PINNED_HASH_MAC = -602781966673993721L;
|
||||
|
||||
@Test
|
||||
public void allStylesRetainPinnedSamples() {
|
||||
|
||||
-90
@@ -339,96 +339,6 @@ public class IrisComplexSurfaceBiomeTest {
|
||||
assertSame(shore, resolved);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shorelineWithoutShoreBiomesKeepsTheBaseBiome() {
|
||||
IrisBiome base = mock(IrisBiome.class);
|
||||
IrisRegion region = mock(IrisRegion.class);
|
||||
doReturn(false).when(base).isShore();
|
||||
doReturn(3D).when(region).getShoreHeight(12D, 18D);
|
||||
doReturn(1D).when(region).getShoreHeightMin();
|
||||
doReturn(5D).when(region).getShoreHeightMax();
|
||||
|
||||
IrisBiome resolved = IrisComplex.resolveSurfaceBiome(
|
||||
63D,
|
||||
base,
|
||||
region,
|
||||
12D,
|
||||
18D,
|
||||
63D,
|
||||
constant(base),
|
||||
constant(base),
|
||||
IrisComplex.NO_BIOMES,
|
||||
constantSlope(0D)
|
||||
);
|
||||
|
||||
assertSame(base, resolved);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void belowFluidWithoutSeaBiomesKeepsTheBaseBiome() {
|
||||
IrisBiome base = mock(IrisBiome.class);
|
||||
IrisRegion region = mock(IrisRegion.class);
|
||||
doReturn(false).when(base).isShore();
|
||||
doReturn(true).when(base).isLand();
|
||||
doReturn(false).when(base).isAquatic();
|
||||
doReturn(3D).when(region).getShoreHeight(12D, 18D);
|
||||
doReturn(1D).when(region).getShoreHeightMin();
|
||||
doReturn(5D).when(region).getShoreHeightMax();
|
||||
|
||||
IrisBiome resolved = IrisComplex.resolveSurfaceBiome(
|
||||
50D,
|
||||
base,
|
||||
region,
|
||||
12D,
|
||||
18D,
|
||||
63D,
|
||||
constant(base),
|
||||
IrisComplex.NO_BIOMES,
|
||||
IrisComplex.NO_BIOMES,
|
||||
constantSlope(0D)
|
||||
);
|
||||
|
||||
assertSame(base, resolved);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void continentSeaInARegionWithoutSeaBiomesPicksFromLand() {
|
||||
IrisRegion sealess = mock(IrisRegion.class);
|
||||
IrisRegion coastal = mock(IrisRegion.class);
|
||||
IrisBiome sea = mock(IrisBiome.class);
|
||||
java.util.Map<IrisRegion, java.util.Map<InferredType, ProceduralStream<IrisBiome>>> streams =
|
||||
IrisComplex.compileInferredBiomeStreams(List.of(sealess, coastal),
|
||||
(IrisRegion region, InferredType type) -> region == sealess && type == InferredType.SEA
|
||||
? IrisComplex.NO_BIOMES : constant(sea));
|
||||
|
||||
assertEquals(InferredType.LAND, IrisComplex.baseType(streams, sealess, InferredType.SEA));
|
||||
assertEquals(InferredType.LAND, IrisComplex.baseType(streams, sealess, InferredType.LAND));
|
||||
assertEquals(InferredType.SEA, IrisComplex.baseType(streams, coastal, InferredType.SEA));
|
||||
assertTrue(IrisComplex.lacks(streams, InferredType.SEA));
|
||||
assertFalse(IrisComplex.lacks(IrisComplex.compileInferredBiomeStreams(List.of(coastal),
|
||||
(IrisRegion region, InferredType type) -> constant(sea)), InferredType.SEA));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void regionWithoutUsableLandBiomesFailsNamingIt() {
|
||||
IrisRegion listed = new IrisRegion();
|
||||
listed.setLoadKey("void");
|
||||
listed.setLandBiomes(new KList<>("gone"));
|
||||
IrisRegion unlisted = new IrisRegion();
|
||||
unlisted.setLoadKey("bare");
|
||||
|
||||
IllegalStateException excluded = assertThrows(IllegalStateException.class,
|
||||
() -> IrisComplex.requireLandBiomes(listed, new KList<>()));
|
||||
IllegalStateException empty = assertThrows(IllegalStateException.class,
|
||||
() -> IrisComplex.requireLandBiomes(unlisted, new KList<>()));
|
||||
KList<IrisBiome> land = new KList<>(new IrisBiome());
|
||||
|
||||
assertTrue(excluded.getMessage(), excluded.getMessage().contains("Region 'void'"));
|
||||
assertTrue(excluded.getMessage(), excluded.getMessage().contains("Minecraft version"));
|
||||
assertTrue(empty.getMessage(), empty.getMessage().contains("Region 'bare'"));
|
||||
assertSame(land, IrisComplex.requireLandBiomes(unlisted, land));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void raisedAquaticBiomeReturnsToLand() {
|
||||
IrisBiome aquatic = mock(IrisBiome.class);
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
package art.arcane.iris.pack;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PackValidatorRegionLandBiomesTest {
|
||||
@Rule
|
||||
public TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||
|
||||
@Test
|
||||
public void regionWithoutLandBiomesIsBlockingAndNamesTheRegion() throws IOException {
|
||||
List<String> errors = validate("{\"seaBiomes\":[\"ocean\"],\"shoreBiomes\":[\"ocean\"]}");
|
||||
|
||||
assertEquals(List.of("Region 'island' has no landBiomes; every region needs at least one land biome."), errors);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void regionWithOnlyMissingLandBiomesIsBlocking() throws IOException {
|
||||
List<String> errors = validate("{\"landBiomes\":[\"absent\"],\"seaBiomes\":[\"ocean\"]}");
|
||||
|
||||
assertEquals(List.of("Region 'island' has no landBiomes; every region needs at least one land biome."), errors);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void regionWithLandButNoSeaOrShoreBiomesIsValid() throws IOException {
|
||||
List<String> errors = validate("{\"landBiomes\":[\"ocean\"]}");
|
||||
|
||||
assertTrue(errors.toString(), errors.isEmpty());
|
||||
}
|
||||
|
||||
private List<String> validate(String region) throws IOException {
|
||||
File pack = temporaryFolder.newFolder();
|
||||
File dimensions = new File(pack, PackValidator.DIMENSIONS_FOLDER);
|
||||
File regions = new File(pack, "regions");
|
||||
File biomes = new File(pack, "biomes");
|
||||
assertTrue(dimensions.mkdirs() && regions.mkdirs() && biomes.mkdirs());
|
||||
File dimension = new File(dimensions, "main.json");
|
||||
Files.writeString(dimension.toPath(), "{\"regions\":[\"island\"]}");
|
||||
Files.writeString(new File(regions, "island.json").toPath(), region);
|
||||
Files.writeString(new File(biomes, "ocean.json").toPath(), "{}");
|
||||
List<String> errors = new ArrayList<>();
|
||||
PackDimensionValidator.validateDimensions(pack, new File[]{dimension}, errors, new ArrayList<>());
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
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;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
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() {
|
||||
JSONObject rule = bedRule(Dimension.OVERWORLD);
|
||||
|
||||
assertEquals("when_dark", rule.getString("can_sleep"));
|
||||
assertEquals("always", rule.getString("can_set_spawn"));
|
||||
assertTrue(rule.has("error_message"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void netherBedsExplodeBefore263() {
|
||||
assertNoSleep(bedRule(fixer, Dimension.NETHER), "explodes", "destroy_on_use");
|
||||
}
|
||||
|
||||
@Test
|
||||
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 assertNoSleep(JSONObject rule, String presentKey, String absentKey) {
|
||||
assertEquals("never", rule.getString("can_sleep"));
|
||||
assertEquals("never", rule.getString("can_set_spawn"));
|
||||
assertTrue(rule.getBoolean(presentKey));
|
||||
assertFalse(rule.has(absentKey));
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,8 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.DeflaterOutputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
@@ -120,215 +118,6 @@ public final class SavedTerrainRecoveryScanTest {
|
||||
assertFalse(Files.exists(world.resolve("region")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void warmCacheReusesStatusWithoutDecodingUnchangedChunks() throws Exception {
|
||||
for (int regionBytes : new int[]{8192, 4 * 1024 * 1024}) {
|
||||
Path world = temporaryFolder.newFolder().toPath();
|
||||
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
|
||||
writeChunkGrid(world);
|
||||
WorldChunkInventory inventory = WorldChunkInventory.scan(world);
|
||||
WorldChunkInventory expected = uncachedScan(world, inventory);
|
||||
assertSameChunks(inventory, expected, cachedScan(world, cacheFile, regionBytes, (x, z) -> false));
|
||||
assertTrue(Files.isRegularFile(cacheFile));
|
||||
corruptAll(world);
|
||||
assertThrows(IOException.class, () -> uncachedScan(world, inventory));
|
||||
assertSameChunks(inventory, expected, cachedScan(world, cacheFile, regionBytes, (x, z) -> false));
|
||||
assertSameChunks(inventory, expected, cachedScan(world, cacheFile, regionBytes, (x, z) -> false));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ownershipIsAppliedOnEveryScanInsteadOfCached() throws Exception {
|
||||
Path world = temporaryFolder.newFolder().toPath();
|
||||
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
|
||||
write(world, new Chunk(0, 0, 2, false, encode(0, 0, "minecraft:biomes")), OLD);
|
||||
write(world, new Chunk(1, 0, 2, false, encode(1, 0, "minecraft:full")), OLD);
|
||||
WorldChunkInventory inventory = WorldChunkInventory.scan(world);
|
||||
WorldChunkInventory first = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> x == 0);
|
||||
assertEquals(2, first.size());
|
||||
WorldChunkInventory second = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
|
||||
assertEquals(1, second.size());
|
||||
assertTrue(second.contains(1, 0));
|
||||
corruptAll(world);
|
||||
assertEquals(2, cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> x == 0).size());
|
||||
WorldChunkInventory third = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
|
||||
assertEquals(1, third.size());
|
||||
assertTrue(third.contains(1, 0));
|
||||
assertSameChunks(inventory, second, third);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void changedHeaderWordsAreDecodedAgain() throws Exception {
|
||||
Path world = temporaryFolder.newFolder().toPath();
|
||||
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
|
||||
writeChunkGrid(world);
|
||||
cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
|
||||
write(world, new Chunk(2, 0, 2, false, encode(2, 0, "minecraft:biomes")), OLD);
|
||||
WorldChunkInventory inventory = WorldChunkInventory.scan(world);
|
||||
WorldChunkInventory rewritten = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
|
||||
assertSameChunks(inventory, uncachedScan(world, inventory), rewritten);
|
||||
assertFalse(rewritten.contains(2, 0));
|
||||
|
||||
cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
|
||||
setTimestamp(world, 3, 0, OLD + 1);
|
||||
corrupt(world, 3, 0);
|
||||
IOException failure = assertThrows(IOException.class,
|
||||
() -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false));
|
||||
assertTrue(failure.getMessage().contains("3,0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void chunksSavedNearTheScanTimeAreDecodedAgain() throws Exception {
|
||||
Path world = temporaryFolder.newFolder().toPath();
|
||||
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
|
||||
writeChunkGrid(world);
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
setTimestamp(world, 4, 1, now);
|
||||
setTimestamp(world, 5, 1, now + 30);
|
||||
cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
|
||||
corrupt(world, 4, 1);
|
||||
assertTrue(assertThrows(IOException.class,
|
||||
() -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false)).getMessage().contains("4,1"));
|
||||
write(world, new Chunk(4, 1, 2, false, encode(4, 1, "minecraft:full")), OLD);
|
||||
cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
|
||||
corrupt(world, 5, 1);
|
||||
assertTrue(assertThrows(IOException.class,
|
||||
() -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false)).getMessage().contains("5,1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void externalPayloadsAreDecodedOnEveryScan() throws Exception {
|
||||
Path world = temporaryFolder.newFolder().toPath();
|
||||
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
|
||||
writeChunkGrid(world);
|
||||
write(world, new Chunk(6, 2, 2, false, encode(6, 2, "minecraft:full")), OLD);
|
||||
write(world, new Chunk(7, 2, 2, true, encode(7, 2, "minecraft:full")), OLD);
|
||||
for (int regionBytes : new int[]{8192, 4 * 1024 * 1024}) {
|
||||
cachedScan(world, cacheFile, regionBytes, (x, z) -> false);
|
||||
Path external = world.resolve("region").resolve("c.7.2.mcc");
|
||||
byte[] payload = Files.readAllBytes(external);
|
||||
Files.write(external, new byte[]{1, 2, 3});
|
||||
assertTrue(assertThrows(IOException.class,
|
||||
() -> cachedScan(world, cacheFile, regionBytes, (x, z) -> false)).getMessage().contains("7,2"));
|
||||
Files.write(external, payload);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unreadableCacheFallsBackToAFullScan() throws Exception {
|
||||
Path world = temporaryFolder.newFolder().toPath();
|
||||
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
|
||||
writeChunkGrid(world);
|
||||
WorldChunkInventory inventory = WorldChunkInventory.scan(world);
|
||||
WorldChunkInventory expected = uncachedScan(world, inventory);
|
||||
cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
|
||||
byte[] valid = Files.readAllBytes(cacheFile);
|
||||
|
||||
byte[] flipped = valid.clone();
|
||||
flipped[flipped.length / 2] ^= 1;
|
||||
byte[] wrongVersion = valid.clone();
|
||||
wrongVersion[7] = 99;
|
||||
CRC32 checksum = new CRC32();
|
||||
checksum.update(wrongVersion, 0, wrongVersion.length - Long.BYTES);
|
||||
ByteBuffer.wrap(wrongVersion, wrongVersion.length - Long.BYTES, Long.BYTES).putLong(checksum.getValue());
|
||||
for (byte[] broken : new byte[][]{flipped, wrongVersion, new byte[]{1, 2, 3}, new byte[0]}) {
|
||||
Files.write(cacheFile, broken);
|
||||
assertSameChunks(inventory, expected, cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false));
|
||||
}
|
||||
|
||||
Files.write(cacheFile, flipped);
|
||||
corrupt(world, 1, 1);
|
||||
assertThrows(IOException.class, () -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void staticStartupScanWritesTheCacheOnlyAfterSuccess() throws Exception {
|
||||
Path world = temporaryFolder.newFolder().toPath();
|
||||
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
|
||||
writeChunkGrid(world);
|
||||
corrupt(world, 1, 1);
|
||||
assertThrows(IOException.class, () -> SavedTerrainRecoveryScan.scan(world, WorldChunkInventory.scan(world),
|
||||
(x, z) -> false, cacheFile));
|
||||
assertFalse(Files.exists(cacheFile));
|
||||
write(world, new Chunk(1, 1, 2, false, encode(1, 1, "minecraft:full")), OLD);
|
||||
WorldChunkInventory inventory = WorldChunkInventory.scan(world);
|
||||
WorldChunkInventory expected = uncachedScan(world, inventory);
|
||||
assertSameChunks(inventory, expected, SavedTerrainRecoveryScan.scan(world, inventory, (x, z) -> false, cacheFile));
|
||||
corruptAll(world);
|
||||
assertSameChunks(inventory, expected, SavedTerrainRecoveryScan.scan(world, inventory, (x, z) -> false, cacheFile));
|
||||
}
|
||||
|
||||
private static final long OLD = 1_700_000_000L;
|
||||
|
||||
private static void writeChunkGrid(Path world) throws IOException {
|
||||
for (int x = 0; x < 12; x++) {
|
||||
for (int z = 0; z < 12; z++) {
|
||||
write(world, new Chunk(x, z, 2, false,
|
||||
encode(x, z, (x + z) % 3 == 0 ? "minecraft:biomes" : "minecraft:full")), OLD);
|
||||
}
|
||||
}
|
||||
write(world, new Chunk(40, 3, 2, false, encode(40, 3, "minecraft:noise")), OLD);
|
||||
}
|
||||
|
||||
private static WorldChunkInventory uncachedScan(Path world, WorldChunkInventory inventory) throws IOException {
|
||||
try (SavedTerrainChunkReader.StatusReader reader = new SavedTerrainChunkReader.StatusReader(world)) {
|
||||
return inventory.filter((x, z) -> SavedTerrainChunk.hasTerrain(reader.readStatus(x, z)));
|
||||
}
|
||||
}
|
||||
|
||||
private static WorldChunkInventory cachedScan(Path world, Path cacheFile, int regionBytes,
|
||||
WorldChunkInventory.ChunkPredicate retained) throws IOException {
|
||||
SavedTerrainStatusCache cache = SavedTerrainStatusCache.load(cacheFile, world);
|
||||
WorldChunkInventory result;
|
||||
try (SavedTerrainRecoveryScan scan = new SavedTerrainRecoveryScan(world,
|
||||
new SavedTerrainRecoveryScan.Limits(2, regionBytes), cache)) {
|
||||
result = scan.filter(WorldChunkInventory.scan(world), retained);
|
||||
}
|
||||
cache.save();
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void assertSameChunks(WorldChunkInventory inventory, WorldChunkInventory expected,
|
||||
WorldChunkInventory actual) throws IOException {
|
||||
assertEquals(expected.size(), actual.size());
|
||||
inventory.forEach((x, z) -> assertEquals(expected.contains(x, z), actual.contains(x, z)));
|
||||
}
|
||||
|
||||
private static void corruptAll(Path world) throws IOException {
|
||||
WorldChunkInventory.scan(world).forEach((x, z) -> corrupt(world, x, z));
|
||||
}
|
||||
|
||||
private static void corrupt(Path world, int x, int z) throws IOException {
|
||||
try (RandomAccessFile file = new RandomAccessFile(regionFile(world, x, z).toFile(), "rw")) {
|
||||
file.seek(slot(x, z) * 4L);
|
||||
int sector = file.readInt() >>> 8;
|
||||
file.seek(sector * 4096L + 4);
|
||||
int compression = file.readUnsignedByte();
|
||||
file.seek(sector * 4096L + 4);
|
||||
file.writeByte((compression & 128) | 99);
|
||||
}
|
||||
}
|
||||
|
||||
private static void setTimestamp(Path world, int x, int z, long seconds) throws IOException {
|
||||
try (RandomAccessFile file = new RandomAccessFile(regionFile(world, x, z).toFile(), "rw")) {
|
||||
file.seek(4096L + slot(x, z) * 4L);
|
||||
file.writeInt((int) seconds);
|
||||
}
|
||||
}
|
||||
|
||||
private static Path regionFile(Path world, int x, int z) {
|
||||
return world.resolve("region").resolve("r." + Math.floorDiv(x, 32) + "." + Math.floorDiv(z, 32) + ".mca");
|
||||
}
|
||||
|
||||
private static int slot(int x, int z) {
|
||||
return Math.floorMod(z, 32) * 32 + Math.floorMod(x, 32);
|
||||
}
|
||||
|
||||
private static void write(Path world, Chunk chunk, long timestamp) throws IOException {
|
||||
write(world, chunk);
|
||||
setTimestamp(world, chunk.x(), chunk.z(), timestamp);
|
||||
}
|
||||
|
||||
private static byte[] encode(int x, int z, String status) throws IOException {
|
||||
CompoundTag root = new CompoundTag();
|
||||
root.putInt("xPos", x);
|
||||
|
||||
Reference in new issue
Block a user