Merge upstream port lane b

This commit is contained in:
piexel committed 2026-11-10 01:31:37 +01:00
commit c448da1155
82 files changed
+2029 -881

No files matched your search

@@ -0,0 +1,129 @@
package art.arcane.iris.core.gui;
import art.arcane.iris.core.pregenerator.IrisPregenerator;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class PregeneratorJobOwnerDrainTest {
@Test
public void ownerPollingCompletesTheRequestThatKeepsTheWorkerAlive() throws Exception {
try (Fixture fixture = new Fixture()) {
Thread owner = Thread.currentThread();
AtomicInteger polls = new AtomicInteger();
assertTrue(PregeneratorJob.shutdownAndWait(1_000L, () -> {
assertSame(owner, Thread.currentThread());
polls.incrementAndGet();
fixture.completion.complete(null);
}));
assertTrue(polls.get() > 0);
assertFalse(fixture.worker.isAlive());
assertNull(PregeneratorJob.getInstance());
verify(fixture.pregenerator).close();
}
}
@Test
public void timeoutKeepsThePendingJobAndDoesNotCompleteItsRequest() throws Exception {
try (Fixture fixture = new Fixture()) {
AtomicInteger polls = new AtomicInteger();
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> PregeneratorJob.shutdownAndWait(20L, polls::incrementAndGet));
assertEquals("Timed out while stopping the Iris pregenerator after 20ms.", failure.getMessage());
assertTrue(polls.get() > 0);
assertTrue(fixture.worker.isAlive());
assertFalse(fixture.completion.isDone());
assertSame(fixture.job, PregeneratorJob.getInstance());
}
}
@Test
public void interruptedOwnerKeepsTheJobAndOriginalInterruption() throws Exception {
try (Fixture fixture = new Fixture()) {
try {
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> PregeneratorJob.shutdownAndWait(1_000L, () -> Thread.currentThread().interrupt()));
assertTrue(failure.getCause() instanceof InterruptedException);
assertTrue(Thread.currentThread().isInterrupted());
assertSame(fixture.job, PregeneratorJob.getInstance());
assertFalse(fixture.completion.isDone());
} finally {
Thread.interrupted();
}
}
}
@Test
public void ownerTaskFailureEscapesWithItsCauseAndRetainsTheJob() throws Exception {
try (Fixture fixture = new Fixture()) {
IllegalStateException expected = new IllegalStateException("Native task failed", new Exception("Chunk cause"));
IllegalStateException actual = assertThrows(IllegalStateException.class,
() -> PregeneratorJob.shutdownAndWait(1_000L, () -> {
throw expected;
}));
assertSame(expected, actual);
assertSame(expected.getCause(), actual.getCause());
assertSame(fixture.job, PregeneratorJob.getInstance());
assertFalse(fixture.completion.isDone());
}
}
private static final class Fixture implements AutoCloseable {
private final PregeneratorJob job = mock(PregeneratorJob.class, CALLS_REAL_METHODS);
private final IrisPregenerator pregenerator = mock(IrisPregenerator.class);
private final CompletableFuture<Void> completion = new CompletableFuture<>();
private final AtomicReference<PregeneratorJob> instance;
private final PregeneratorJob previous;
private final Thread worker;
private Fixture() throws Exception {
CountDownLatch started = new CountDownLatch(1);
worker = new Thread(() -> {
started.countDown();
completion.join();
}, "Pregen owner drain test");
set("worker", worker);
set("pregenerator", pregenerator);
instance = instance();
previous = instance.getAndSet(job);
worker.start();
assertTrue(started.await(5L, TimeUnit.SECONDS));
}
@Override
public void close() throws Exception {
completion.complete(null);
worker.join(5_000L);
instance.set(previous);
assertFalse(worker.isAlive());
}
private void set(String name, Object value) throws Exception {
Field field = PregeneratorJob.class.getDeclaredField(name);
field.setAccessible(true);
field.set(job, value);
}
@SuppressWarnings("unchecked")
private static AtomicReference<PregeneratorJob> instance() throws Exception {
Field field = PregeneratorJob.class.getDeclaredField("instance");
field.setAccessible(true);
return (AtomicReference<PregeneratorJob>) field.get(null);
}
}
}
@@ -0,0 +1,24 @@
package art.arcane.iris.core.lifecycle;
import art.arcane.iris.spi.IrisServices;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertNull;
public class IrisRuntimeStaticsTest {
@After
public void clearStatics() {
IrisRuntimeStatics.reset();
}
@Test
public void resetUnbindsEveryRegisteredService() {
IrisServices.register(Runnable.class, (Runnable) () -> {
});
IrisRuntimeStatics.reset();
assertNull(IrisServices.getOrNull(Runnable.class));
}
}
@@ -78,7 +78,7 @@ public class ModuleMantleComponentTest {
assertEquals(List.of(MantleFlag.of(first), MantleFlag.of(first + 1), MantleFlag.of(first + 2), MantleFlag.of(first + 3), MantleFlag.of(first + 4)),
components.stream().map(ModuleMantleComponent::getFlag).toList());
assertEquals(List.of(0, 1, 2, 3, 4), components.stream().map(ModuleMantleComponent::getPriority).toList());
assertEquals("a pack without objects or structures: caves 1, floating objects at least 16", List.of(1, 0, 16, 0, MARK_REACH),
assertEquals("a pack without objects or structures: caves 1, no floating objects", List.of(1, 0, 0, 0, MARK_REACH),
components.stream().map(ModuleMantleComponent::getRadius).toList());
assertEquals("disabledComponents: [iris:carve/caves] turns the cave pass off", List.of(false, true, true, true, true),
components.stream().map(ModuleMantleComponent::isEnabled).toList());
@@ -20,7 +20,6 @@ package art.arcane.iris.core.modules;
import art.arcane.iris.engine.UsableBlockPlatform;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineGeneration;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.project.hunk.Hunk;
@@ -68,7 +67,7 @@ public class PlannedBlocksTest {
public void placementsBlocksReadInWorldCoordinatesInVisitOrder() {
plan(20, 10, 33, planks);
plan(17, 40, 35, planks);
PlannedBlocks blocks = planned(true, false);
PlannedBlocks blocks = planned(true);
List<String> visited = new ArrayList<>();
blocks.visit(CHUNK, (x, y, z, block) -> visited.add(x + "," + y + "," + z + " " + block.key()));
@@ -79,20 +78,20 @@ public class PlannedBlocksTest {
}
@Test
public void aDimensionWithoutAMantleOrAChunkWithoutItPlansNothing() {
public void aDimensionWithoutAMantlePlansNothing() {
plan(20, 10, 33, planks);
PlannedBlocks blocks = planned(false);
List<BlockState> visited = new ArrayList<>();
for (PlannedBlocks blocks : List.of(planned(false, false), planned(true, true))) {
List<BlockState> visited = new ArrayList<>();
blocks.visit(CHUNK, (x, y, z, block) -> visited.add(block));
assertEquals(List.of(), visited);
assertNull(blocks.get(20, 10, 33));
}
blocks.visit(CHUNK, (x, y, z, block) -> visited.add(block));
assertEquals(List.of(), visited);
assertNull(blocks.get(20, 10, 33));
}
@Test
public void stagesCannotPlanBlocks() {
MantleLayer<BlockState> blocks = planned(true, false);
MantleLayer<BlockState> blocks = planned(true);
BlockState stone = BlockState.parse("minecraft:stone");
assertThrows(UnsupportedOperationException.class, () -> blocks.set(20, 10, 33, stone));
@@ -106,7 +105,7 @@ public class PlannedBlocksTest {
PlatformBlockState vanilla = UsableBlockPlatform.block("minecraft:note_block");
plan(20, 10, 33, custom);
PlatformBlockStates states = new PlatformBlockStates(key -> vanilla);
PlannedBlocks blocks = PlannedBlocks.of(engine(true, false), CHUNK, mantle::chunk, states);
PlannedBlocks blocks = PlannedBlocks.of(engine(true), CHUNK, mantle::chunk, states);
Hunk<PlatformBlockState> chunk = Hunk.newArrayHunk(16, SECTIONS * 16, 16);
BlockStateHunk hunk = new BlockStateHunk(chunk, states);
@@ -121,18 +120,15 @@ public class PlannedBlocksTest {
mantle.chunk(x >> 4, z >> 4).getOrCreate(y >> 4).slice(PlatformBlockState.class).set(x & 15, y & 15, z & 15, block);
}
private PlannedBlocks planned(boolean useMantle, boolean bypass) {
return PlannedBlocks.of(engine(useMantle, bypass), CHUNK, mantle::chunk, new PlatformBlockStates(UsableBlockPlatform::block));
private PlannedBlocks planned(boolean useMantle) {
return PlannedBlocks.of(engine(useMantle), CHUNK, mantle::chunk, new PlatformBlockStates(UsableBlockPlatform::block));
}
private static Engine engine(boolean useMantle, boolean bypass) {
private static Engine engine(boolean useMantle) {
IrisDimension dimension = mock(IrisDimension.class);
when(dimension.isUseMantle()).thenReturn(useMantle);
EngineGeneration generation = mock(EngineGeneration.class);
when(generation.bypassesMantleStages()).thenReturn(bypass);
Engine engine = mock(Engine.class);
when(engine.getDimension()).thenReturn(dimension);
when(engine.getGeneration()).thenReturn(generation);
return engine;
}
}
@@ -0,0 +1,84 @@
package art.arcane.iris.core.pregenerator;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.LogLevel;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
public class PregenDiagnosticsTest {
private final List<String> emitted = new ArrayList<>();
private final List<LogLevel> levels = new ArrayList<>();
private IrisPlatform previousPlatform;
@Before
public void captureLog() {
previousPlatform = IrisPlatforms.isBound() ? IrisPlatforms.get() : null;
IrisPlatforms.unbind();
emitted.clear();
levels.clear();
IrisPlatform platform = mock(IrisPlatform.class);
doAnswer(invocation -> {
levels.add(invocation.getArgument(0, LogLevel.class));
emitted.add(invocation.getArgument(1, String.class));
return null;
}).when(platform).log(ArgumentMatchers.any(LogLevel.class), ArgumentMatchers.anyString());
IrisPlatforms.bind(platform);
}
@After
public void restorePlatform() {
IrisPlatforms.unbind();
if (previousPlatform != null) {
IrisPlatforms.bind(previousPlatform);
}
}
@Test
public void aFailedProbeReportsItsNameClassAndMessageAtDebug() {
PregenDiagnostics.probeFailed("moonrise worker pool size", new IllegalStateException("no such field"));
assertEquals(1, emitted.size());
assertEquals(LogLevel.DEBUG, levels.get(0));
assertTrue(emitted.get(0), emitted.get(0).contains("moonrise worker pool size"));
assertTrue(emitted.get(0), emitted.get(0).contains(IllegalStateException.class.getName()));
assertTrue(emitted.get(0), emitted.get(0).contains("no such field"));
}
@Test
public void aThrowableWithNoMessageStillReportsItsClass() {
PregenDiagnostics.probeFailed("engine access", new NoClassDefFoundError());
assertEquals(1, emitted.size());
assertTrue(emitted.get(0), emitted.get(0).contains(NoClassDefFoundError.class.getName()));
assertTrue(emitted.get(0), emitted.get(0).contains("engine access"));
}
@Test
public void aMissingProbeNameAndThrowableStillProduceAReadableLine() {
PregenDiagnostics.probeFailed(null, null);
assertEquals(1, emitted.size());
assertTrue(emitted.get(0), emitted.get(0).contains("unnamed"));
assertTrue(emitted.get(0), emitted.get(0).contains("no throwable reported"));
}
@Test
public void percentSignsInAProbeNameAreNotTreatedAsFormatSpecifiers() {
PregenDiagnostics.probeFailed("heap at 95% headroom", new IllegalArgumentException("bad %s value"));
assertEquals(1, emitted.size());
assertTrue(emitted.get(0), emitted.get(0).contains("heap at 95% headroom"));
assertTrue(emitted.get(0), emitted.get(0).contains("bad %s value"));
}
}
@@ -0,0 +1,136 @@
package art.arcane.iris.core.pregenerator;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PregenSilentFailureContractTest {
@Test
public void noPregenSourceSwallowsAThrowableWithoutSayingAnything() throws IOException {
List<String> offenders = new ArrayList<>();
Path pregenRoot = sourceRoot().resolve("art/arcane/iris/core/pregenerator");
try (Stream<Path> sources = Files.walk(pregenRoot)) {
for (Path source : sources.filter(path -> path.toString().endsWith(".java")).toList()) {
String text = Files.readString(source);
if (text.contains("catch (Throwable ignored)") || text.contains("catch (Exception ignored)")) {
offenders.add(source.getFileName().toString());
}
}
}
assertEquals("silent catches on the pregen path: " + offenders, List.of(), offenders);
}
@Test
public void mantleCleanupFailureIsReportedWithItsStackTrace() throws IOException {
String cleanup = method(read("art/arcane/iris/core/pregenerator/methods/AsyncPregenMethod.java"),
"private void cleanupMantleChunk(");
assertTrue(cleanup, cleanup.contains("IrisLogging.reportError("));
assertTrue(cleanup, cleanup.contains("catch (Throwable e)"));
}
@Test
public void aStrandedPluginChunkTicketIsReportedWithItsStackTrace() throws IOException {
String unload = method(read("art/arcane/iris/core/pregenerator/methods/AsyncPregenMethod.java"),
"private void unloadChunkSafely(");
assertTrue(unload, unload.contains("removePluginChunkTicket"));
assertEquals(unload, 2, countOccurrences(unload, "IrisLogging.reportError("));
}
@Test
public void capabilityProbesLogThroughTheNamedDebugHelperRatherThanReportingErrors() throws IOException {
String async = read("art/arcane/iris/core/pregenerator/methods/AsyncPregenMethod.java");
assertTrue(method(async, "private int resolveWorkerPoolThreads()").contains("PregenDiagnostics.probeFailed("));
assertTrue(method(async, "private int evictionWindow()").contains("PregenDiagnostics.probeFailed("));
assertTrue(method(async, "private Engine resolveMetricsEngine()").contains("PregenDiagnostics.probeFailed("));
}
@Test
public void theFoliaSubmitFallbackNamesTheFailureItIsFallingBackFrom() throws IOException {
String executor = method(read("art/arcane/iris/core/pregenerator/methods/AsyncPregenMethod.java"),
"private class FoliaRegionExecutor");
assertTrue(executor, executor.contains("PregenDiagnostics.probeFailed("));
assertTrue(executor, executor.contains("falling back to a region task"));
}
@Test
public void backpressureProbesAnnounceWhyTheyFellBack() throws IOException {
String backpressure = read("art/arcane/iris/core/pregenerator/PregenMantleBackpressure.java");
assertTrue(method(backpressure, "private boolean isCancelled()").contains("PregenDiagnostics.probeFailed("));
assertTrue(method(backpressure, "private Mantle resolveMantle()").contains("PregenDiagnostics.probeFailed("));
}
@Test
public void medievalEngineResolutionAnnouncesWhyItFellBack() throws IOException {
String medieval = read("art/arcane/iris/core/pregenerator/methods/MedievalPregenMethod.java");
assertTrue(method(medieval, "private Engine resolveEngine()").contains("PregenDiagnostics.probeFailed("));
}
private static int countOccurrences(String text, String needle) {
int count = 0;
int index = text.indexOf(needle);
while (index >= 0) {
count++;
index = text.indexOf(needle, index + needle.length());
}
return count;
}
private static Path sourceRoot() throws IOException {
Path current;
try {
current = Path.of(PregenSilentFailureContractTest.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI());
} catch (URISyntaxException e) {
throw new IOException("Unable to resolve the core source root", e);
}
while (current != null && !Files.isDirectory(current.resolve("src/main/java"))) {
current = current.getParent();
}
if (current == null) {
throw new IOException("Unable to locate the core source root");
}
return current.resolve("src/main/java");
}
private static String read(String relativePath) throws IOException {
return Files.readString(sourceRoot().resolve(relativePath));
}
private static String method(String source, String signature) {
int start = source.indexOf(signature);
assertTrue("Missing source contract signature: " + signature, start >= 0);
int openBrace = source.indexOf('{', start);
assertTrue("Missing source contract method body: " + signature, openBrace >= 0);
int depth = 0;
for (int index = openBrace; index < source.length(); index++) {
char current = source.charAt(index);
if (current == '{') {
depth++;
} else if (current == '}') {
depth--;
if (depth == 0) {
return source.substring(start, index + 1);
}
}
}
throw new IllegalArgumentException("Unclosed source contract method: " + signature);
}
}
@@ -0,0 +1,46 @@
package art.arcane.iris.core.pregenerator;
import art.arcane.volmlib.util.math.Position2;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
public class PregenTaskChunkCountTest {
@Test
public void countMatchesTraversalAcrossChunkAndRegionBoundaries() {
int[][] areas = {
{0, 0, 1, 1},
{0, 0, 16, 32},
{17, -17, 15, 33},
{-16, -32, 16, 16},
{-513, 511, 32, 17},
{512, -512, 512, 256},
{PregenTask.MAX_WORLD_BLOCK - 32, 0, 32, 1},
{0, -PregenTask.MAX_WORLD_BLOCK + 32, 1, 32}
};
for (int[] area : areas) {
PregenTask task = PregenTask.builder()
.center(new Position2(area[0], area[1]))
.radiusX(area[2])
.radiusZ(area[3])
.build();
AtomicLong visited = new AtomicLong();
task.iterateAllChunks((x, z) -> visited.incrementAndGet());
assertEquals("center=" + area[0] + "," + area[1], visited.get(), task.chunkCount());
}
}
@Test(timeout = 2_000L)
public void entireWorldCountUsesLongArithmeticWithoutTraversal() {
PregenTask task = PregenTask.builder()
.radiusX(PregenTask.MAX_WORLD_BLOCK)
.radiusZ(PregenTask.MAX_WORLD_BLOCK)
.build();
assertEquals(14_062_492_500_001L, task.chunkCount());
}
}
@@ -0,0 +1,151 @@
package art.arcane.iris.core.pregenerator.methods;
import art.arcane.iris.core.pregenerator.PregenListener;
import art.arcane.iris.core.pregenerator.PregenMantleBackpressure;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AsyncPregenGenerationFailureTest {
private static final int OUTSTANDING_REQUESTS = 2;
@Test
public void aGenerationFailureFailsEveryOutstandingRequestAndReleasesTheirPermits() throws Exception {
Harness harness = Harness.withOutstanding(OUTSTANDING_REQUESTS);
IllegalStateException cause = new IllegalStateException("Accepted hydrology layer exceeds the mantle bounds");
harness.method.onChunkGenerationFailed(48, -4, cause);
assertEquals(OUTSTANDING_REQUESTS, harness.semaphore.availablePermits());
assertEquals(OUTSTANDING_REQUESTS, harness.failed.get());
assertEquals(0, harness.inFlight.get());
assertEquals(0, harness.requests.size());
verify(harness.listener).onChunkFailed(10, 0);
verify(harness.listener).onChunkFailed(11, 0);
IllegalStateException abort = assertThrows(IllegalStateException.class,
() -> harness.method.generateChunk(12, 0, harness.listener));
assertSame(cause, abort.getCause());
verify(harness.listener, never()).onChunkGenerating(12, 0);
}
@Test
public void aLateCompletionForASettledRequestIsIgnored() throws Exception {
Harness harness = Harness.withOutstanding(OUTSTANDING_REQUESTS);
harness.method.onChunkGenerationFailed(48, -4, new IllegalStateException("boom"));
harness.completeChunk(10, 0, null, null);
harness.completeChunk(11, 0, null, new IllegalStateException("late failure"));
assertEquals(OUTSTANDING_REQUESTS, harness.failed.get());
assertEquals(0, harness.completed.get());
assertEquals(0, harness.inFlight.get());
assertEquals(OUTSTANDING_REQUESTS, harness.semaphore.availablePermits());
}
@Test
public void closingAbandonsRequestsThatNeverCompleteAndReturnsTheirPermits() throws Exception {
Harness harness = Harness.withOutstanding(OUTSTANDING_REQUESTS);
harness.abandon(new AsyncPregenMethod.Drain(false, false, OUTSTANDING_REQUESTS));
assertEquals(OUTSTANDING_REQUESTS, harness.semaphore.availablePermits());
assertEquals(OUTSTANDING_REQUESTS, harness.failed.get());
assertEquals(0, harness.requests.size());
verify(harness.listener).onChunkFailed(10, 0);
verify(harness.listener).onChunkFailed(11, 0);
}
private static final class Harness {
private final AsyncPregenMethod method;
private final Semaphore semaphore;
private final PregenInFlightRequests requests;
private final PregenListener listener;
private final AtomicInteger inFlight;
private final AtomicLong failed;
private final AtomicLong completed;
private Harness(AsyncPregenMethod method, Semaphore semaphore, PregenInFlightRequests requests,
PregenListener listener, AtomicInteger inFlight, AtomicLong failed, AtomicLong completed) {
this.method = method;
this.semaphore = semaphore;
this.requests = requests;
this.listener = listener;
this.inFlight = inFlight;
this.failed = failed;
this.completed = completed;
}
static Harness withOutstanding(int outstanding) throws Exception {
AsyncPregenMethod method = mock(AsyncPregenMethod.class, CALLS_REAL_METHODS);
World world = mock(World.class);
when(world.getName()).thenReturn("qa");
Semaphore semaphore = new Semaphore(outstanding, true);
semaphore.acquire(outstanding);
PregenInFlightRequests requests = new PregenInFlightRequests();
PregenListener listener = mock(PregenListener.class);
AtomicInteger inFlight = new AtomicInteger(outstanding);
AtomicLong failed = new AtomicLong();
AtomicLong completed = new AtomicLong();
for (int index = 0; index < outstanding; index++) {
requests.add(PregenInFlightRequests.key(10 + index, 0), listener);
}
set(method, "world", world);
set(method, "semaphore", semaphore);
set(method, "backpressure", mock(PregenMantleBackpressure.class));
set(method, "inFlightRequests", requests);
set(method, "generationFailure", new AtomicReference<>());
set(method, "regionPending", new ConcurrentHashMap<>());
set(method, "lastFailedReleaseLogAt", new AtomicLong());
set(method, "slowRequestWarnIntervalMs", 15_000);
set(method, "inFlight", inFlight);
set(method, "submitted", new AtomicLong(outstanding));
set(method, "completed", completed);
set(method, "failed", failed);
set(method, "lastProgressAt", new AtomicLong());
set(method, "adaptiveInFlightLimit", new AtomicInteger(outstanding));
set(method, "permitMonitor", new Object());
set(method, "threads", outstanding);
set(method, "closing", new AtomicBoolean());
return new Harness(method, semaphore, requests, listener, inFlight, failed, completed);
}
void completeChunk(int x, int z, Chunk chunk, Throwable throwable) throws Exception {
Method complete = AsyncPregenMethod.class.getDeclaredMethod(
"completeChunk", int.class, int.class, PregenListener.class, Chunk.class, Throwable.class);
complete.setAccessible(true);
complete.invoke(method, x, z, listener, chunk, throwable);
}
void abandon(AsyncPregenMethod.Drain drain) throws Exception {
Method abandon = AsyncPregenMethod.class.getDeclaredMethod(
"abandonOutstandingRequests", AsyncPregenMethod.Drain.class);
abandon.setAccessible(true);
abandon.invoke(method, drain);
}
private static void set(AsyncPregenMethod method, String name, Object value) throws Exception {
Field field = AsyncPregenMethod.class.getDeclaredField(name);
field.setAccessible(true);
field.set(method, value);
}
}
}
@@ -90,10 +90,11 @@ public class AsyncPregenMethodConcurrencyCapTest {
AtomicInteger warnings = new AtomicInteger();
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<Boolean> drain = executor.submit(() -> AsyncPregenMethod.awaitDrain(
Future<AsyncPregenMethod.Drain> drain = executor.submit(() -> AsyncPregenMethod.awaitDrain(
semaphore,
2,
10L,
5L * 1000L,
TimeUnit.MILLISECONDS,
warnings::incrementAndGet
));
@@ -103,11 +104,34 @@ public class AsyncPregenMethodConcurrencyCapTest {
}
semaphore.release(2);
assertFalse(drain.get(1L, TimeUnit.SECONDS));
AsyncPregenMethod.Drain result = drain.get(1L, TimeUnit.SECONDS);
assertTrue(result.drained());
assertFalse(result.interrupted());
assertEquals(0, result.outstanding());
assertTrue(warnings.get() > 0);
assertEquals(0, semaphore.availablePermits());
} finally {
executor.shutdownNow();
}
}
@Test
public void closeDrainGivesUpAtItsDeadlineWhilePermitsStayHeld() {
Semaphore semaphore = new Semaphore(0);
AtomicInteger warnings = new AtomicInteger();
AsyncPregenMethod.Drain result = AsyncPregenMethod.awaitDrain(
semaphore,
2,
5L,
80L,
TimeUnit.MILLISECONDS,
warnings::incrementAndGet
);
assertFalse(result.drained());
assertFalse(result.interrupted());
assertEquals(2, result.outstanding());
assertTrue(warnings.get() > 0);
}
}
@@ -0,0 +1,66 @@
package art.arcane.iris.core.pregenerator.methods;
import art.arcane.iris.core.pregenerator.PregenListener;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
public class PregenInFlightRequestsTest {
@Test
public void settlingARequestReturnsItsListenerOnlyOnce() {
PregenInFlightRequests requests = new PregenInFlightRequests();
PregenListener listener = mock(PregenListener.class);
long key = PregenInFlightRequests.key(48, -4);
assertTrue(requests.add(key, listener));
assertEquals(1, requests.size());
assertSame(listener, requests.settle(key));
assertNull(requests.settle(key));
assertEquals(0, requests.size());
}
@Test
public void aDuplicateSubmissionKeepsTheOriginalRequest() {
PregenInFlightRequests requests = new PregenInFlightRequests();
PregenListener first = mock(PregenListener.class);
PregenListener second = mock(PregenListener.class);
long key = PregenInFlightRequests.key(1, 2);
assertTrue(requests.add(key, first));
assertFalse(requests.add(key, second));
assertSame(first, requests.settle(key));
}
@Test
public void drainingHandsBackEveryOutstandingRequestExactlyOnce() {
PregenInFlightRequests requests = new PregenInFlightRequests();
PregenListener listener = mock(PregenListener.class);
requests.add(PregenInFlightRequests.key(0, 0), listener);
requests.add(PregenInFlightRequests.key(1, 0), listener);
requests.add(PregenInFlightRequests.key(-7, 9), listener);
Map<Long, PregenListener> drained = requests.drain();
assertEquals(3, drained.size());
assertEquals(0, requests.size());
assertTrue(requests.drain().isEmpty());
assertNull(requests.settle(PregenInFlightRequests.key(1, 0)));
}
@Test
public void keysKeepNegativeCoordinatesApartAndRoundTrip() {
assertNotEquals(PregenInFlightRequests.key(1, -1), PregenInFlightRequests.key(-1, 1));
assertNotEquals(PregenInFlightRequests.key(0, -1), PregenInFlightRequests.key(-1, 0));
long key = PregenInFlightRequests.key(-48, -4);
assertEquals(-48, PregenInFlightRequests.chunkX(key));
assertEquals(-4, PregenInFlightRequests.chunkZ(key));
}
}
@@ -0,0 +1,50 @@
package art.arcane.iris.engine;
import art.arcane.iris.engine.framework.EnginePlatformHooks;
import art.arcane.iris.engine.framework.GenerationSessionException;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.spi.PlatformBiome;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.project.hunk.Hunk;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
public class IrisEngineMaintenanceRefusalTest {
@Test
@SuppressWarnings("unchecked")
public void maintenanceThatCannotRunMantleStagesRefusesTheChunkInsteadOfGeneratingIt() throws Exception {
IrisEngine engine = mock(IrisEngine.class);
EnginePlatformHooks hooks = mock(EnginePlatformHooks.class);
when(hooks.shouldRefuseGeneration(engine)).thenReturn(true);
Field platformHooks = IrisEngine.class.getDeclaredField("platformHooks");
platformHooks.setAccessible(true);
platformHooks.set(engine, hooks);
IrisWorld world = mock(IrisWorld.class);
when(world.name()).thenReturn("world");
when(engine.getWorld()).thenReturn(world);
doCallRealMethod().when(engine).generate(anyInt(), anyInt(), any(), any(), anyBoolean());
Hunk<PlatformBlockState> blocks = mock(Hunk.class);
Hunk<PlatformBiome> biomes = mock(Hunk.class);
GenerationSessionException refused = assertThrows(GenerationSessionException.class,
() -> engine.generate(32, 48, blocks, biomes, false));
assertTrue(refused.isExpectedTeardown());
verify(engine, never()).acquireGenerationLease(anyString());
verifyNoInteractions(blocks, biomes);
}
}
@@ -14,6 +14,7 @@ import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.RejectedExecutionException;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
@@ -22,6 +23,7 @@ import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.Mockito.mock;
@@ -85,6 +87,27 @@ public class DecoratorCoreTest {
assertNull(result);
}
@Test
public void pickDecorator_contentFailure_skipsThatDecorator() {
ResolvedDecorator broken = mock(ResolvedDecorator.class);
when(broken.passesChanceGate(anyDouble(), anyDouble())).thenThrow(new IllegalArgumentException("malformed decorator"));
ResolvedDecorator healthy = mock(ResolvedDecorator.class);
when(healthy.passesChanceGate(anyDouble(), anyDouble())).thenReturn(true);
ResolvedDecorator result = DecoratorCore.pickDecorator(new ResolvedDecorator[]{broken, healthy}, new RNG(2L), 0.0, 0.0, ModuleLogs.discarding());
assertSame(healthy, result);
}
@Test
public void pickDecorator_engineFailure_endsTheChunk() {
ResolvedDecorator closed = mock(ResolvedDecorator.class);
RejectedExecutionException failure = new RejectedExecutionException("pool shut down");
when(closed.passesChanceGate(anyDouble(), anyDouble())).thenThrow(failure);
assertSame(failure, assertThrows(RejectedExecutionException.class, () ->
DecoratorCore.pickDecorator(new ResolvedDecorator[]{closed}, new RNG(2L), 0.0, 0.0, ModuleLogs.discarding())));
}
@Test
public void pickDecorator_singleCandidate_alwaysReturnsThat() {
ResolvedDecorator d = mock(ResolvedDecorator.class);
@@ -0,0 +1,184 @@
package art.arcane.iris.engine.mantle;
import art.arcane.iris.engine.object.value.IrisPosition;
import org.junit.Test;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class MantleWriterNeighborhoodTest {
@Test
public void balloonedVoxelsMatchTheReferenceSphereForFractionalRadii() {
for (double radius : new double[]{0.0D, 0.5D, 1.0D, 1.5D, 2.0D, 3.7D, 5.0D}) {
Set<IrisPosition> seeds = line(-3, 60, 7, 4, 63, 9);
assertEquals("radius " + radius, referenceBallooned(seeds, radius), MantleWriter.getBallooned(seeds, radius));
}
}
@Test
public void hollowedVoxelsMatchTheReferenceSurfaceExtraction() {
Set<IrisPosition> ballooned = MantleWriter.getBallooned(line(0, 40, 0, 6, 44, 3), 4.0D);
assertEquals(referenceHollowed(ballooned), MantleWriter.getHollowed(ballooned));
}
@Test
public void hollowingASolidBlockKeepsOnlyItsShell() {
Set<IrisPosition> solid = new LinkedHashSet<>();
for (int x = 0; x < 5; x++) {
for (int y = 0; y < 5; y++) {
for (int z = 0; z < 5; z++) {
solid.add(new IrisPosition(x, y, z));
}
}
}
Set<IrisPosition> hollow = MantleWriter.getHollowed(solid);
assertEquals(98, hollow.size());
assertFalse(hollow.contains(new IrisPosition(2, 2, 2)));
assertTrue(hollow.contains(new IrisPosition(0, 2, 2)));
}
@Test
public void aSetTooWideToPackFallsBackToPositionEqualityWithoutChangingTheResult() {
Set<IrisPosition> spread = new LinkedHashSet<>();
spread.add(new IrisPosition(-20_000_000, 60, 0));
spread.add(new IrisPosition(20_000_000, 60, 0));
spread.add(new IrisPosition(20_000_001, 60, 0));
assertEquals(referenceHollowed(spread), MantleWriter.getHollowed(spread));
assertEquals(spread, MantleWriter.getHollowed(spread));
}
@Test
public void maskedVoxelsMatchTheReferenceMaskExpansion() {
Set<IrisPosition> seeds = line(0, 70, 0, 3, 70, 4);
Set<IrisPosition> masks = new LinkedHashSet<>();
masks.add(new IrisPosition(0, 0, 0));
masks.add(new IrisPosition(1, 0, 0));
masks.add(new IrisPosition(0, 1, 0));
masks.add(new IrisPosition(-1, 0, 1));
masks.add(new IrisPosition(0, 0, -2));
assertEquals(referenceMasked(seeds, masks, 3.0D), MantleWriter.getMasked(seeds, masks, 3.0D));
}
@Test
public void anEmptyMaskProducesNoVoxels() {
assertTrue(MantleWriter.getMasked(line(0, 70, 0, 2, 70, 2), new LinkedHashSet<>(), 2.0D).isEmpty());
}
@Test
public void aPositionLookupReportsMembershipOutsideItsBoundingBoxAsAbsent() {
Set<IrisPosition> positions = new LinkedHashSet<>();
positions.add(new IrisPosition(10, 20, 30));
MantleWriter.PositionLookup lookup = MantleWriter.PositionLookup.of(positions);
assertTrue(lookup.contains(10, 20, 30));
assertFalse(lookup.contains(9, 20, 30));
assertFalse(lookup.contains(10, 20, 31));
assertFalse(lookup.contains(Integer.MIN_VALUE, 20, 30));
assertFalse(lookup.contains(Integer.MAX_VALUE, 20, 30));
}
@Test
public void anEmptyPositionLookupContainsNothing() {
MantleWriter.PositionLookup lookup = MantleWriter.PositionLookup.of(new LinkedHashSet<>());
assertFalse(lookup.contains(0, 0, 0));
assertFalse(lookup.contains(-1, -1, -1));
}
private static Set<IrisPosition> line(int x1, int y1, int z1, int x2, int y2, int z2) {
Set<IrisPosition> positions = new LinkedHashSet<>();
int steps = Math.max(Math.max(Math.abs(x2 - x1), Math.abs(y2 - y1)), Math.abs(z2 - z1));
for (int step = 0; step <= steps; step++) {
double t = steps == 0 ? 0D : (double) step / steps;
positions.add(new IrisPosition(
(int) Math.round(x1 + t * (x2 - x1)),
(int) Math.round(y1 + t * (y2 - y1)),
(int) Math.round(z1 + t * (z2 - z1))));
}
return positions;
}
static Set<IrisPosition> referenceBallooned(Set<IrisPosition> vset, double radius) {
Set<IrisPosition> returnset = new HashSet<>();
int ceilrad = (int) Math.ceil(radius);
double r2 = Math.pow(radius, 2);
for (IrisPosition v : vset) {
int tipx = v.getX();
int tipy = v.getY();
int tipz = v.getZ();
for (int loopx = tipx - ceilrad; loopx <= tipx + ceilrad; loopx++) {
for (int loopy = tipy - ceilrad; loopy <= tipy + ceilrad; loopy++) {
for (int loopz = tipz - ceilrad; loopz <= tipz + ceilrad; loopz++) {
if (referenceHypot(loopx - tipx, loopy - tipy, loopz - tipz) <= r2) {
returnset.add(new IrisPosition(loopx, loopy, loopz));
}
}
}
}
}
return returnset;
}
static Set<IrisPosition> referenceHollowed(Set<IrisPosition> vset) {
Set<IrisPosition> returnset = new LinkedHashSet<>();
for (IrisPosition v : vset) {
double x = v.getX();
double y = v.getY();
double z = v.getZ();
if (!(vset.contains(new IrisPosition(x + 1, y, z))
&& vset.contains(new IrisPosition(x - 1, y, z))
&& vset.contains(new IrisPosition(x, y + 1, z))
&& vset.contains(new IrisPosition(x, y - 1, z))
&& vset.contains(new IrisPosition(x, y, z + 1))
&& vset.contains(new IrisPosition(x, y, z - 1)))) {
returnset.add(v);
}
}
return returnset;
}
static Set<IrisPosition> referenceMasked(Set<IrisPosition> vectors, Set<IrisPosition> masks, double radius) {
Set<IrisPosition> vset = new LinkedHashSet<>();
int ceil = (int) Math.ceil(radius);
double r2 = Math.pow(radius, 2);
for (IrisPosition v : vectors) {
int tipX = v.getX();
int tipY = v.getY();
int tipZ = v.getZ();
for (int x = -ceil; x <= ceil; x++) {
for (int y = -ceil; y <= ceil; y++) {
for (int z = -ceil; z <= ceil; z++) {
if (referenceHypot(x, y, z) > r2 || !masks.contains(new IrisPosition(x, y, z))) {
continue;
}
vset.add(new IrisPosition(tipX + x, tipY + y, tipZ + z));
}
}
}
}
return vset;
}
private static double referenceHypot(double... pars) {
double sum = 0;
for (double d : pars) {
sum += Math.pow(d, 2);
}
return sum;
}
}
@@ -38,6 +38,7 @@ import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -58,6 +59,39 @@ public class FloatingObjectPlacingBoundaryRadiusTest {
assertEquals(33, FloatingObjectPlacing.reach(pack(new FloatingChildSettings(List.of(floatingChild)), resources), ModuleLogs.discarding()));
}
@Test
public void packWithoutFloatingChildrenHasNoReach() {
assertEquals(0, FloatingObjectPlacing.reach(pack(new FloatingChildSettings(List.of()), mock(PackResources.class)), ModuleLogs.discarding()));
}
@Test
public void floatingChildWithoutObjectsHasNoReach() {
FloatingChildBiome floatingChild = TestSettings.with(new FloatingChildBiome(), "inheritObjects", false);
assertEquals(0, FloatingObjectPlacing.reach(pack(new FloatingChildSettings(List.of(floatingChild)), mock(PackResources.class)), ModuleLogs.discarding()));
}
@Test
public void placementOfMissingObjectKeepsTheMinimumReach() {
ObjectPlacement placement = TestSettings.of(ObjectPlacement.class, "{\"place\":[\"test/missing\"]}");
FloatingChildBiome floatingChild = TestSettings.with(new FloatingChildBiome(), "extraObjects", List.of(placement));
PackResources resources = mock(PackResources.class);
PackObjects objects = mock(PackObjects.class);
when(resources.objects()).thenReturn(objects);
when(objects.sizeOf(any())).thenReturn(Optional.empty());
assertEquals(16, FloatingObjectPlacing.reach(pack(new FloatingChildSettings(List.of(floatingChild)), resources), ModuleLogs.discarding()));
}
@Test
public void failedReachScanKeepsTheMinimumReach() {
PackSettings failing = mock(PackSettings.class);
when(failing.resources()).thenReturn(mock(PackResources.class));
when(failing.declared(any())).thenThrow(new IllegalStateException("Unavailable settings"));
assertEquals(16, FloatingObjectPlacing.reach(failing, ModuleLogs.discarding()));
}
private static PackSettings pack(FloatingChildSettings declared, PackResources resources) {
return new PackSettings() {
@Override
@@ -0,0 +1,28 @@
package art.arcane.iris.platform.bukkit;
import org.bukkit.plugin.Plugin;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
public class BukkitPlatformHostReleaseTest {
@After
public void clearHost() {
BukkitPlatform.releaseHost();
}
@Test
public void releasingTheHostDropsThePluginTheHudAndTheBridges() {
BukkitPlatform.hostPlugin(mock(Plugin.class));
BukkitPlatform.hostConsoleSender(() -> null);
BukkitPlatform.releaseHost();
assertFalse(BukkitPlatform.hasPlugin());
assertFalse(BukkitPlatform.hasHud());
assertThrows(IllegalStateException.class, BukkitPlatform::console);
}
}
@@ -0,0 +1,72 @@
package art.arcane.iris.util.common.scheduling;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.volmlib.util.scheduling.FoliaScheduler;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.scheduler.BukkitScheduler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockedStatic;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class JPluginEnabledCheckTest {
private final Plugin plugin = mock(Plugin.class);
private final PluginManager manager = mock(PluginManager.class);
private final BukkitScheduler scheduler = mock(BukkitScheduler.class);
@Before
public void bindBukkitHost() {
IrisPlatform platform = mock(IrisPlatform.class);
when(platform.platformName()).thenReturn("bukkit");
IrisPlatforms.bind(platform);
BukkitPlatform.hostPlugin(plugin);
}
@After
public void unbindBukkitHost() {
BukkitPlatform.hostPlugin(null);
IrisPlatforms.unbind();
}
@Test
public void enabledCheckReadsThePluginWithoutTheManagerMonitor() {
when(plugin.isEnabled()).thenReturn(true);
scheduleAsync();
verify(scheduler).runTaskAsynchronously(eq(plugin), any(Runnable.class));
verify(manager, never()).isPluginEnabled(any(Plugin.class));
}
@Test
public void disabledPluginRejectsSchedulingWithoutTheManagerMonitor() {
when(plugin.isEnabled()).thenReturn(false);
scheduleAsync();
verify(scheduler, never()).runTaskAsynchronously(any(Plugin.class), any(Runnable.class));
verify(manager, never()).isPluginEnabled(any(Plugin.class));
}
private void scheduleAsync() {
try (MockedStatic<Bukkit> bukkit = mockStatic(Bukkit.class);
MockedStatic<FoliaScheduler> folia = mockStatic(FoliaScheduler.class)) {
bukkit.when(Bukkit::getPluginManager).thenReturn(manager);
bukkit.when(Bukkit::getScheduler).thenReturn(scheduler);
J.aBukkit(() -> {
});
}
}
}
@@ -0,0 +1,66 @@
package art.arcane.iris.util.project.hunk.storage;
import art.arcane.iris.util.project.hunk.Hunk;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class VolmLibStorageHunkTest {
private static final int WIDTH = 3;
private static final int HEIGHT = 4;
private static final int DEPTH = 5;
@Test
public void everyStorageHunkReadsBackWhatWasWritten() {
assertRoundTrip(new ArrayHunk<Integer>(WIDTH, HEIGHT, DEPTH));
assertRoundTrip(new AtomicHunk<Integer>(WIDTH, HEIGHT, DEPTH));
assertRoundTrip(new SynchronizedArrayHunk<Integer>(WIDTH, HEIGHT, DEPTH));
assertRoundTrip(new AtomicIntegerHunk(WIDTH, HEIGHT, DEPTH));
}
@Test
public void atomicHunksReportAtomic() {
assertTrue(new AtomicHunk<Integer>(WIDTH, HEIGHT, DEPTH).isAtomic());
assertTrue(new AtomicDoubleHunk(WIDTH, HEIGHT, DEPTH).isAtomic());
assertTrue(new AtomicIntegerHunk(WIDTH, HEIGHT, DEPTH).isAtomic());
assertTrue(new AtomicLongHunk(WIDTH, HEIGHT, DEPTH).isAtomic());
}
@Test
public void filledHunkHoldsTheValueEverywhere() {
ArrayHunk<Integer> hunk = new ArrayHunk<>(WIDTH, HEIGHT, DEPTH);
hunk.fill(7);
assertEquals(Integer.valueOf(7), hunk.getRaw(0, 0, 0));
assertEquals(Integer.valueOf(7), hunk.getRaw(WIDTH - 1, HEIGHT - 1, DEPTH - 1));
}
@Test
public void emptyHunkIsRejected() {
assertThrows(RuntimeException.class, () -> new ArrayHunk<Integer>(0, HEIGHT, DEPTH));
}
private static void assertRoundTrip(Hunk<Integer> hunk) {
assertEquals(WIDTH, hunk.getWidth());
assertEquals(HEIGHT, hunk.getHeight());
assertEquals(DEPTH, hunk.getDepth());
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
for (int z = 0; z < DEPTH; z++) {
hunk.setRaw(x, y, z, x * 100 + y * 10 + z);
}
}
}
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
for (int z = 0; z < DEPTH; z++) {
assertEquals(Integer.valueOf(x * 100 + y * 10 + z), hunk.getRaw(x, y, z));
}
}
}
}
}
@@ -0,0 +1,28 @@
package art.arcane.iris.util.project.interpolation;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class IrisInterpolationRangeScaleTest {
private static final double TOLERANCE = 1e-12;
@Test
public void degenerateSourceRangeKeepsIrisArithmetic() {
assertTrue(Double.isNaN(IrisInterpolation.rangeScale(0, 1, 5, 5, 5)));
assertTrue(Double.isInfinite(IrisInterpolation.rangeScale(0, 1, 5, 5, 6)));
}
@Test
public void rangeScaleMapsAcrossTheRange() {
assertEquals(0.25, IrisInterpolation.rangeScale(0, 1, 0, 8, 2), TOLERANCE);
}
@Test
public void inheritedInterpolationStillBlends() {
assertEquals(2.5, IrisInterpolation.lerp(2, 3, 0.5), TOLERANCE);
assertEquals(1.5, IrisInterpolation.blerp(1, 2, 1, 2, 0.5, 0.5), TOLERANCE);
assertEquals(2.5, IrisInterpolation.hermite(1, 2, 3, 4, 0.5, 0, 0), TOLERANCE);
}
}