Archive incari-client (client, 26.3, clean)
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
package com.mojang.blaze3d.audio;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.audio.CompressedSoundStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import javax.sound.sampled.AudioFormat;
|
||||
import net.minecraft.client.sounds.AudioStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ChannelTest {
|
||||
|
||||
private static final AudioFormat STEREO16 = new AudioFormat(44100, 16, 2, true, false);
|
||||
|
||||
/** A stream of {@code chunks} full reads, then the empty buffer that marks its end. */
|
||||
private static final class Stream implements AudioStream {
|
||||
int chunksLeft;
|
||||
int lastRequest;
|
||||
boolean closed;
|
||||
|
||||
Stream(int chunks) {
|
||||
this.chunksLeft = chunks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AudioFormat getFormat() {
|
||||
return STEREO16;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ByteBuffer read(int expectedSize) {
|
||||
lastRequest = expectedSize;
|
||||
if (chunksLeft == 0) {
|
||||
return ByteBuffer.allocateDirect(0);
|
||||
}
|
||||
chunksLeft--;
|
||||
return ByteBuffer.allocateDirect(expectedSize);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamsOneSecondChunks() {
|
||||
assertThat(Channel.bytesPerSeconds(STEREO16, 1)).isEqualTo(44100 * 2 * 2);
|
||||
assertThat(Channel.bytesPerSeconds(new AudioFormat(22050, 8, 1, false, false), 2))
|
||||
.isEqualTo(44100);
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsTheStreamQueueToppedUp() {
|
||||
FakeAudio.Device device = new FakeAudio.Device("d", 30);
|
||||
Channel channel = Channel.create(device);
|
||||
assertThat(channel).isNotNull();
|
||||
FakeAudio.Source source = device.sources.getFirst();
|
||||
Stream stream = new Stream(10);
|
||||
|
||||
channel.attachBufferStream(stream);
|
||||
assertThat(source.queue).hasSize(4);
|
||||
assertThat(stream.lastRequest).isEqualTo(44100 * 4);
|
||||
|
||||
source.processed = 3;
|
||||
channel.updateStream();
|
||||
assertThat(source.queue).hasSize(4);
|
||||
assertThat(stream.chunksLeft).isEqualTo(3);
|
||||
|
||||
// Past the end nothing more is queued, and the queue drains.
|
||||
source.processed = 4;
|
||||
channel.updateStream();
|
||||
assertThat(source.queue).hasSize(3);
|
||||
assertThat(stream.chunksLeft).isZero();
|
||||
source.processed = 3;
|
||||
channel.updateStream();
|
||||
assertThat(source.queue).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void handsCompressedStreamsToADeviceThatStreamsThem() throws Exception {
|
||||
FakeAudio.Device device = new FakeAudio.Device("d", 30);
|
||||
device.streams = true;
|
||||
Channel channel = Channel.create(device);
|
||||
assertThat(channel).isNotNull();
|
||||
FakeAudio.Source source = device.sources.getFirst();
|
||||
byte[] file = {1, 2, 3};
|
||||
|
||||
channel.attachBufferStream(new CompressedSoundStream(file, true));
|
||||
assertThat(source.streamed).isSameAs(file);
|
||||
assertThat(source.streamLooping).isTrue();
|
||||
assertThat(source.queue).isEmpty();
|
||||
|
||||
// Nothing to top up: the device decodes as it plays.
|
||||
source.processed = 2;
|
||||
channel.updateStream();
|
||||
assertThat(source.queue).isEmpty();
|
||||
channel.destroy();
|
||||
assertThat(source.closed).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void destroyClosesTheStreamAndTheSourceOnce() {
|
||||
FakeAudio.Device device = new FakeAudio.Device("d", 30);
|
||||
Channel channel = Channel.create(device);
|
||||
assertThat(channel).isNotNull();
|
||||
Stream stream = new Stream(10);
|
||||
channel.attachBufferStream(stream);
|
||||
channel.play();
|
||||
assertThat(channel.playing()).isTrue();
|
||||
|
||||
channel.destroy();
|
||||
channel.destroy();
|
||||
FakeAudio.Source source = device.sources.getFirst();
|
||||
assertThat(stream.closed).isTrue();
|
||||
assertThat(source.closed).isTrue();
|
||||
assertThat(device.buffers).allMatch(buffer -> buffer.closed);
|
||||
assertThat(channel.stopped()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFreshChannelIsNotStopped() {
|
||||
FakeAudio.Device device = new FakeAudio.Device("d", 30);
|
||||
Channel channel = Channel.create(device);
|
||||
assertThat(channel).isNotNull();
|
||||
assertThat(channel.stopped()).isFalse();
|
||||
channel.pause(); // Only a playing channel pauses.
|
||||
assertThat(device.sources.getFirst().state).isEqualTo(FakeAudio.Source.State.INITIAL);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noChannelWhenTheDeviceIsOutOfSources() {
|
||||
FakeAudio.Device device = new FakeAudio.Device("d", 1);
|
||||
assertThat(Channel.create(device)).isNotNull();
|
||||
assertThat(Channel.create(device)).isNull();
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.mojang.blaze3d.audio;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.platform.api.audio.AudioDeviceList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DeviceTrackingTest {
|
||||
|
||||
@Test
|
||||
void copiesThePlatformsList() {
|
||||
DeviceList list = DeviceList.from(new AudioDeviceList("B", List.of("A", "B")));
|
||||
assertThat(list).isEqualTo(new DeviceList("B", List.of("A", "B")));
|
||||
assertThat(DeviceList.from(AudioDeviceList.EMPTY)).isEqualTo(DeviceList.EMPTY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlatformNoticeRequestsAnUpdate() {
|
||||
FakeAudio audio = new FakeAudio();
|
||||
CallbackDeviceTracker tracker = CallbackDeviceTracker.createAndInstall(audio, DeviceList.EMPTY);
|
||||
assertThat(tracker.isUpdateRequested()).isFalse();
|
||||
|
||||
Runnable listener = audio.deviceChangeListener;
|
||||
assertThat(listener).isNotNull();
|
||||
listener.run();
|
||||
assertThat(tracker.isUpdateRequested()).isTrue();
|
||||
|
||||
tracker.discardUpdateRequest();
|
||||
assertThat(tracker.isUpdateRequested()).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package com.mojang.blaze3d.audio;
|
||||
|
||||
import incari.platform.api.audio.AudioBuffer;
|
||||
import incari.platform.api.audio.AudioDevice;
|
||||
import incari.platform.api.audio.AudioDeviceList;
|
||||
import incari.platform.api.audio.AudioException;
|
||||
import incari.platform.api.audio.AudioListener;
|
||||
import incari.platform.api.audio.AudioSource;
|
||||
import incari.platform.api.audio.DecodedAudio;
|
||||
import incari.platform.api.audio.PcmFormat;
|
||||
import incari.platform.api.audio.PlatformAudio;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/** A sound system in memory: records what the game asks of it, plays nothing. */
|
||||
final class FakeAudio implements PlatformAudio {
|
||||
|
||||
AudioDeviceList devices = AudioDeviceList.EMPTY;
|
||||
Set<String> unopenable = Set.of();
|
||||
int maxSources = 30;
|
||||
final List<@Nullable String> openAttempts = new ArrayList<>();
|
||||
final List<Device> opened = new ArrayList<>();
|
||||
|
||||
@Nullable
|
||||
Runnable deviceChangeListener;
|
||||
|
||||
@Override
|
||||
public AudioDeviceList devices() {
|
||||
return devices;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean reportsDeviceChanges() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDeviceChangeListener(@Nullable Runnable listener) {
|
||||
deviceChangeListener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AudioDevice open(@Nullable String deviceName, boolean spatialize) {
|
||||
openAttempts.add(deviceName);
|
||||
String name = deviceName == null ? "Fake default" : deviceName;
|
||||
if (unopenable.contains(name)) {
|
||||
throw new AudioException("unplugged: " + name);
|
||||
}
|
||||
Device device = new Device(name, maxSources);
|
||||
opened.add(device);
|
||||
return device;
|
||||
}
|
||||
|
||||
static final class Device implements AudioDevice {
|
||||
final String name;
|
||||
final int maxSources;
|
||||
final List<Source> sources = new ArrayList<>();
|
||||
final List<Buffer> buffers = new ArrayList<>();
|
||||
final Listener listener = new Listener();
|
||||
boolean closed;
|
||||
boolean failUploads;
|
||||
boolean streams;
|
||||
|
||||
Device(String name, int maxSources) {
|
||||
this.name = name;
|
||||
this.maxSources = maxSources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDisconnected() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int maxSources() {
|
||||
return maxSources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AudioListener listener() {
|
||||
return listener;
|
||||
}
|
||||
|
||||
long openSources() {
|
||||
return sources.stream().filter(s -> !s.closed).count();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable AudioSource createSource() {
|
||||
if (openSources() >= maxSources) {
|
||||
return null;
|
||||
}
|
||||
Source source = new Source();
|
||||
sources.add(source);
|
||||
return source;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AudioBuffer createBuffer(ByteBuffer samples, PcmFormat format) {
|
||||
if (failUploads) {
|
||||
throw new AudioException("upload failed");
|
||||
}
|
||||
Buffer buffer = new Buffer(format, samples.remaining());
|
||||
buffers.add(buffer);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AudioBuffer createBuffer(DecodedAudio audio) {
|
||||
if (failUploads) {
|
||||
throw new AudioException("upload failed");
|
||||
}
|
||||
Buffer buffer = new Buffer(new PcmFormat(audio.sampleRate(), audio.channels(), 16), audio.sizeInBytes());
|
||||
buffers.add(buffer);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean streamsOggVorbis() {
|
||||
return streams;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
static final class Listener implements AudioListener {
|
||||
double[] position = new double[3];
|
||||
double[] orientation = new double[6];
|
||||
|
||||
@Override
|
||||
public void setPosition(double x, double y, double z) {
|
||||
position = new double[] {x, y, z};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOrientation(
|
||||
double forwardX, double forwardY, double forwardZ, double upX, double upY, double upZ) {
|
||||
orientation = new double[] {forwardX, forwardY, forwardZ, upX, upY, upZ};
|
||||
}
|
||||
}
|
||||
|
||||
static final class Source implements AudioSource {
|
||||
State state = State.INITIAL;
|
||||
|
||||
@Nullable
|
||||
AudioBuffer buffer;
|
||||
|
||||
final ArrayDeque<AudioBuffer> queue = new ArrayDeque<>();
|
||||
int processed;
|
||||
boolean closed;
|
||||
float gain = 1;
|
||||
|
||||
@Nullable
|
||||
Float maxDistance;
|
||||
|
||||
@Override
|
||||
public void play() {
|
||||
state = State.PLAYING;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pause() {
|
||||
state = State.PAUSED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
state = State.STOPPED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public State state() {
|
||||
return state;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPosition(double x, double y, double z) {}
|
||||
|
||||
@Override
|
||||
public void setPitch(float pitch) {}
|
||||
|
||||
@Override
|
||||
public void setLooping(boolean looping) {}
|
||||
|
||||
@Override
|
||||
public void setGain(float gain) {
|
||||
this.gain = gain;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRelative(boolean relative) {}
|
||||
|
||||
@Override
|
||||
public void disableAttenuation() {
|
||||
maxDistance = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLinearAttenuation(float maxDistance) {
|
||||
this.maxDistance = maxDistance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBuffer(AudioBuffer buffer) {
|
||||
this.buffer = buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void queue(AudioBuffer buffer) {
|
||||
queue.addLast(buffer);
|
||||
}
|
||||
|
||||
byte @Nullable [] streamed;
|
||||
boolean streamLooping;
|
||||
|
||||
@Override
|
||||
public void streamOggVorbis(byte[] file, boolean looping) {
|
||||
streamed = file;
|
||||
streamLooping = looping;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int releaseProcessedBuffers() {
|
||||
int released = Math.min(processed, queue.size());
|
||||
for (int i = 0; i < released; i++) {
|
||||
queue.removeFirst().close();
|
||||
}
|
||||
processed = 0;
|
||||
return released;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closed = true;
|
||||
queue.forEach(AudioBuffer::close);
|
||||
queue.clear();
|
||||
}
|
||||
}
|
||||
|
||||
static final class Buffer implements AudioBuffer {
|
||||
final PcmFormat format;
|
||||
final int size;
|
||||
boolean closed;
|
||||
|
||||
Buffer(PcmFormat format, int size) {
|
||||
this.format = format;
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PcmFormat format() {
|
||||
return format;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int sizeInBytes() {
|
||||
return size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.mojang.blaze3d.audio;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class LibraryTest {
|
||||
|
||||
@Test
|
||||
void splitsSourcesBetweenThePools() {
|
||||
// OpenAL Soft's usual 255 mono sources.
|
||||
assertThat(Library.streamingPoolSize(255)).isEqualTo(8);
|
||||
assertThat(Library.staticPoolSize(255, 8)).isEqualTo(247);
|
||||
// The fallback count when a device doesn't say.
|
||||
assertThat(Library.streamingPoolSize(30)).isEqualTo(5);
|
||||
assertThat(Library.staticPoolSize(30, 5)).isEqualTo(25);
|
||||
// Floors and ceilings.
|
||||
assertThat(Library.streamingPoolSize(1)).isEqualTo(2);
|
||||
assertThat(Library.staticPoolSize(1, 2)).isEqualTo(8);
|
||||
assertThat(Library.streamingPoolSize(10_000)).isEqualTo(8);
|
||||
assertThat(Library.staticPoolSize(10_000, 8)).isEqualTo(255);
|
||||
}
|
||||
|
||||
@Test
|
||||
void opensThePreferredDeviceFirst() {
|
||||
FakeAudio audio = new FakeAudio();
|
||||
assertThat(Library.openWithFallback(audio, "Headset", "Speakers", false).name())
|
||||
.isEqualTo("Headset");
|
||||
assertThat(audio.openAttempts).containsExactly("Headset");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackToTheSystemDefaultThenThePlatformDefault() {
|
||||
FakeAudio audio = new FakeAudio();
|
||||
audio.unopenable = Set.of("Headset", "Speakers");
|
||||
assertThat(Library.openWithFallback(audio, "Headset", "Speakers", false).name())
|
||||
.isEqualTo("Fake default");
|
||||
assertThat(audio.openAttempts).containsExactly("Headset", "Speakers", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesntTryTheSameDeviceTwice() {
|
||||
FakeAudio audio = new FakeAudio();
|
||||
audio.unopenable = Set.of("Speakers");
|
||||
Library.openWithFallback(audio, "Speakers", "Speakers", false);
|
||||
assertThat(audio.openAttempts).containsExactly("Speakers", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenNothingOpens() {
|
||||
FakeAudio audio = new FakeAudio();
|
||||
audio.unopenable = Set.of("Speakers", "Fake default");
|
||||
assertThatThrownBy(() -> Library.openWithFallback(audio, null, "Speakers", false))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void handsOutChannelsUpToEachPoolsLimit() {
|
||||
FakeAudio audio = new FakeAudio();
|
||||
audio.maxSources = 30;
|
||||
Library library = new Library();
|
||||
library.init(audio, null, DeviceList.EMPTY, false);
|
||||
assertThat(library.currentDeviceName()).isEqualTo("Fake default");
|
||||
|
||||
List<Channel> streaming = new ArrayList<>();
|
||||
Channel channel;
|
||||
while ((channel = library.acquireChannel(Library.Pool.STREAMING)) != null) {
|
||||
streaming.add(channel);
|
||||
}
|
||||
assertThat(streaming).hasSize(5);
|
||||
assertThat(library.getChannelDebugString()).isEqualTo("Sounds: 0/25 + 5/5");
|
||||
|
||||
// The static pool is untouched by a full streaming pool.
|
||||
Channel single = library.acquireChannel(Library.Pool.STATIC);
|
||||
assertThat(single).isNotNull();
|
||||
assertThat(library.getChannelDebugString()).isEqualTo("Sounds: 1/25 + 5/5");
|
||||
|
||||
library.releaseChannel(streaming.getFirst());
|
||||
assertThat(library.getChannelDebugString()).isEqualTo("Sounds: 1/25 + 4/5");
|
||||
assertThat(audio.opened.getFirst().openSources()).isEqualTo(5);
|
||||
assertThatThrownBy(() -> library.releaseChannel(streaming.getFirst()))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanupFreesEverythingAndClosesTheDevice() {
|
||||
FakeAudio audio = new FakeAudio();
|
||||
Library library = new Library();
|
||||
library.init(audio, null, DeviceList.EMPTY, false);
|
||||
library.acquireChannel(Library.Pool.STATIC);
|
||||
library.acquireChannel(Library.Pool.STREAMING);
|
||||
|
||||
library.cleanup();
|
||||
|
||||
FakeAudio.Device device = audio.opened.getFirst();
|
||||
assertThat(device.closed).isTrue();
|
||||
assertThat(device.openSources()).isZero();
|
||||
assertThat(library.acquireChannel(Library.Pool.STATIC)).isNull();
|
||||
assertThat(library.isCurrentDeviceDisconnected()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanupWithNothingOpenIsHarmless() {
|
||||
new Library().cleanup();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theListenerFollowsTheDeviceOpenedAfterIt() {
|
||||
FakeAudio audio = new FakeAudio();
|
||||
Library library = new Library();
|
||||
// The game moves the listener before any device is open.
|
||||
library.getListener()
|
||||
.setTransform(new ListenerTransform(new Vec3(1, 2, 3), new Vec3(1, 0, 0), new Vec3(0, 1, 0)));
|
||||
library.init(audio, null, DeviceList.EMPTY, false);
|
||||
|
||||
FakeAudio.Listener target = audio.opened.getFirst().listener;
|
||||
assertThat(target.position).containsExactly(1, 2, 3);
|
||||
assertThat(target.orientation).containsExactly(1, 0, 0, 0, 1, 0);
|
||||
|
||||
library.getListener().reset();
|
||||
assertThat(target.position).containsExactly(0, 0, 0);
|
||||
assertThat(target.orientation).containsExactly(0, 0, -1, 0, 1, 0);
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package com.mojang.blaze3d.audio;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.platform.api.audio.DecodedAudio;
|
||||
import incari.platform.api.audio.PcmFormat;
|
||||
import java.nio.ByteBuffer;
|
||||
import javax.sound.sampled.AudioFormat;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SoundBufferTest {
|
||||
|
||||
private static final AudioFormat MONO16 = new AudioFormat(44100, 16, 1, true, false);
|
||||
|
||||
@Test
|
||||
void mapsPcmFormats() {
|
||||
assertThat(SoundBuffer.toPcmFormat(MONO16)).isEqualTo(new PcmFormat(44100, 1, 16));
|
||||
assertThat(SoundBuffer.toPcmFormat(new AudioFormat(22050, 8, 2, false, false)))
|
||||
.isEqualTo(new PcmFormat(22050, 2, 8));
|
||||
assertThat(SoundBuffer.toPcmFormat(new AudioFormat(48000, 16, 2, true, false)))
|
||||
.isEqualTo(new PcmFormat(48000, 2, 16));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsWhatThePlatformCantPlay() {
|
||||
AudioFormat ulaw = new AudioFormat(AudioFormat.Encoding.ULAW, 8000, 8, 1, 1, 8000, false);
|
||||
assertThatThrownBy(() -> SoundBuffer.toPcmFormat(ulaw)).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> SoundBuffer.toPcmFormat(new AudioFormat(44100, 24, 1, true, false)))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> SoundBuffer.toPcmFormat(new AudioFormat(44100, 16, 6, true, false)))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadsOnceAndDropsTheSamples() {
|
||||
FakeAudio.Device device = new FakeAudio.Device("d", 30);
|
||||
SoundBuffer buffer = new SoundBuffer(ByteBuffer.allocateDirect(1000), MONO16);
|
||||
assertThat(buffer.size()).isEqualTo(1000);
|
||||
assertThat(buffer.isValid()).isTrue();
|
||||
|
||||
var first = buffer.bufferOn(device);
|
||||
assertThat(first).isNotNull();
|
||||
assertThat(first.sizeInBytes()).isEqualTo(1000);
|
||||
assertThat(buffer.bufferOn(device)).isSameAs(first);
|
||||
assertThat(device.buffers).hasSize(1);
|
||||
|
||||
buffer.discardAlBuffer();
|
||||
assertThat(((FakeAudio.Buffer) first).closed).isTrue();
|
||||
assertThat(buffer.isValid()).isFalse();
|
||||
assertThat(buffer.bufferOn(device)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadsWhatThePlatformDecoded() {
|
||||
FakeAudio.Device device = new FakeAudio.Device("d", 30);
|
||||
SoundBuffer buffer = new SoundBuffer(new DecodedAudio() {
|
||||
@Override
|
||||
public int sampleRate() {
|
||||
return 48000;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int channels() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int frames() {
|
||||
return 100;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int sizeInBytes() {
|
||||
return 800;
|
||||
}
|
||||
});
|
||||
assertThat(buffer.size()).isEqualTo(800);
|
||||
assertThat(buffer.format().getEncoding()).isEqualTo(AudioFormat.Encoding.PCM_FLOAT);
|
||||
assertThat(buffer.format().getChannels()).isEqualTo(2);
|
||||
assertThat(buffer.format().getFrameSize()).isEqualTo(8);
|
||||
assertThat(buffer.isValid()).isTrue();
|
||||
|
||||
var uploaded = buffer.bufferOn(device);
|
||||
assertThat(uploaded).isNotNull();
|
||||
assertThat(uploaded.format()).isEqualTo(new PcmFormat(48000, 2, 16));
|
||||
assertThat(buffer.bufferOn(device)).isSameAs(uploaded);
|
||||
buffer.discardAlBuffer();
|
||||
assertThat(buffer.isValid()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedUploadKeepsTheSamplesForARetry() {
|
||||
FakeAudio.Device device = new FakeAudio.Device("d", 30);
|
||||
device.failUploads = true;
|
||||
SoundBuffer buffer = new SoundBuffer(ByteBuffer.allocateDirect(8), MONO16);
|
||||
assertThat(buffer.bufferOn(device)).isNull();
|
||||
assertThat(buffer.isValid()).isTrue();
|
||||
|
||||
device.failUploads = false;
|
||||
assertThat(buffer.bufferOn(device)).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void wontHandOutAnotherDevicesBuffer() {
|
||||
SoundBuffer buffer = new SoundBuffer(ByteBuffer.allocateDirect(8), MONO16);
|
||||
buffer.bufferOn(new FakeAudio.Device("a", 30));
|
||||
assertThat(buffer.bufferOn(new FakeAudio.Device("b", 30))).isNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package incari.client;
|
||||
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.tngtech.archunit.base.DescribedPredicate;
|
||||
import com.tngtech.archunit.core.domain.JavaClass;
|
||||
import com.tngtech.archunit.core.domain.JavaClasses;
|
||||
import com.tngtech.archunit.core.importer.ClassFileImporter;
|
||||
import com.tngtech.archunit.core.importer.ImportOption;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Incari's game-side code runs in every build, so it's platform-neutral: it reaches the machine
|
||||
* only through platform-api, never through LWJGL, TeaVM or a platform implementation. That covers
|
||||
* the incari.client packages and every vendor class Incari replaces (patches/classes.txt), which
|
||||
* is the point of replacing them. Vendor code keeps its own LWJGL calls until a patch routes them.
|
||||
*/
|
||||
class BoundaryTest {
|
||||
|
||||
private static JavaClasses classes;
|
||||
private static Set<String> replacedClasses;
|
||||
|
||||
@BeforeAll
|
||||
static void importClasses() throws IOException {
|
||||
Path manifest = Path.of(System.getProperty("incari.repoRoot", "../..")).resolve("patches/classes.txt");
|
||||
replacedClasses = Files.readAllLines(manifest).stream()
|
||||
.map(line -> line.replaceAll("#.*", "").strip())
|
||||
.filter(line -> line.startsWith("replace "))
|
||||
.map(line -> line.split("\\s+", -1)[1])
|
||||
.collect(Collectors.toSet());
|
||||
classes = new ClassFileImporter()
|
||||
.withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
|
||||
.importPackages("incari.client", "com.mojang", "net.minecraft");
|
||||
}
|
||||
|
||||
@Test
|
||||
void incariCodeIsPlatformNeutral() {
|
||||
DescribedPredicate<JavaClass> incariCode = DescribedPredicate.describe(
|
||||
"Incari code (incari.client and the classes patches/classes.txt replaces)",
|
||||
javaClass -> javaClass.getPackageName().startsWith("incari.client")
|
||||
|| replacedClasses.contains(outermost(javaClass).getName()));
|
||||
|
||||
noClasses()
|
||||
.that(incariCode)
|
||||
.should()
|
||||
.dependOnClassesThat()
|
||||
.resideInAnyPackage("org.lwjgl..", "org.teavm..", "incari.platform.desktop..", "incari.platform.web..")
|
||||
.check(classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyReplacementWasImported() {
|
||||
// Guards the rule above: a replacement it can't see isn't checked.
|
||||
Set<String> imported = classes.stream().map(JavaClass::getName).collect(Collectors.toSet());
|
||||
assertThat(imported).containsAll(replacedClasses);
|
||||
}
|
||||
|
||||
private static JavaClass outermost(JavaClass javaClass) {
|
||||
JavaClass current = javaClass;
|
||||
while (current.getEnclosingClass().isPresent()) {
|
||||
current = current.getEnclosingClass().get();
|
||||
}
|
||||
return current;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package incari.client;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import net.minecraft.client.KeyMapping;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** {@link IncariKeys}' binds survive a restart: {@code options.txt} reads each line back to its key. */
|
||||
class IncariKeysTest {
|
||||
|
||||
@Test
|
||||
void namesHaveNoColon() {
|
||||
// options.txt is "key_<name>:<key>", split at the first colon.
|
||||
for (KeyMapping key : IncariKeys.all()) {
|
||||
assertThat(key.getName()).doesNotContain(":");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package incari.client;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Random;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** {@link TickPacing} runs every tick the game would, spread over frames, and keeps up when slow. */
|
||||
class TickPacingTest {
|
||||
|
||||
@BeforeEach
|
||||
void enable() {
|
||||
TickPacing.setEnabled(true);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void disable() {
|
||||
TickPacing.setEnabled(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void offRunsWhatIsDue() {
|
||||
TickPacing.setEnabled(false);
|
||||
assertThat(TickPacing.ticksToRun(7, true)).isEqualTo(7);
|
||||
}
|
||||
|
||||
@Test
|
||||
void spreadsABurstAtSixtyFps() {
|
||||
warmUp(60);
|
||||
// A 300 ms frame: six ticks due at once.
|
||||
int first = TickPacing.ticksToRun(6, true);
|
||||
assertThat(first).isLessThanOrEqualTo(2);
|
||||
int total = first;
|
||||
int frames = 1;
|
||||
while (TickPacing.debt() > 0) {
|
||||
int run = TickPacing.ticksToRun(0, true);
|
||||
assertThat(run).isBetween(1, 2);
|
||||
total += run;
|
||||
frames++;
|
||||
}
|
||||
assertThat(total).isEqualTo(6);
|
||||
assertThat(frames).isLessThanOrEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void runsEveryTickTheGameWouldWhileBurstsComeApart() {
|
||||
Random random = new Random(20261003);
|
||||
int due = 0;
|
||||
int run = 0;
|
||||
for (int frame = 0; frame < 100_000; frame++) {
|
||||
// Mostly 60 fps, with a slow frame now and then, never two within ten frames.
|
||||
int ticks = frame % 50 == 0 ? random.nextInt(11) : (random.nextInt(3) == 0 ? 1 : 0);
|
||||
due += ticks;
|
||||
run += TickPacing.ticksToRun(ticks, true);
|
||||
}
|
||||
assertThat(run + TickPacing.debt()).isEqualTo(due);
|
||||
}
|
||||
|
||||
@Test
|
||||
void neverRunsMoreThanTheGameAfterALongStall() {
|
||||
warmUp(60);
|
||||
// A two-second stall: the game runs ten ticks and drops the rest.
|
||||
int total = TickPacing.ticksToRun(40, true);
|
||||
while (TickPacing.debt() > 0) {
|
||||
total += TickPacing.ticksToRun(0, true);
|
||||
}
|
||||
assertThat(total).isEqualTo(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsUpWhenTheFrameRateIsLow() {
|
||||
// About 8 fps: two or three ticks due every frame.
|
||||
int maxDebt = 0;
|
||||
for (int frame = 0; frame < 1000; frame++) {
|
||||
TickPacing.ticksToRun(frame % 2 == 0 ? 2 : 3, true);
|
||||
maxDebt = Math.max(maxDebt, TickPacing.debt());
|
||||
}
|
||||
assertThat(maxDebt).isLessThanOrEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitsWhileTimeStands() {
|
||||
warmUp(60);
|
||||
TickPacing.ticksToRun(4, true);
|
||||
int owed = TickPacing.debt();
|
||||
assertThat(TickPacing.ticksToRun(0, false)).isZero();
|
||||
assertThat(TickPacing.debt()).isEqualTo(owed);
|
||||
}
|
||||
|
||||
private static void warmUp(int fps) {
|
||||
int ticksPerFrameTimes3 = 60 / fps;
|
||||
for (int frame = 0; frame < 300; frame++) {
|
||||
TickPacing.ticksToRun(frame % 3 < ticksPerFrameTimes3 ? 1 : 0, true);
|
||||
}
|
||||
while (TickPacing.debt() > 0) {
|
||||
TickPacing.ticksToRun(0, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package incari.client.audio;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.mojang.blaze3d.audio.SoundBuffer;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DecodedSoundBudgetTest {
|
||||
|
||||
private static final Identifier A = Identifier.withDefaultNamespace("sounds/a.ogg");
|
||||
private static final Identifier B = Identifier.withDefaultNamespace("sounds/b.ogg");
|
||||
private static final Identifier C = Identifier.withDefaultNamespace("sounds/c.ogg");
|
||||
|
||||
private static Map<Identifier, CompletableFuture<SoundBuffer>> cacheOf(Identifier... locations) {
|
||||
Map<Identifier, CompletableFuture<SoundBuffer>> cache = new HashMap<>();
|
||||
for (Identifier location : locations) {
|
||||
cache.put(location, new CompletableFuture<>());
|
||||
}
|
||||
return cache;
|
||||
}
|
||||
|
||||
@Test
|
||||
void dropsTheSoundsAskedForLongestAgoPastTheBudget() {
|
||||
DecodedSoundBudget budget = new DecodedSoundBudget();
|
||||
Map<Identifier, CompletableFuture<SoundBuffer>> cache = cacheOf(A, B, C);
|
||||
budget.decoded(A, 100);
|
||||
budget.decoded(B, 100);
|
||||
budget.decoded(C, 100);
|
||||
// A was asked for again, so B is now the oldest.
|
||||
budget.used(A);
|
||||
|
||||
budget.trim(cache, C, 250);
|
||||
|
||||
assertThat(cache).containsOnlyKeys(A, C);
|
||||
assertThat(budget.total()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void neverDropsTheSoundBeingAskedFor() {
|
||||
DecodedSoundBudget budget = new DecodedSoundBudget();
|
||||
Map<Identifier, CompletableFuture<SoundBuffer>> cache = cacheOf(A, B);
|
||||
budget.decoded(A, 1000);
|
||||
budget.decoded(B, 10);
|
||||
|
||||
budget.trim(cache, A, 100);
|
||||
|
||||
assertThat(cache).containsOnlyKeys(A);
|
||||
assertThat(budget.total()).isEqualTo(1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void countsASoundDecodedAgainOnce() {
|
||||
DecodedSoundBudget budget = new DecodedSoundBudget();
|
||||
budget.decoded(A, 100);
|
||||
// After a resource reload the game decodes it afresh.
|
||||
budget.decoded(A, 120);
|
||||
assertThat(budget.total()).isEqualTo(120);
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsEverythingWithinTheBudget() {
|
||||
DecodedSoundBudget budget = new DecodedSoundBudget();
|
||||
Map<Identifier, CompletableFuture<SoundBuffer>> cache = cacheOf(A, B);
|
||||
budget.decoded(A, 100);
|
||||
budget.decoded(B, 100);
|
||||
|
||||
budget.trim(cache, A, 200);
|
||||
|
||||
assertThat(cache).containsOnlyKeys(A, B);
|
||||
}
|
||||
}
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
package incari.client.audio;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.mojang.blaze3d.audio.SoundBuffer;
|
||||
import incari.platform.api.audio.AudioDecoder;
|
||||
import incari.platform.api.audio.AudioException;
|
||||
import incari.platform.api.audio.DecodedAudio;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.minecraft.client.sounds.AudioStream;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.packs.resources.Resource;
|
||||
import net.minecraft.server.packs.resources.ResourceProvider;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PlatformSoundLoadingTest {
|
||||
|
||||
private static final Identifier CLICK = Identifier.withDefaultNamespace("sounds/random/click.ogg");
|
||||
|
||||
/** A decoder that hands back the file's length as frames, and remembers what it was given. */
|
||||
private static final class FakeDecoder implements AudioDecoder {
|
||||
final List<byte[]> files = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public DecodedAudio decodeOggVorbis(byte[] file) {
|
||||
files.add(file);
|
||||
if (file.length > 0 && file[0] == 'X') {
|
||||
throw new AudioException("not Ogg");
|
||||
}
|
||||
return new DecodedAudio() {
|
||||
@Override
|
||||
public int sampleRate() {
|
||||
return 48000;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int channels() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int frames() {
|
||||
return file.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int sizeInBytes() {
|
||||
return file.length * Float.BYTES;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Resources from a map of paths to contents. */
|
||||
private static ResourceProvider files(Map<Identifier, byte[]> files) {
|
||||
return new ResourceProvider() {
|
||||
@Override
|
||||
public Optional<Resource> getResource(Identifier location) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream open(Identifier location) throws FileNotFoundException {
|
||||
byte[] file = files.get(location);
|
||||
if (file == null) {
|
||||
throw new FileNotFoundException(location.toString());
|
||||
}
|
||||
return new ByteArrayInputStream(file);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeRemoteSource() {
|
||||
RemoteSounds.install(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesDecodingToTheGameWithoutAPlatformDecoder() {
|
||||
assertThat(PlatformSoundLoading.completeBuffer(null, new HashMap<>(), files(Map.of()), CLICK))
|
||||
.isNull();
|
||||
assertThat(PlatformSoundLoading.stream(null, files(Map.of()), CLICK, false))
|
||||
.isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodesThroughThePlatformAndCachesTheResult() throws Exception {
|
||||
FakeDecoder decoder = new FakeDecoder();
|
||||
Map<Identifier, CompletableFuture<SoundBuffer>> cache = new HashMap<>();
|
||||
ResourceProvider resources = files(Map.of(CLICK, new byte[] {1, 2, 3}));
|
||||
|
||||
CompletableFuture<SoundBuffer> first = PlatformSoundLoading.completeBuffer(decoder, cache, resources, CLICK);
|
||||
SoundBuffer buffer = first.get(10, TimeUnit.SECONDS);
|
||||
assertThat(buffer.size()).isEqualTo(3 * Float.BYTES);
|
||||
assertThat(buffer.format().getChannels()).isEqualTo(1);
|
||||
assertThat(buffer.isValid()).isTrue();
|
||||
|
||||
assertThat(PlatformSoundLoading.completeBuffer(decoder, cache, resources, CLICK))
|
||||
.isSameAs(first);
|
||||
assertThat(cache).containsKey(CLICK);
|
||||
assertThat(decoder.files).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchesPlaceholdersByTheirAssetName() throws Exception {
|
||||
List<String> asked = new ArrayList<>();
|
||||
RemoteSounds.install(name -> {
|
||||
asked.add(name);
|
||||
return new byte[] {9, 9, 9, 9, 9};
|
||||
});
|
||||
FakeDecoder decoder = new FakeDecoder();
|
||||
ResourceProvider resources = files(Map.of(CLICK, new byte[0]));
|
||||
|
||||
SoundBuffer buffer = PlatformSoundLoading.completeBuffer(decoder, new HashMap<>(), resources, CLICK)
|
||||
.get(10, TimeUnit.SECONDS);
|
||||
assertThat(asked).containsExactly("minecraft/sounds/random/click.ogg");
|
||||
assertThat(buffer.size()).isEqualTo(5 * Float.BYTES);
|
||||
|
||||
// A file that's really there (a resource pack's) is never fetched.
|
||||
asked.clear();
|
||||
PlatformSoundLoading.completeBuffer(decoder, new HashMap<>(), files(Map.of(CLICK, new byte[] {1})), CLICK)
|
||||
.get(10, TimeUnit.SECONDS);
|
||||
assertThat(asked).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void playsSilenceWhenNeitherDecoderCanRead() throws Exception {
|
||||
FakeDecoder decoder = new FakeDecoder();
|
||||
// Not Ogg for the platform, and not for the game's decoder either.
|
||||
ResourceProvider resources =
|
||||
files(Map.of(CLICK, "XXXXXXXXXXXXXXXX".getBytes(java.nio.charset.StandardCharsets.US_ASCII)));
|
||||
SoundBuffer unreadable = PlatformSoundLoading.completeBuffer(decoder, new HashMap<>(), resources, CLICK)
|
||||
.get(10, TimeUnit.SECONDS);
|
||||
assertThat(unreadable).isInstanceOf(PlatformSoundLoading.Silence.class);
|
||||
assertThat(unreadable.isValid()).isTrue();
|
||||
|
||||
SoundBuffer missing = PlatformSoundLoading.completeBuffer(decoder, new HashMap<>(), files(Map.of()), CLICK)
|
||||
.get(10, TimeUnit.SECONDS);
|
||||
assertThat(missing).isInstanceOf(PlatformSoundLoading.Silence.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void triesAFailedDownloadAgainOnlyAfterAWhile() throws Exception {
|
||||
int[] tries = {0};
|
||||
RemoteSounds.install(name -> {
|
||||
if (++tries[0] == 1) {
|
||||
throw new java.io.IOException("Failed to fetch");
|
||||
}
|
||||
return new byte[] {7, 7};
|
||||
});
|
||||
FakeDecoder decoder = new FakeDecoder();
|
||||
Map<Identifier, CompletableFuture<SoundBuffer>> cache = new HashMap<>();
|
||||
ResourceProvider resources = files(Map.of(CLICK, new byte[0]));
|
||||
|
||||
CompletableFuture<SoundBuffer> failed = PlatformSoundLoading.completeBuffer(decoder, cache, resources, CLICK);
|
||||
assertThat(failed.get(10, TimeUnit.SECONDS)).isInstanceOf(PlatformSoundLoading.Silence.class);
|
||||
// Asked for again at once: still the silence, not another download.
|
||||
assertThat(PlatformSoundLoading.completeBuffer(decoder, cache, resources, CLICK))
|
||||
.isSameAs(failed);
|
||||
assertThat(tries[0]).isEqualTo(1);
|
||||
|
||||
// Long enough after the failure, it's fetched again.
|
||||
cache.put(CLICK, CompletableFuture.completedFuture(new PlatformSoundLoading.Silence(0)));
|
||||
SoundBuffer fetched = PlatformSoundLoading.completeBuffer(decoder, cache, resources, CLICK)
|
||||
.get(10, TimeUnit.SECONDS);
|
||||
assertThat(fetched).isNotInstanceOf(PlatformSoundLoading.Silence.class);
|
||||
assertThat(fetched.size()).isEqualTo(2 * Float.BYTES);
|
||||
assertThat(tries[0]).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamsHandTheWholeFileOver() throws Exception {
|
||||
byte[] file = {4, 5, 6};
|
||||
AudioStream stream = PlatformSoundLoading.stream(new FakeDecoder(), files(Map.of(CLICK, file)), CLICK, true)
|
||||
.get(10, TimeUnit.SECONDS);
|
||||
assertThat(stream).isInstanceOf(CompressedSoundStream.class);
|
||||
CompressedSoundStream compressed = (CompressedSoundStream) stream;
|
||||
assertThat(compressed.file()).containsExactly(4, 5, 6);
|
||||
assertThat(compressed.looping()).isTrue();
|
||||
compressed.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package incari.client.cosmetics;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
|
||||
import java.util.Set;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.Style;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BadgesTest {
|
||||
|
||||
private static final Set<String> INCARI = Set.of("Steve", "Alex");
|
||||
|
||||
@Test
|
||||
void chatWithNoIncariPlayerIsUnchanged() {
|
||||
Component message = Component.literal("<Notch> hello Steven");
|
||||
assertSame(message, Badges.badgedInChat(message, INCARI::contains));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badgeGoesBeforeEachIncariPlayersFirstMention() {
|
||||
Component message = Component.literal("<Steve> hi Alex, Steve here");
|
||||
assertEquals(
|
||||
"< Steve> hi Alex, Steve here",
|
||||
Badges.badgedInChat(message, INCARI::contains).getString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void piecesKeepTheirStyleAndLegacyColours() {
|
||||
Style green = Style.EMPTY.withColor(ChatFormatting.GREEN);
|
||||
Component message = Component.literal("§7[§aVIP§7] Steve: hi").setStyle(green);
|
||||
Component badged = Badges.badgedInChat(message, INCARI::contains);
|
||||
assertEquals("§7[§aVIP§7] §7§a§7Steve: hi", badged.getString());
|
||||
// The cut after the badge repeats the codes before it, so "Steve" stays grey (§7).
|
||||
StringBuilder pieces = new StringBuilder();
|
||||
badged.visit(
|
||||
(style, text) -> {
|
||||
if (text.contains("Steve")) {
|
||||
assertEquals(green.getColor(), style.getColor());
|
||||
pieces.append(text);
|
||||
}
|
||||
return java.util.Optional.empty();
|
||||
},
|
||||
Style.EMPTY);
|
||||
assertEquals("§7§a§7Steve: hi", pieces.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package incari.client.credits;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.net.URI;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CreditsTest {
|
||||
|
||||
@Test
|
||||
void creditsIncariAndViaInEveryBuild() {
|
||||
assertThat(Credits.all()).extracting(Credit::name).startsWith("Incari Client", "ViaVersion", "ViaBackwards");
|
||||
}
|
||||
|
||||
@Test
|
||||
void namesViaVersionsTheBuildBundles() {
|
||||
// The versions the build was compiled against, so the source links name the right release.
|
||||
assertThat(Credits.all())
|
||||
.filteredOn(credit -> credit.name().startsWith("Via"))
|
||||
.allSatisfy(credit -> assertThat(credit.version()).matches("\\d+\\.\\d+\\.\\d+.*"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsWhatABuildContainsAfterTheCommonEntries() {
|
||||
Credit added = new Credit(
|
||||
"Example",
|
||||
null,
|
||||
"Someone",
|
||||
"MIT",
|
||||
URI.create("https://example.com/license"),
|
||||
URI.create("https://example.com/source"));
|
||||
Credits.add(added);
|
||||
assertThat(Credits.all()).last().isEqualTo(added);
|
||||
}
|
||||
|
||||
@Test
|
||||
void linksAreHttps() {
|
||||
assertThat(Credits.all()).allSatisfy(credit -> {
|
||||
assertThat(credit.source().getScheme()).isEqualTo("https");
|
||||
assertThat(credit.licenseText().getScheme()).isEqualTo("https");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void titleNamesTheVersionWhenThereIsOne() {
|
||||
URI uri = URI.create("https://example.com");
|
||||
assertThat(new Credit("A", "1.0", "x", "MIT", uri, uri).title()).isEqualTo("A 1.0");
|
||||
assertThat(new Credit("A", null, "x", "MIT", uri, uri).title()).isEqualTo("A");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package incari.client.datafix;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.mojang.serialization.Dynamic;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import net.minecraft.util.datafix.fixes.References;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class LazyDataFixerTest {
|
||||
|
||||
@Test
|
||||
void passesCurrentDataThroughWithoutBuildingTheFixer() {
|
||||
Dynamic<?> input = new Dynamic<>(JsonOps.INSTANCE, new JsonPrimitive("options"));
|
||||
assertThat(LazyDataFixer.INSTANCE.update(References.OPTIONS, input, 4000, 4000))
|
||||
.isSameAs(input);
|
||||
assertThat(LazyDataFixer.INSTANCE.update(References.OPTIONS, input, 4100, 4000))
|
||||
.isSameAs(input);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package incari.client.gui;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import net.minecraft.util.FormattedCharSequence;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class HiddenPasswordsTest {
|
||||
|
||||
@Test
|
||||
void loginCommandsHideTheirArguments() {
|
||||
assertThat(HiddenPasswords.hiddenFrom("/login hunter2")).isEqualTo(7);
|
||||
assertThat(HiddenPasswords.hiddenFrom("/L hunter2")).isEqualTo(3);
|
||||
assertThat(HiddenPasswords.hiddenFrom("/register a a")).isEqualTo(10);
|
||||
assertThat(HiddenPasswords.hiddenFrom("/authme:login hunter2")).isEqualTo(14);
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherLinesHideNothing() {
|
||||
assertThat(HiddenPasswords.hiddenFrom("login hunter2")).isEqualTo(-1);
|
||||
assertThat(HiddenPasswords.hiddenFrom("/login")).isEqualTo(-1);
|
||||
assertThat(HiddenPasswords.hiddenFrom("/logout now")).isEqualTo(-1);
|
||||
assertThat(HiddenPasswords.hiddenFrom("/tp 0 64 0")).isEqualTo(-1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyLinesWithAPasswordStayOutOfTheHistory() {
|
||||
assertThat(HiddenPasswords.hasPassword("/login hunter2")).isTrue();
|
||||
assertThat(HiddenPasswords.hasPassword("/changepassword old new")).isTrue();
|
||||
assertThat(HiddenPasswords.hasPassword("/login")).isFalse();
|
||||
assertThat(HiddenPasswords.hasPassword("/home")).isFalse();
|
||||
assertThat(HiddenPasswords.hasPassword("hello")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void starsReplaceTheHiddenPartButNotSpaces() {
|
||||
// The box draws its value in pieces; the second starts at offset 4.
|
||||
assertThat(drawn(HiddenPasswords.starred("in pässwörd 𝄞", 4, 7))).isEqualTo("in ******** *");
|
||||
assertThat(drawn(HiddenPasswords.starred("/log", 0, 7))).isEqualTo("/log");
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordLabelsAreFoundInAnyCase() {
|
||||
assertThat(HiddenPasswords.isPasswordLabel("Password")).isTrue();
|
||||
assertThat(HiddenPasswords.isPasswordLabel("Confirm your PASSWORD")).isTrue();
|
||||
assertThat(HiddenPasswords.isPasswordLabel("Passwort")).isTrue();
|
||||
assertThat(HiddenPasswords.isPasswordLabel("Username")).isFalse();
|
||||
}
|
||||
|
||||
private static String drawn(FormattedCharSequence sequence) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
sequence.accept((position, style, codePoint) -> {
|
||||
text.appendCodePoint(codePoint);
|
||||
return true;
|
||||
});
|
||||
return text.toString();
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package incari.client.memory;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.testing.TestPlatform;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.world.level.EmptyBlockGetter;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.SupportType;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Every block state's cache, built with what states share and sturdy faces worked out once
|
||||
* per support shape, answers as the game's own computation does.
|
||||
*/
|
||||
class BlockStateSharingTest {
|
||||
|
||||
@BeforeAll
|
||||
static void bootstrap() {
|
||||
TestPlatform.install();
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sturdyFacesAreTheGamesAnswers() {
|
||||
int states = 0;
|
||||
for (Block block : BuiltInRegistries.BLOCK) {
|
||||
for (BlockState state : block.getStateDefinition().getPossibleStates()) {
|
||||
states++;
|
||||
for (Direction direction : Direction.values()) {
|
||||
for (SupportType type : SupportType.values()) {
|
||||
assertThat(state.isFaceSturdy(EmptyBlockGetter.INSTANCE, BlockPos.ZERO, direction, type))
|
||||
.as("%s, %s face, %s", state, direction, type)
|
||||
.isEqualTo(
|
||||
type.isSupporting(state, EmptyBlockGetter.INSTANCE, BlockPos.ZERO, direction));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assertThat(states).isGreaterThan(20000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullBlocksAreTheGamesAnswers() {
|
||||
for (Block block : BuiltInRegistries.BLOCK) {
|
||||
for (BlockState state : block.getStateDefinition().getPossibleStates()) {
|
||||
assertThat(state.isSolidRender())
|
||||
.as("%s", state)
|
||||
.isEqualTo(Block.isShapeFullBlock(state.getOcclusionShape()));
|
||||
assertThat(state.isCollisionShapeFullBlock(EmptyBlockGetter.INSTANCE, BlockPos.ZERO))
|
||||
.as("%s", state)
|
||||
.isEqualTo(Block.isShapeFullBlock(
|
||||
state.getCollisionShape(EmptyBlockGetter.INSTANCE, BlockPos.ZERO)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void occlusionFacesAreTheShapesFaces() {
|
||||
for (Block block : BuiltInRegistries.BLOCK) {
|
||||
for (BlockState state : block.getStateDefinition().getPossibleStates()) {
|
||||
if (state.isSolidRender() || state.getOcclusionShape().isEmpty()) {
|
||||
continue; // The game's shared constant arrays, untouched.
|
||||
}
|
||||
for (Direction direction : Direction.values()) {
|
||||
assertThat(state.getFaceOcclusionShape(direction))
|
||||
.as("%s, %s face", state, direction)
|
||||
.isSameAs(state.getOcclusionShape().getFaceShape(direction));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package incari.client.memory;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
import com.mojang.blaze3d.font.UnbakedGlyph;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import incari.client.testing.TestPlatform;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.RecordComponent;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Random;
|
||||
import net.minecraft.client.gui.font.CodepointMap;
|
||||
import net.minecraft.client.gui.font.providers.UnihexProvider;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** {@link PackedUnihex} gives back every glyph's lines and edges exactly as the game's objects hold them. */
|
||||
class PackedUnihexTest {
|
||||
|
||||
/** Where {@code ./incari assets} keeps the game's Unicode font (asset index of 26.3). */
|
||||
private static final Path UNIFONT = Path.of(
|
||||
System.getProperty("incari.repoRoot", "."),
|
||||
"work/cache/assets/objects/cc/ccd5ac4767ce0a9c71d1dd62f2dc25449789b5dd");
|
||||
|
||||
@BeforeAll
|
||||
static void platform() {
|
||||
TestPlatform.install();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void off() {
|
||||
PackedUnihex.setEnabled(false);
|
||||
}
|
||||
|
||||
/** A glyph as the game's record holds one: its lines and edges. */
|
||||
private record TestGlyph(UnihexProvider.LineData contents, int left, int right) implements UnbakedGlyph {
|
||||
@Override
|
||||
public com.mojang.blaze3d.font.GlyphInfo info() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public net.minecraft.client.gui.font.glyphs.BakedGlyph bake(UnbakedGlyph.Stitcher stitcher) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
/** Lines of a given width, the bits at the top of each int as the game keeps them. */
|
||||
private static final class TestLines implements UnihexProvider.LineData {
|
||||
private final int[] lines;
|
||||
private final int bitWidth;
|
||||
|
||||
TestLines(int[] lines, int bitWidth) {
|
||||
this.lines = lines;
|
||||
this.bitWidth = bitWidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int line(int index) {
|
||||
return lines[index];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int bitWidth() {
|
||||
return bitWidth;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyWidthReadsBackBitForBit() {
|
||||
Random random = new Random(26_3);
|
||||
CodepointMap<TestGlyph> glyphs = new CodepointMap<>(TestGlyph[]::new, TestGlyph[][]::new);
|
||||
int[] widths = {8, 16, 24, 32};
|
||||
for (int i = 0; i < 20_000; i++) {
|
||||
int codepoint = random.nextInt(0x110000);
|
||||
int width = widths[random.nextInt(widths.length)];
|
||||
int[] lines = new int[16];
|
||||
for (int line = 0; line < 16; line++) {
|
||||
lines[line] = width == 32 ? random.nextInt() : (random.nextInt() >>> (32 - width)) << (32 - width);
|
||||
}
|
||||
glyphs.put(
|
||||
codepoint,
|
||||
new TestGlyph(new TestLines(lines, width), random.nextInt(32) - 8, random.nextInt(40) - 8));
|
||||
}
|
||||
glyphs.put(0x10FFFF, new TestGlyph(new TestLines(new int[16], 16), 0, 15));
|
||||
|
||||
PackedUnihex packed = PackedUnihex.pack(glyphs, TestGlyph::contents, TestGlyph::left, TestGlyph::right);
|
||||
|
||||
assertThat(packed.codepoints()).isEqualTo(glyphs.keySet());
|
||||
glyphs.forEach((codepoint, expected) -> {
|
||||
TestGlyph actual = packed.get(codepoint, TestGlyph::new);
|
||||
assertThat(actual).isNotNull();
|
||||
assertSame(
|
||||
codepoint,
|
||||
expected.contents(),
|
||||
expected.left(),
|
||||
expected.right(),
|
||||
actual.contents(),
|
||||
actual.left(),
|
||||
actual.right());
|
||||
});
|
||||
assertThat(packed.get(0x110000, TestGlyph::new)).isNull();
|
||||
assertThat(packed.get(-1, TestGlyph::new)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theGamesUnicodeFontPacksExactly() throws Exception {
|
||||
Assumptions.assumeTrue(Files.exists(UNIFONT), "The Unicode font isn't in work/cache/assets (./incari assets)");
|
||||
PackedUnihex.setEnabled(false);
|
||||
UnihexProvider game = load();
|
||||
PackedUnihex.setEnabled(true);
|
||||
UnihexProvider packed = load();
|
||||
|
||||
assertThat(packed.getSupportedGlyphs()).isEqualTo(game.getSupportedGlyphs());
|
||||
assertThat(game.getSupportedGlyphs()).hasSizeGreaterThan(50_000);
|
||||
for (int codepoint : game.getSupportedGlyphs()) {
|
||||
UnbakedGlyph expected = game.getGlyph(codepoint);
|
||||
UnbakedGlyph actual = packed.getGlyph(codepoint);
|
||||
assertThat(actual).isNotNull();
|
||||
assertSame(
|
||||
codepoint,
|
||||
contents(expected),
|
||||
edge(expected, "left"),
|
||||
edge(expected, "right"),
|
||||
contents(actual),
|
||||
edge(actual, "left"),
|
||||
edge(actual, "right"));
|
||||
assertThat(actual.info().getAdvance()).isEqualTo(expected.info().getAdvance());
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertSame(
|
||||
int codepoint,
|
||||
UnihexProvider.LineData expected,
|
||||
int expectedLeft,
|
||||
int expectedRight,
|
||||
UnihexProvider.LineData actual,
|
||||
int left,
|
||||
int right) {
|
||||
assertThat(actual.bitWidth()).as("width of %x", codepoint).isEqualTo(expected.bitWidth());
|
||||
for (int line = 0; line < 16; line++) {
|
||||
assertThat(actual.line(line)).as("line %d of %x", line, codepoint).isEqualTo(expected.line(line));
|
||||
}
|
||||
assertThat(actual.calculateWidth()).isEqualTo(expected.calculateWidth());
|
||||
assertThat(left).as("left of %x", codepoint).isEqualTo(expectedLeft);
|
||||
assertThat(right).as("right of %x", codepoint).isEqualTo(expectedRight);
|
||||
}
|
||||
|
||||
/** The game's unihex provider for its Unicode font, read from the asset cache. */
|
||||
private static UnihexProvider load() throws Exception {
|
||||
UnihexProvider.Definition definition = UnihexProvider.Definition.CODEC
|
||||
.codec()
|
||||
.parse(JsonOps.INSTANCE, JsonParser.parseString("{\"hex_file\": \"minecraft:font/unifont.zip\"}"))
|
||||
.getOrThrow();
|
||||
Method loadData = UnihexProvider.Definition.class.getDeclaredMethod("loadData", InputStream.class);
|
||||
loadData.setAccessible(true);
|
||||
try (InputStream in = Files.newInputStream(UNIFONT)) {
|
||||
return (UnihexProvider) loadData.invoke(definition, in);
|
||||
} catch (java.lang.reflect.InvocationTargetException e) {
|
||||
if (e.getCause() instanceof IOException io) {
|
||||
throw io;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** The game's glyph record's lines, read through its accessor. */
|
||||
private static UnihexProvider.LineData contents(UnbakedGlyph glyph) throws ReflectiveOperationException {
|
||||
return (UnihexProvider.LineData) component(glyph, "contents");
|
||||
}
|
||||
|
||||
private static int edge(UnbakedGlyph glyph, String name) throws ReflectiveOperationException {
|
||||
return (Integer) component(glyph, name);
|
||||
}
|
||||
|
||||
private static Object component(UnbakedGlyph glyph, String name) throws ReflectiveOperationException {
|
||||
for (RecordComponent component : glyph.getClass().getRecordComponents()) {
|
||||
if (component.getName().equals(name)) {
|
||||
Method accessor = component.getAccessor();
|
||||
accessor.setAccessible(true);
|
||||
return accessor.invoke(glyph);
|
||||
}
|
||||
}
|
||||
throw new NoSuchFieldException(name + " in " + glyph.getClass());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package incari.client.modules;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class MapMemoryTest {
|
||||
|
||||
@TempDir
|
||||
Path gameDirectory;
|
||||
|
||||
@AfterEach
|
||||
void reset() {
|
||||
MapMemory.close();
|
||||
MapMemory.setRemember(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rememberingAgainKeepsWhatTheFileHad() {
|
||||
MapMemory.open(gameDirectory, "world/Test");
|
||||
MapMemory.record("overworld", 0, 0, colors(0xFF112233));
|
||||
MapMemory.close();
|
||||
|
||||
// A visit without remembering makes the region afresh, without its file.
|
||||
MapMemory.setRemember(false);
|
||||
MapMemory.open(gameDirectory, "world/Test");
|
||||
MapMemory.record("overworld", 1, 0, colors(0xFF445566));
|
||||
MapMemory.setRemember(true);
|
||||
MapMemory.close();
|
||||
|
||||
MapMemory.open(gameDirectory, "world/Test");
|
||||
MapMemory.Region region = MapMemory.region("overworld", 0, 0, false);
|
||||
assertThat(region).isNotNull();
|
||||
assertThat(region.chunk(0, 0)).isNotNull().contains(0xFF112233);
|
||||
assertThat(region.chunk(1, 0)).isNotNull().contains(0xFF445566);
|
||||
}
|
||||
|
||||
private static int[] colors(int argb) {
|
||||
int[] colors = new int[256];
|
||||
Arrays.fill(colors, argb);
|
||||
return colors;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package incari.client.net;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.testing.TestPlatform;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.client.multiplayer.ServerData;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FeaturedServersTest {
|
||||
|
||||
@BeforeAll
|
||||
static void gameVersion() {
|
||||
// A ServerData asks for the game's version, set once per run: not left to whichever test ran first.
|
||||
TestPlatform.install();
|
||||
SharedConstants.tryDetectVersion();
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsTheBuiltInList() {
|
||||
assertThat(FeaturedServers.parse("Carrotcraft|wss://eagler.carrot-craft.org"))
|
||||
.containsExactly(new FeaturedServers.Entry("Carrotcraft", "wss://eagler.carrot-craft.org"));
|
||||
assertThat(FeaturedServers.parse(" A | a.example ;B|b.example;"))
|
||||
.containsExactly(
|
||||
new FeaturedServers.Entry("A", "a.example"), new FeaturedServers.Entry("B", "b.example"));
|
||||
}
|
||||
|
||||
private static final List<FeaturedServers.Entry> CARROT =
|
||||
List.of(new FeaturedServers.Entry("Carrotcraft", "wss://eagler.carrot-craft.org"));
|
||||
|
||||
@Test
|
||||
void anotherListLoadingKeepsTheShownListsEntryFeatured() {
|
||||
// The multiplayer screen's list, then the one a join loads to save the server it joined.
|
||||
List<ServerData> shown = new ArrayList<>();
|
||||
FeaturedServers.addTo(shown, CARROT);
|
||||
List<ServerData> joined = new ArrayList<>();
|
||||
FeaturedServers.addTo(joined, CARROT);
|
||||
|
||||
assertThat(FeaturedServers.is(shown.getFirst())).isTrue();
|
||||
assertThat(FeaturedServers.is(joined.getFirst())).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSavedCopyIsToldApartFromThePlayersOwnEntry() {
|
||||
assertThat(FeaturedServers.isSavedCopy(
|
||||
new ServerData("Carrotcraft", "WSS://eagler.carrot-craft.org", ServerData.Type.OTHER), CARROT))
|
||||
.isTrue();
|
||||
assertThat(FeaturedServers.isSavedCopy(
|
||||
new ServerData("My carrots", "wss://eagler.carrot-craft.org", ServerData.Type.OTHER), CARROT))
|
||||
.isFalse();
|
||||
assertThat(FeaturedServers.is(
|
||||
new ServerData("Carrotcraft", "wss://eagler.carrot-craft.org", ServerData.Type.OTHER)))
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePlayersOwnEntryWithAFeaturedNameIsKept() {
|
||||
ServerData own = new ServerData("Carrotcraft", "wss://eagler.carrot-craft.org", ServerData.Type.OTHER);
|
||||
// Written by an older build: a copy of the featured entry, left out.
|
||||
assertThat(FeaturedServers.isSavedCopy(own.write(), own, CARROT)).isTrue();
|
||||
// Written by this one: the player's, kept.
|
||||
ListTag saved = new ListTag();
|
||||
saved.add(own.write());
|
||||
FeaturedServers.markOwn(saved);
|
||||
assertThat(FeaturedServers.isSavedCopy(saved.getCompoundOrEmpty(0), own, CARROT))
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesOutMalformedEntries() {
|
||||
assertThat(FeaturedServers.parse("")).isEmpty();
|
||||
assertThat(FeaturedServers.parse("no-bar;|address;name|")).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package incari.client.net;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class LearnedVersionsTest {
|
||||
|
||||
@TempDir
|
||||
Path folder;
|
||||
|
||||
@Test
|
||||
void remembersAcrossLoads() {
|
||||
LearnedVersions.load(folder).put("Play.Example.net", 47);
|
||||
assertThat(LearnedVersions.load(folder).get("play.example.net")).isEqualTo(47);
|
||||
}
|
||||
|
||||
@Test
|
||||
void dropsTheOldFileUnread() throws IOException {
|
||||
// Its entries may be 1.8 taught by a silent drop after a kick; each server is learned again.
|
||||
Files.writeString(folder.resolve("server-versions.txt"), "wss://carrot.example=47\n");
|
||||
assertThat(LearnedVersions.load(folder).get("wss://carrot.example")).isEqualTo(-1);
|
||||
assertThat(folder.resolve("server-versions.txt")).doesNotExist();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSilentDropOfAVersionThatWorkedIsNoHint() {
|
||||
// A rejoin after a kick, turned away while the old session lingers: not a version problem.
|
||||
assertThat(VersionRetry.dropIsAHint(775, 775)).isFalse();
|
||||
// A first join, or a learned version the server has since stopped speaking.
|
||||
assertThat(VersionRetry.dropIsAHint(775, -1)).isTrue();
|
||||
assertThat(VersionRetry.dropIsAHint(775, 47)).isTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package incari.client.net;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* What {@link PacketHandoff} relies on, read from the game's sources (the patched tree in
|
||||
* {@code work/client}): every client handler that hands its packet to the game's thread does so as
|
||||
* its first statement, to the game's packet processor, except the two {@link PacketHandoff} never
|
||||
* notes. A new version that adds a handler doing something first fails here.
|
||||
*/
|
||||
class PacketHandoffTest {
|
||||
|
||||
private static final String HANDOFF = "PacketUtils.ensureRunningOnSameThread(";
|
||||
|
||||
/** The handlers that do something before handing off, by their packet type. */
|
||||
private static final Set<String> NOT_NOTED = Set.of("ClientboundCustomPayloadPacket", "ClientboundTransferPacket");
|
||||
|
||||
private static final Pattern HANDLER = Pattern.compile(
|
||||
"\n (?:@Override\n )?public void (handle\\w+)\\(final (\\w+) packet\\) \\{\n(.*?)\n }\n",
|
||||
Pattern.DOTALL);
|
||||
|
||||
@Test
|
||||
void everyHandlerThatHandsOffDoesSoFirst() throws IOException {
|
||||
Path listeners = Path.of(System.getProperty("incari.repoRoot", "../.."))
|
||||
.resolve("work/client/src/main/java/net/minecraft/client/multiplayer");
|
||||
List<String> handingOff = new ArrayList<>();
|
||||
List<String> wrong = new ArrayList<>();
|
||||
try (Stream<Path> files = Files.list(listeners)) {
|
||||
for (Path file : files.filter(f -> f.toString().endsWith(".java")).toList()) {
|
||||
Matcher handler = HANDLER.matcher(Files.readString(file));
|
||||
while (handler.find()) {
|
||||
String body = handler.group(3);
|
||||
if (!body.contains(HANDOFF)) {
|
||||
continue;
|
||||
}
|
||||
String where = file.getFileName() + " " + handler.group(1);
|
||||
handingOff.add(where);
|
||||
if (NOT_NOTED.contains(handler.group(2))) {
|
||||
continue;
|
||||
}
|
||||
String first = body.strip().lines().findFirst().orElse("").strip();
|
||||
if (!first.equals(HANDOFF + "packet, this, this.minecraft.packetProcessor());")
|
||||
|| body.indexOf(HANDOFF) != body.lastIndexOf(HANDOFF)) {
|
||||
wrong.add(where + ": " + first);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The pattern still finds the game's handlers (138 hand off in 26.3).
|
||||
assertThat(handingOff).hasSizeGreaterThan(100);
|
||||
assertThat(wrong).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package incari.client.net;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PngBytesTest {
|
||||
|
||||
@Test
|
||||
void writesAPngAnyDecoderReadsBack() throws Exception {
|
||||
byte[] rgba = new byte[64 * 64 * 4];
|
||||
for (int i = 0; i < 64 * 64; i++) {
|
||||
rgba[i * 4] = (byte) i;
|
||||
rgba[i * 4 + 1] = (byte) (i >> 4);
|
||||
rgba[i * 4 + 2] = (byte) 0x80;
|
||||
rgba[i * 4 + 3] = (byte) (i % 2 == 0 ? 0xFF : 0x40);
|
||||
}
|
||||
|
||||
BufferedImage image = ImageIO.read(new ByteArrayInputStream(PngBytes.encode(64, 64, rgba)));
|
||||
|
||||
assertThat(image.getWidth()).isEqualTo(64);
|
||||
assertThat(image.getHeight()).isEqualTo(64);
|
||||
for (int i = 0; i < 64 * 64; i++) {
|
||||
int argb = image.getRGB(i % 64, i / 64);
|
||||
assertThat(argb)
|
||||
.isEqualTo(((rgba[i * 4 + 3] & 0xFF) << 24)
|
||||
| ((rgba[i * 4] & 0xFF) << 16)
|
||||
| ((rgba[i * 4 + 1] & 0xFF) << 8)
|
||||
| (rgba[i * 4 + 2] & 0xFF));
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package incari.client.net;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ReconnectCountdownTest {
|
||||
|
||||
private static final long SECOND = TimeUnit.SECONDS.toNanos(1);
|
||||
|
||||
@Test
|
||||
void countsWholeSecondsDownRoundingUp() {
|
||||
ReconnectCountdown countdown = new ReconnectCountdown();
|
||||
countdown.start(1_000);
|
||||
assertThat(countdown.secondsLeft(1_000)).isEqualTo(ReconnectCountdown.SECONDS);
|
||||
assertThat(countdown.secondsLeft(1_000 + SECOND / 2)).isEqualTo(ReconnectCountdown.SECONDS);
|
||||
assertThat(countdown.secondsLeft(1_000 + SECOND)).isEqualTo(ReconnectCountdown.SECONDS - 1);
|
||||
assertThat(countdown.secondsLeft(1_000 + ReconnectCountdown.SECONDS * SECOND - 1))
|
||||
.isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reachesZeroAndStaysThere() {
|
||||
ReconnectCountdown countdown = new ReconnectCountdown();
|
||||
countdown.start(0);
|
||||
assertThat(countdown.secondsLeft(ReconnectCountdown.SECONDS * SECOND)).isZero();
|
||||
assertThat(countdown.secondsLeft(ReconnectCountdown.SECONDS * SECOND * 10))
|
||||
.isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void startingAgainGivesAFullCountdown() {
|
||||
ReconnectCountdown countdown = new ReconnectCountdown();
|
||||
countdown.start(0);
|
||||
countdown.start(4 * SECOND);
|
||||
assertThat(countdown.secondsLeft(4 * SECOND)).isEqualTo(ReconnectCountdown.SECONDS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package incari.client.net;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class SavedWispProxyTest {
|
||||
|
||||
@TempDir
|
||||
Path folder;
|
||||
|
||||
@Test
|
||||
void remembersAcrossLoads() {
|
||||
assertThat(SavedWispProxy.load(folder)).isNull();
|
||||
SavedWispProxy.save(folder, " wss://wisp.example/ ");
|
||||
assertThat(SavedWispProxy.load(folder)).isEqualTo("wss://wisp.example/");
|
||||
}
|
||||
|
||||
@Test
|
||||
void startsAServerNotYetSetUpFromTheSavedProxy() {
|
||||
assertThat(SavedWispProxy.initial(WispChoice.OFF, "wss://wisp.example/"))
|
||||
.isEqualTo(new WispChoice(false, "wss://wisp.example/"));
|
||||
assertThat(SavedWispProxy.initial(WispChoice.OFF, null)).isEqualTo(WispChoice.OFF);
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsAServerThatHasItsOwnChoice() {
|
||||
WispChoice own = new WispChoice(false, "wss://other.example/");
|
||||
assertThat(SavedWispProxy.initial(own, "wss://wisp.example/")).isEqualTo(own);
|
||||
WispChoice onWithDefault = new WispChoice(true, WispChoice.DEFAULT_PROXY);
|
||||
assertThat(SavedWispProxy.initial(onWithDefault, "wss://wisp.example/")).isEqualTo(onWithDefault);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package incari.client.net;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class VersionRefusalsTest {
|
||||
|
||||
private static final int GAME = 777;
|
||||
private static final Map<String, Integer> NAMES =
|
||||
Map.of("1.8.8", 47, "1.8.9", 47, "1.8.x", 47, "1.12.2", 340, "1.20.4", 765, "1.21.x", 774, "26.1", 775);
|
||||
|
||||
private static int next(String message, int tried, Set<Integer> attempted) {
|
||||
return VersionRefusals.nextProtocol(
|
||||
message, tried, attempted, name -> NAMES.getOrDefault(name, -1), protocol -> protocol >= 47);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsTheVersionASpigotServerIsStillOn() {
|
||||
assertThat(next("Outdated server! I'm still on 1.8.8", GAME, Set.of())).isEqualTo(47);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsItThroughBungeeCordsKick() {
|
||||
assertThat(next("Kicked whilst connecting to lobby: Outdated server! I'm still on 1.8.8", GAME, Set.of()))
|
||||
.isEqualTo(47);
|
||||
}
|
||||
|
||||
@Test
|
||||
void takesTheNewestOfAProxysRangeFirst() {
|
||||
// BungeeCord names the range it speaks; its backend may be anywhere in it.
|
||||
assertThat(next("Outdated server! I'm still on 1.8.x-1.21.x", GAME, Set.of()))
|
||||
.isEqualTo(774);
|
||||
// Then the backend's own refusal takes it the rest of the way.
|
||||
assertThat(next("Outdated server! I'm still on 1.8.8", 774, Set.of(GAME)))
|
||||
.isEqualTo(47);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsModernVanillasTranslatedRefusal() {
|
||||
assertThat(next("Incompatible client! Please use 1.20.4", GAME, Set.of()))
|
||||
.isEqualTo(765);
|
||||
// A translation the client has no text for: its key, then its argument.
|
||||
assertThat(next("multiplayer.disconnect.outdated_client 1.12.2", GAME, Set.of()))
|
||||
.isEqualTo(340);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsAnEaglerVersionMismatch() {
|
||||
assertThat(next("Unsupported client version (the server takes Minecraft protocols 47 to 340)", GAME, Set.of()))
|
||||
.isEqualTo(340);
|
||||
}
|
||||
|
||||
@Test
|
||||
void neverOffersAVersionAlreadyTried() {
|
||||
assertThat(next("Outdated server! I'm still on 1.8.8", 340, Set.of(GAME, 47)))
|
||||
.isEqualTo(-1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesOtherKicksAlone() {
|
||||
assertThat(next("You are banned from this server until 1.8.2027", GAME, Set.of()))
|
||||
.isEqualTo(-1);
|
||||
assertThat(next("Server closed", GAME, Set.of())).isEqualTo(-1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void offersANewerVersionOnlyWhenNothingOlderIsNamed() {
|
||||
assertThat(next("Outdated client! Please use 26.1", 765, Set.of())).isEqualTo(775);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package incari.client.net;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import net.minecraft.client.multiplayer.ServerData;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Via is off unless the player turns it on (ADR 0071), and the disconnection screen says how. */
|
||||
class ViaChoiceTest {
|
||||
|
||||
private static ServerData server(int choice) {
|
||||
ServerData server = new ServerData("Test", "mc.example.com", ServerData.Type.OTHER);
|
||||
server.incariVersion = choice;
|
||||
return server;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewServerHasViaOff() {
|
||||
assertThat(ServerVersions.usesVia(new ServerData("Test", "mc.example.com", ServerData.Type.OTHER)))
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerSavedByAnEarlierBuildLoadsWithViaOff() {
|
||||
CompoundTag saved = new CompoundTag();
|
||||
saved.putInt("incariVersion", 47);
|
||||
ServerData server = server(ServerVersions.AUTO);
|
||||
ServerVersions.read(server, saved);
|
||||
assertThat(server.incariVersion).isEqualTo(ServerVersions.OFF);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theChoiceIsSavedAndReadBack() {
|
||||
for (int choice : new int[] {ServerVersions.AUTO, 47}) {
|
||||
CompoundTag tag = new CompoundTag();
|
||||
ServerVersions.write(server(choice), tag);
|
||||
ServerData read = server(ServerVersions.OFF);
|
||||
ServerVersions.read(read, tag);
|
||||
assertThat(read.incariVersion).isEqualTo(choice);
|
||||
}
|
||||
CompoundTag off = new CompoundTag();
|
||||
ServerVersions.write(server(ServerVersions.OFF), off);
|
||||
assertThat(off.isEmpty()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void hintsAtAVersionRefusalWithViaOff() {
|
||||
assertThat(ViaHint.applies(server(ServerVersions.OFF), false, true, false))
|
||||
.isTrue();
|
||||
assertThat(ViaHint.applies(server(ServerVersions.OFF), false, false, true))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void noHintWithViaOnOrForAnotherKick() {
|
||||
assertThat(ViaHint.applies(server(ServerVersions.AUTO), false, true, false))
|
||||
.isFalse();
|
||||
assertThat(ViaHint.applies(server(ServerVersions.OFF), false, false, false))
|
||||
.isFalse();
|
||||
assertThat(ViaHint.applies(null, false, true, true)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsTheUsualRefusals() {
|
||||
assertThat(VersionRefusals.isAboutVersions("Outdated server! I'm still on 1.8.8"))
|
||||
.isTrue();
|
||||
assertThat(VersionRefusals.isAboutVersions("Outdated client! Please use 1.8.8"))
|
||||
.isTrue();
|
||||
assertThat(VersionRefusals.isAboutVersions("multiplayer.disconnect.incompatible 1.20.4"))
|
||||
.isTrue();
|
||||
assertThat(VersionRefusals.isAboutVersions("You were kicked for flying"))
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsThePagesViaChoice() {
|
||||
assertThat(ServerVersions.parseChoice("auto")).isEqualTo(ServerVersions.AUTO);
|
||||
assertThat(ServerVersions.parseChoice("Off")).isEqualTo(ServerVersions.OFF);
|
||||
assertThat(ServerVersions.parseChoice("1.8.9")).isEqualTo(47);
|
||||
assertThat(ServerVersions.parseChoice("banana")).isEqualTo(ServerVersions.UNKNOWN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQuickPlayJoinGetsThePagesChoiceOnce() {
|
||||
assertThat(ServerVersions.setQuickPlay("ws://127.0.0.1:8801", "auto")).isTrue();
|
||||
ServerData other = new ServerData("Other", "ws://127.0.0.1:9999", ServerData.Type.OTHER);
|
||||
ServerVersions.applyQuickPlay(other);
|
||||
assertThat(ServerVersions.usesVia(other)).isFalse();
|
||||
ServerData quick = new ServerData("Minecraft Server", "ws://127.0.0.1:8801", ServerData.Type.OTHER);
|
||||
ServerVersions.applyQuickPlay(quick);
|
||||
assertThat(quick.incariVersion).isEqualTo(ServerVersions.AUTO);
|
||||
ServerData again = new ServerData("Minecraft Server", "ws://127.0.0.1:8801", ServerData.Type.OTHER);
|
||||
ServerVersions.applyQuickPlay(again);
|
||||
assertThat(ServerVersions.usesVia(again)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEaglerServerFoundToRunAnotherVersionNeedsViaWhileItsOff() {
|
||||
ServerData off = server(ServerVersions.OFF);
|
||||
off.protocol = ServerVersions.UNKNOWN;
|
||||
assertThat(ServerVersions.isCompatible(off, () -> 47)).isFalse();
|
||||
assertThat(ServerVersions.isCompatible(off, () -> -1)).isTrue();
|
||||
assertThat(ServerVersions.isCompatible(off, ServerVersions::gameProtocol))
|
||||
.isTrue();
|
||||
ServerData auto = server(ServerVersions.AUTO);
|
||||
auto.protocol = ServerVersions.UNKNOWN;
|
||||
assertThat(ServerVersions.isCompatible(auto, () -> 47)).isTrue();
|
||||
|
||||
assertThat(EaglerPings.versionLabel(47, false)).startsWith("Needs Via");
|
||||
assertThat(EaglerPings.versionLabel(47, true)).startsWith("Eagler ");
|
||||
assertThat(EaglerPings.versionLabel(-1, false)).isEqualTo("Eagler");
|
||||
assertThat(EaglerPings.versionLabel(ServerVersions.gameProtocol(), false))
|
||||
.startsWith("Eagler ");
|
||||
}
|
||||
|
||||
@Test
|
||||
void noEditHintForAFeaturedServer() {
|
||||
assertThat(ViaHint.applies(server(ServerVersions.OFF), true, true, true))
|
||||
.isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package incari.client.online;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.IncariBuild;
|
||||
import incari.framework.config.ConfigStorage;
|
||||
import incari.online.FakeService;
|
||||
import incari.online.OnlineService;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class UpdateNoticeTest {
|
||||
|
||||
private final FakeService fake = new FakeService();
|
||||
|
||||
@AfterEach
|
||||
void unforce() {
|
||||
UpdateNotice.force(false);
|
||||
}
|
||||
|
||||
/** A client that has said hello to a service naming {@code release} as the latest. */
|
||||
private OnlineService greeted(String release, String... notes) {
|
||||
fake.announceRelease(release, notes);
|
||||
Map<String, String> files = new HashMap<>();
|
||||
OnlineService online = new OnlineService(
|
||||
"wss://online.test/v1/ws",
|
||||
"test",
|
||||
fake,
|
||||
new ConfigStorage() {
|
||||
@Override
|
||||
public @Nullable String read(String path) {
|
||||
return files.get(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(String path, String text) {
|
||||
files.put(path, text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String path) {
|
||||
files.remove(path);
|
||||
}
|
||||
},
|
||||
Runnable::run,
|
||||
() -> {},
|
||||
() -> 0,
|
||||
() -> 0.5,
|
||||
(message, error) -> {});
|
||||
online.start();
|
||||
for (int i = 0; i < 6; i++) {
|
||||
online.tick();
|
||||
}
|
||||
assertThat(online.latestRelease()).isEqualTo(release);
|
||||
return online;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDevBuildIsNeverTold() {
|
||||
assertThat(IncariBuild.RELEASE).isFalse();
|
||||
assertThat(UpdateNotice.newer(greeted("999.0.0"))).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewerReleaseIsShown() {
|
||||
UpdateNotice.force(true);
|
||||
assertThat(UpdateNotice.newer(greeted("999.0.0"))).isEqualTo("999.0.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void thisReleaseOrAnOlderOneIsNot() {
|
||||
UpdateNotice.force(true);
|
||||
assertThat(UpdateNotice.newer(greeted(IncariBuild.VERSION))).isNull();
|
||||
assertThat(UpdateNotice.newer(greeted("0.0.1"))).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theNoticeCarriesTheNewerReleasesChangelog() {
|
||||
UpdateNotice.force(true);
|
||||
assertThat(UpdateNotice.notes(greeted("999.0.0", "Faster chunk loading", "A changelog")))
|
||||
.containsExactly("Faster chunk loading", "A changelog");
|
||||
assertThat(UpdateNotice.notes(greeted("999.0.0"))).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void noChangelogWithoutANotice() {
|
||||
assertThat(UpdateNotice.notes(greeted("999.0.0", "Faster chunk loading")))
|
||||
.as("dev build")
|
||||
.isEmpty();
|
||||
UpdateNotice.force(true);
|
||||
assertThat(UpdateNotice.notes(greeted("0.0.1", "Old news"))).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package incari.client.profile;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.client.account.MicrosoftAccounts;
|
||||
import incari.net.msa.MicrosoftAccount;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.client.User;
|
||||
import net.minecraft.core.UUIDUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class PlayerNameTest {
|
||||
|
||||
@TempDir
|
||||
Path gameDirectory;
|
||||
|
||||
@AfterEach
|
||||
void forget() {
|
||||
PlayerName.reset();
|
||||
MicrosoftAccounts.reset();
|
||||
}
|
||||
|
||||
private void saveMicrosoftAccount() throws IOException {
|
||||
Files.createDirectories(gameDirectory.resolve("incari"));
|
||||
MicrosoftAccount account = new MicrosoftAccount(
|
||||
"Notch", "069a79f444e94726a5befca90e38aaf5", "mc-token", Long.MAX_VALUE, "refresh");
|
||||
Files.writeString(gameDirectory.resolve("incari/microsoft-account.json"), account.toJson());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSavedMicrosoftAccountIsThePlayer() throws IOException {
|
||||
save("Chosen_1");
|
||||
saveMicrosoftAccount();
|
||||
User user = PlayerName.user(launched("Player123", "0"), gameDirectory.toFile());
|
||||
assertThat(user.getName()).isEqualTo("Notch");
|
||||
assertThat(user.getProfileId()).isEqualTo(UUID.fromString("069a79f4-44e9-4726-a5be-fca90e38aaf5"));
|
||||
assertThat(user.getAccessToken()).isEqualTo("mc-token");
|
||||
assertThat(PlayerName.name()).isEqualTo("Notch");
|
||||
assertThat(PlayerName.editable()).isFalse();
|
||||
assertThat(PlayerName.asksAtStartup()).isFalse();
|
||||
assertThatThrownBy(() -> PlayerName.set("Other_1")).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void signingOutGoesBackToTheOfflineNameAndDeletesTheTokens() throws IOException {
|
||||
save("Chosen_1");
|
||||
saveMicrosoftAccount();
|
||||
User launched = launched("Player123", "0");
|
||||
PlayerName.user(launched, gameDirectory.toFile());
|
||||
MicrosoftAccounts.signOut();
|
||||
assertThat(PlayerName.user(launched, gameDirectory.toFile()).getName()).isEqualTo("Chosen_1");
|
||||
assertThat(PlayerName.editable()).isTrue();
|
||||
assertThat(gameDirectory.resolve("incari/microsoft-account.json")).doesNotExist();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLauncherAccountIgnoresIncarisSignIn() throws IOException {
|
||||
saveMicrosoftAccount();
|
||||
User account = new User("Real", UUID.randomUUID(), "token", Optional.empty(), Optional.empty());
|
||||
assertThat(PlayerName.user(account, gameDirectory.toFile())).isSameAs(account);
|
||||
assertThat(PlayerName.launchedOffline()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBrokenAccountFileIsIgnored() throws IOException {
|
||||
Files.createDirectories(gameDirectory.resolve("incari"));
|
||||
Files.writeString(gameDirectory.resolve("incari/microsoft-account.json"), "{\"version\":1,\"name\":\"\"}");
|
||||
User launched = launched("Player123", "0");
|
||||
assertThat(PlayerName.user(launched, gameDirectory.toFile())).isSameAs(launched);
|
||||
}
|
||||
|
||||
private static User launched(String name, String token) {
|
||||
return new User(name, UUIDUtil.createOfflinePlayerUUID(name), token, Optional.empty(), Optional.empty());
|
||||
}
|
||||
|
||||
private void save(String name) throws IOException {
|
||||
Files.createDirectories(gameDirectory.resolve("incari"));
|
||||
Files.writeString(gameDirectory.resolve("incari/profile.properties"), "name=" + name + "\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void takesWhatEveryServerTakes() {
|
||||
assertThat(PlayerName.isValid("Steve_123")).isTrue();
|
||||
assertThat(PlayerName.isValid("abc")).isTrue();
|
||||
assertThat(PlayerName.isValid("abcdefghijklmnop")).isTrue();
|
||||
assertThat(PlayerName.isValid("ab")).isFalse();
|
||||
assertThat(PlayerName.isValid("abcdefghijklmnopq")).isFalse();
|
||||
assertThat(PlayerName.isValid("two words")).isFalse();
|
||||
assertThat(PlayerName.isValid("ümlaut")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void filterKeepsLettersDigitsAndUnderscores() {
|
||||
assertThat(PlayerName.filter("Hi there! _9-é")).isEqualTo("Hithere_9");
|
||||
}
|
||||
|
||||
@Test
|
||||
void offlinePlaysUnderTheSavedNameWithItsOfflineUuid() throws IOException {
|
||||
save("Chosen_1");
|
||||
User user = PlayerName.user(launched("Player123", "0"), gameDirectory.toFile());
|
||||
assertThat(user.getName()).isEqualTo("Chosen_1");
|
||||
assertThat(user.getProfileId()).isEqualTo(UUIDUtil.createOfflinePlayerUUID("Chosen_1"));
|
||||
assertThat(PlayerName.asksAtStartup()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void withNothingSavedPlaysUnderTheLaunchName() {
|
||||
User launched = launched("Player123", "0");
|
||||
assertThat(PlayerName.user(launched, gameDirectory.toFile())).isSameAs(launched);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNameFixedAtLaunchStands() throws IOException {
|
||||
save("Chosen_1");
|
||||
PlayerName.fixAtLaunch();
|
||||
User launched = launched("Bench", "0");
|
||||
assertThat(PlayerName.user(launched, gameDirectory.toFile())).isSameAs(launched);
|
||||
assertThat(PlayerName.asksAtStartup()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAccountKeepsItsOwnName() throws IOException {
|
||||
save("Chosen_1");
|
||||
User account = new User("Real", UUID.randomUUID(), "token", Optional.empty(), Optional.empty());
|
||||
assertThat(PlayerName.user(account, gameDirectory.toFile())).isSameAs(account);
|
||||
assertThat(PlayerName.editable()).isFalse();
|
||||
assertThat(PlayerName.asksAtStartup()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void setPlaysUnderTheNameAndKeepsIt() throws IOException {
|
||||
PlayerName.user(launched("Player123", "0"), gameDirectory.toFile());
|
||||
PlayerName.set("New_Name");
|
||||
assertThat(PlayerName.name()).isEqualTo("New_Name");
|
||||
assertThat(Files.readString(gameDirectory.resolve("incari/profile.properties")))
|
||||
.contains("name=New_Name");
|
||||
|
||||
PlayerName.reset();
|
||||
assertThat(PlayerName.user(launched("Player456", "0"), gameDirectory.toFile())
|
||||
.getName())
|
||||
.isEqualTo("New_Name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesANameNoServerTakes() {
|
||||
PlayerName.user(launched("Player123", "0"), gameDirectory.toFile());
|
||||
assertThatThrownBy(() -> PlayerName.set("no")).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ignoresASavedNameNoServerTakes() throws IOException {
|
||||
save("bad name!");
|
||||
User launched = launched("Player123", "0");
|
||||
assertThat(PlayerName.user(launched, gameDirectory.toFile())).isSameAs(launched);
|
||||
}
|
||||
|
||||
@Test
|
||||
void suggestsNamesWithIncariThatEveryServerTakes() {
|
||||
Random random = new Random(1);
|
||||
for (int i = 0; i < 10_000; i++) {
|
||||
String name = PlayerName.suggest(random);
|
||||
assertThat(name).contains("Incari");
|
||||
assertThat(PlayerName.isValid(name)).as(name).isTrue();
|
||||
assertThat(PlayerName.isSuggestion(name)).as(name).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tellsMadeUpNamesFromChosenOnes() {
|
||||
assertThat(PlayerName.isSuggestion("IncariFox482")).isTrue();
|
||||
assertThat(PlayerName.isSuggestion("YeeIncari07")).isFalse();
|
||||
assertThat(PlayerName.isSuggestion("YeeIncari70")).isTrue();
|
||||
assertThat(PlayerName.isSuggestion("IncariFox")).isFalse();
|
||||
assertThat(PlayerName.isSuggestion("IncariFox1")).isFalse();
|
||||
assertThat(PlayerName.isSuggestion("Steve_123")).isFalse();
|
||||
assertThat(PlayerName.isSuggestion("Incari123")).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package incari.client.profiler;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FrameHistoryTest {
|
||||
|
||||
@Test
|
||||
void keepsTheNewestFrames() {
|
||||
FrameHistory history = new FrameHistory(3);
|
||||
for (int frame = 1; frame <= 5; frame++) {
|
||||
history.add(frame);
|
||||
}
|
||||
|
||||
assertThat(history.size()).isEqualTo(3);
|
||||
assertThat(history.ago(0)).isEqualTo(5);
|
||||
assertThat(history.ago(2)).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void framesPerSecondCoverTheWindow() {
|
||||
FrameHistory history = new FrameHistory(100);
|
||||
for (int frame = 0; frame < 100; frame++) {
|
||||
history.add(20);
|
||||
}
|
||||
|
||||
// 50 frames of 20 ms fill a second.
|
||||
assertThat(history.framesPerSecond(1000)).isCloseTo(50, within(1e-9));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOnePercentLowAveragesTheSlowestFrames() {
|
||||
FrameHistory history = new FrameHistory(200);
|
||||
for (int frame = 0; frame < 198; frame++) {
|
||||
history.add(10);
|
||||
}
|
||||
history.add(40);
|
||||
history.add(50);
|
||||
|
||||
assertThat(history.slowestMean(1)).isEqualTo(45);
|
||||
assertThat(new FrameHistory(4).slowestMean(1)).isNaN();
|
||||
}
|
||||
|
||||
@Test
|
||||
void tenthsWithoutFormatting() {
|
||||
assertThat(ProfilerOverlay.tenths(16.66)).isEqualTo("16.7");
|
||||
assertThat(ProfilerOverlay.tenths(0.04)).isEqualTo("0.0");
|
||||
assertThat(ProfilerOverlay.tenths(-1.26)).isEqualTo("-1.3");
|
||||
assertThat(ProfilerOverlay.tenths(Double.NaN)).isEqualTo("n/a");
|
||||
}
|
||||
|
||||
@Test
|
||||
void zonesCountTowardsTheirPartOfTheFrame() {
|
||||
assertThat(FrameProfiler.outerZone("tick")).isEqualTo(FrameProfiler.outerZone("scheduledPacketProcessing"));
|
||||
assertThat(FrameProfiler.outerZone("frame")).isNotEqualTo(FrameProfiler.outerZone("tick"));
|
||||
assertThat(FrameProfiler.outerZone("sound")).isZero();
|
||||
assertThat(FrameProfiler.innerZone("render")).isEqualTo(FrameProfiler.innerZone("submit"));
|
||||
assertThat(FrameProfiler.innerZone("extract")).isNotEqualTo(FrameProfiler.innerZone("render"));
|
||||
assertThat(FrameProfiler.innerZone("frameLimiter")).isZero();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package incari.client.render;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.tier.DeviceTier;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class AtlasBudgetTest {
|
||||
|
||||
@AfterEach
|
||||
void restoreTier() {
|
||||
DeviceTier.set(DeviceTier.HIGH);
|
||||
}
|
||||
|
||||
@Test
|
||||
void vanillasLargestAtlasFitsEveryTier() {
|
||||
for (DeviceTier tier : DeviceTier.values()) {
|
||||
assertThat(AtlasBudget.maxSize(tier)).isGreaterThanOrEqualTo(2048);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDevicesLimitWinsWhenItsSmaller() {
|
||||
DeviceTier.set(DeviceTier.HIGH);
|
||||
assertThat(AtlasBudget.maxSize(8192)).isEqualTo(8192);
|
||||
DeviceTier.set(DeviceTier.POTATO);
|
||||
assertThat(AtlasBudget.maxSize(8192)).isEqualTo(2048);
|
||||
}
|
||||
|
||||
@Test
|
||||
void averagesOpaquePixels() {
|
||||
int mean = AtlasBudget.mean(0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF);
|
||||
assertThat(mean).isEqualTo(0xFF808080);
|
||||
}
|
||||
|
||||
@Test
|
||||
void transparentPixelsLendNoColour() {
|
||||
// One opaque red pixel among three transparent white ones: red, at a quarter of the alpha.
|
||||
int mean = AtlasBudget.mean(0xFFFF0000, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF);
|
||||
assertThat(mean).isEqualTo(0x3FFF0000);
|
||||
assertThat(AtlasBudget.mean(0, 0, 0, 0)).isZero();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package incari.client.render;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import incari.client.testing.TestPlatform;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Matrix4fc;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* {@link GlyphQuads} writes a glyph's quad as the game's four vertex calls write it: the same
|
||||
* positions to the bit (transformed as {@code BufferBuilder} transforms them, {@link VertexMath}),
|
||||
* and the same color, texture corners and light in the same order ({@code BufferBuilder} packs them
|
||||
* with its own helpers either way).
|
||||
*/
|
||||
class GlyphQuadsTest {
|
||||
|
||||
@BeforeAll
|
||||
static void platform() {
|
||||
TestPlatform.install();
|
||||
}
|
||||
|
||||
/** The game's vertices, as {@code BufferBuilder} receives them after its transform. */
|
||||
private static final class Recorder implements VertexConsumer {
|
||||
final List<String> vertices = new ArrayList<>();
|
||||
private String vertex = "";
|
||||
|
||||
@Override
|
||||
public VertexConsumer addVertex(Matrix4fc pose, float x, float y, float z) {
|
||||
// BufferBuilder's own override: VertexMath's transform.
|
||||
return VertexMath.addVertex(this, pose, x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer addVertex(float x, float y, float z) {
|
||||
vertex = Float.floatToRawIntBits(x) + " " + Float.floatToRawIntBits(y) + " " + Float.floatToRawIntBits(z);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setColor(int color) {
|
||||
vertex += " color " + color;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv(float u, float v) {
|
||||
vertex += " uv " + Float.floatToRawIntBits(u) + " " + Float.floatToRawIntBits(v);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setLight(int light) {
|
||||
vertices.add(vertex + " light " + light);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setColor(int red, int green, int blue, int alpha) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv1(int u, int v) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv2(int u, int v) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv3(float u, float v) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setNormal(float x, float y, float z) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setLineWidth(float width) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesTheGamesVertices() {
|
||||
// A name tag's pose: turned to the camera, scaled to text size, some way off.
|
||||
Matrix4f pose = new Matrix4f()
|
||||
.translate(3.25F, 1.875F, -7.5F)
|
||||
.rotateXYZ(0.21F, -2.3F, 0.05F)
|
||||
.scale(0.025F, -0.025F, 0.025F);
|
||||
float x0 = -21.5F;
|
||||
float x1 = -15.5F;
|
||||
float y0 = 0.0F;
|
||||
float y1 = 8.0F;
|
||||
float shear0 = 0.1F;
|
||||
float shear1 = 0.6F;
|
||||
float thick = 0.1F;
|
||||
float z = 0.03F;
|
||||
int color = 0xC8F0E0D0;
|
||||
int light = 0x00F000A0;
|
||||
float u0 = 0.125F;
|
||||
float u1 = 0.1328125F;
|
||||
float v0 = 0.25F;
|
||||
float v1 = 0.2578125F;
|
||||
|
||||
// BakedSheetGlyph.render's four vertices, as the game writes them.
|
||||
Recorder game = new Recorder();
|
||||
game.addVertex(pose, x0 + shear0 - thick, y0 - thick, z)
|
||||
.setColor(color)
|
||||
.setUv(u0, v0)
|
||||
.setLight(light);
|
||||
game.addVertex(pose, x0 + shear1 - thick, y1 + thick, z)
|
||||
.setColor(color)
|
||||
.setUv(u0, v1)
|
||||
.setLight(light);
|
||||
game.addVertex(pose, x1 + shear1 + thick, y1 + thick, z)
|
||||
.setColor(color)
|
||||
.setUv(u1, v1)
|
||||
.setLight(light);
|
||||
game.addVertex(pose, x1 + shear0 + thick, y0 - thick, z)
|
||||
.setColor(color)
|
||||
.setUv(u1, v0)
|
||||
.setLight(light);
|
||||
|
||||
List<String> quad = new ArrayList<>();
|
||||
GlyphQuads.quad(
|
||||
(x, y, vz, vertexColor, u, v, vertexLight) -> quad.add(Float.floatToRawIntBits(x) + " "
|
||||
+ Float.floatToRawIntBits(y) + " " + Float.floatToRawIntBits(vz)
|
||||
+ " color " + vertexColor
|
||||
+ " uv " + Float.floatToRawIntBits(u) + " " + Float.floatToRawIntBits(v)
|
||||
+ " light " + vertexLight),
|
||||
pose,
|
||||
x0 + shear0 - thick,
|
||||
y0 - thick,
|
||||
x0 + shear1 - thick,
|
||||
y1 + thick,
|
||||
x1 + shear1 + thick,
|
||||
y1 + thick,
|
||||
x1 + shear0 + thick,
|
||||
y0 - thick,
|
||||
z,
|
||||
color,
|
||||
u0,
|
||||
v0,
|
||||
u1,
|
||||
v1,
|
||||
light);
|
||||
|
||||
assertThat(quad).containsExactlyElementsOf(game.vertices);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package incari.client.render;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.common.primitives.Floats;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrays;
|
||||
import java.util.Random;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** {@link QuadSort} gives the game's merge sort's permutation exactly, ties and odd floats included. */
|
||||
class QuadSortTest {
|
||||
|
||||
private static final float[] ODD = {
|
||||
0.0F,
|
||||
-0.0F,
|
||||
Float.NaN,
|
||||
Float.intBitsToFloat(0x7fc00001),
|
||||
Float.POSITIVE_INFINITY,
|
||||
Float.NEGATIVE_INFINITY,
|
||||
Float.MIN_VALUE,
|
||||
-Float.MIN_VALUE,
|
||||
Float.MAX_VALUE,
|
||||
-Float.MAX_VALUE,
|
||||
1.0F,
|
||||
-1.0F
|
||||
};
|
||||
|
||||
@Test
|
||||
void sortsAsTheGameDoes() {
|
||||
Random random = new Random(20261001);
|
||||
for (int round = 0; round < 400; round++) {
|
||||
int n = round < 100 ? round : random.nextInt(5000);
|
||||
float[] keys = new float[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
keys[i] = switch (random.nextInt(4)) {
|
||||
// Few distinct values: many ties, which the order of the indices must survive.
|
||||
case 0 -> random.nextInt(8);
|
||||
case 1 -> ODD[random.nextInt(ODD.length)];
|
||||
case 2 -> (random.nextFloat() - 0.5F) * 1000.0F;
|
||||
default -> random.nextFloat() * random.nextFloat();
|
||||
};
|
||||
}
|
||||
assertThat(quadSort(keys)).as("round %d, %d keys", round, n).containsExactly(gameSort(keys));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theGamesOwnSortWhenTurnedOff() {
|
||||
float[] keys = {3, 1, 2, 2, Float.NaN, -0.0F, 0.0F};
|
||||
QuadSort.setEnabled(false);
|
||||
try {
|
||||
assertThat(quadSort(keys)).containsExactly(gameSort(keys));
|
||||
} finally {
|
||||
QuadSort.setEnabled(true);
|
||||
}
|
||||
}
|
||||
|
||||
private static int[] quadSort(float[] keys) {
|
||||
int[] indices = identity(keys.length);
|
||||
QuadSort.sortDescending(keys, indices);
|
||||
return indices;
|
||||
}
|
||||
|
||||
private static int[] gameSort(float[] keys) {
|
||||
int[] indices = identity(keys.length);
|
||||
IntArrays.mergeSort(indices, (o1, o2) -> Floats.compare(keys[o2], keys[o1]));
|
||||
return indices;
|
||||
}
|
||||
|
||||
private static int[] identity(int n) {
|
||||
int[] indices = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
indices[i] = i;
|
||||
}
|
||||
return indices;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package incari.client.render;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.UUID;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.network.chat.ClickEvent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.HoverEvent;
|
||||
import net.minecraft.network.chat.Style;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** What makes two styles lay text out the same way, for {@link TextLayouts}. */
|
||||
class TextLayoutsTest {
|
||||
|
||||
@Test
|
||||
void eventsDontChangeTheLayout() {
|
||||
Style plain = Style.EMPTY.withColor(ChatFormatting.YELLOW);
|
||||
Style withEvents = plain.withHoverEvent(new HoverEvent.ShowText(
|
||||
Component.literal(UUID.randomUUID().toString())))
|
||||
.withClickEvent(new ClickEvent.SuggestCommand("/msg"));
|
||||
|
||||
assertThat(TextLayouts.sameLayout(plain, withEvents)).isTrue();
|
||||
assertThat(TextLayouts.layoutHash(plain)).isEqualTo(TextLayouts.layoutHash(withEvents));
|
||||
}
|
||||
|
||||
@Test
|
||||
void colourAndWeightDo() {
|
||||
Style yellow = Style.EMPTY.withColor(ChatFormatting.YELLOW);
|
||||
assertThat(TextLayouts.sameLayout(yellow, Style.EMPTY.withColor(ChatFormatting.RED)))
|
||||
.isFalse();
|
||||
assertThat(TextLayouts.sameLayout(yellow, yellow.withBold(true))).isFalse();
|
||||
assertThat(TextLayouts.sameLayout(yellow, yellow.withObfuscated(true))).isFalse();
|
||||
assertThat(TextLayouts.sameLayout(Style.EMPTY, Style.EMPTY.withShadowColor(0xFF000000)))
|
||||
.isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package incari.client.render;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.testing.TestPlatform;
|
||||
import java.util.Random;
|
||||
import net.minecraft.util.ARGB;
|
||||
import net.minecraft.world.level.ColorResolver;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** {@link TintBlend} blends as the game's {@code ClientLevel.calculateBlockTint}, reused samples or not. */
|
||||
class TintBlendTest {
|
||||
|
||||
private static final ColorResolver GRASS = (biome, x, z) -> 1;
|
||||
private static final ColorResolver FOLIAGE = (biome, x, z) -> 2;
|
||||
|
||||
@BeforeAll
|
||||
static void platform() {
|
||||
// Its block position class starts the game's background pool, which asks the platform.
|
||||
TestPlatform.install();
|
||||
}
|
||||
|
||||
@Test
|
||||
void blendsAsTheGameDoesAlongRowsAndAcrossThem() {
|
||||
Random random = new Random(20261001);
|
||||
// Colours that depend on the position and the resolver, as swamp grass's do.
|
||||
TintBlend.ColorAt grass = (x, y, z) -> hash(x, y, z, 1);
|
||||
TintBlend.ColorAt foliage = (x, y, z) -> hash(x, y, z, 2);
|
||||
int x = 0;
|
||||
int y = 64;
|
||||
int z = 0;
|
||||
for (int i = 0; i < 20000; i++) {
|
||||
switch (random.nextInt(10)) {
|
||||
case 0, 1, 2, 3 -> x++;
|
||||
case 4 -> x += random.nextInt(6);
|
||||
case 5 -> x -= random.nextInt(3);
|
||||
case 6 -> z += random.nextInt(3) - 1;
|
||||
case 7 -> y += random.nextInt(3) - 1;
|
||||
case 8 -> TintBlend.changed();
|
||||
default -> x = random.nextInt(64) - 32;
|
||||
}
|
||||
int radius = random.nextInt(20) == 0 ? random.nextInt(8) + 1 : 2;
|
||||
boolean useFoliage = random.nextInt(5) == 0;
|
||||
ColorResolver resolver = useFoliage ? FOLIAGE : GRASS;
|
||||
TintBlend.ColorAt colors = useFoliage ? foliage : grass;
|
||||
assertThat(TintBlend.blend(x, y, z, resolver, radius, colors))
|
||||
.as("step %d at %d %d %d, radius %d", i, x, y, z, radius)
|
||||
.isEqualTo(gameBlend(x, y, z, radius, colors));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void forgetsSamplesWhenTheBiomesChange() {
|
||||
int[] shift = {0};
|
||||
TintBlend.ColorAt colors = (x, y, z) -> hash(x, y, z, 3) + shift[0];
|
||||
int before = TintBlend.blend(5, 70, 5, GRASS, 2, colors);
|
||||
assertThat(before).isEqualTo(gameBlend(5, 70, 5, 2, colors));
|
||||
shift[0] = 0x010101;
|
||||
TintBlend.changed();
|
||||
assertThat(TintBlend.blend(6, 70, 5, GRASS, 2, colors)).isEqualTo(gameBlend(6, 70, 5, 2, colors));
|
||||
}
|
||||
|
||||
/** The game's own loop, as written in {@code ClientLevel.calculateBlockTint}. */
|
||||
private static int gameBlend(int x, int y, int z, int radius, TintBlend.ColorAt colors) {
|
||||
int count = (radius * 2 + 1) * (radius * 2 + 1);
|
||||
int totalRed = 0;
|
||||
int totalGreen = 0;
|
||||
int totalBlue = 0;
|
||||
for (int sz = z - radius; sz <= z + radius; sz++) {
|
||||
for (int sx = x - radius; sx <= x + radius; sx++) {
|
||||
int color = colors.color(sx, y, sz);
|
||||
totalRed += ARGB.red(color);
|
||||
totalGreen += ARGB.green(color);
|
||||
totalBlue += ARGB.blue(color);
|
||||
}
|
||||
}
|
||||
return ARGB.color(totalRed / count, totalGreen / count, totalBlue / count);
|
||||
}
|
||||
|
||||
private static int hash(int x, int y, int z, int salt) {
|
||||
int h = (x * 31 + y) * 31 + z + salt * 1000003;
|
||||
h ^= h >>> 13;
|
||||
h *= 0x5bd1e995;
|
||||
h ^= h >>> 15;
|
||||
return 0xFF000000 | (h & 0xFFFFFF);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package incari.client.render;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.vertex.QuadInstance;
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import incari.client.testing.TestPlatform;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.minecraft.client.model.geom.builders.UVPair;
|
||||
import net.minecraft.client.resources.model.geometry.BakedQuad;
|
||||
import net.minecraft.core.Direction;
|
||||
import org.joml.Vector3f;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** {@link VertexMath#putBakedQuad} writes what the game's {@code putBakedQuad} writes, to the bit. */
|
||||
class VertexMathTest {
|
||||
|
||||
/** Every vertex written, as the 11 values the game hands over. */
|
||||
private static final class Recorder implements VertexConsumer {
|
||||
final List<String> vertices = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public VertexConsumer addVertex(float x, float y, float z) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setColor(int red, int green, int blue, int alpha) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setColor(int color) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv(float u, float v) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv1(int u, int v) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv2(int u, int v) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv3(float u, float v) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setNormal(float x, float y, float z) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setLineWidth(float width) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addVertex(
|
||||
float x,
|
||||
float y,
|
||||
float z,
|
||||
int color,
|
||||
float u,
|
||||
float v,
|
||||
int overlay,
|
||||
int light,
|
||||
float nx,
|
||||
float ny,
|
||||
float nz) {
|
||||
vertices.add(
|
||||
Float.floatToRawIntBits(x) + " " + Float.floatToRawIntBits(y) + " " + Float.floatToRawIntBits(z)
|
||||
+ " " + color + " " + u + " " + v + " " + overlay + " " + light + " "
|
||||
+ Float.floatToRawIntBits(nx) + " " + Float.floatToRawIntBits(ny) + " "
|
||||
+ Float.floatToRawIntBits(nz));
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
static void onTheRenderThread() {
|
||||
TestPlatform.install();
|
||||
// Once per test JVM: another test class may have made this thread the render thread already.
|
||||
if (!RenderSystem.isOnRenderThread()) {
|
||||
RenderSystem.initRenderThread();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("NullAway") // The quad's material is only asked for its light emission.
|
||||
void writesTheGamesVertices() {
|
||||
BakedQuad quad = new BakedQuad(
|
||||
new Vector3f(0.1F, 0.2F, 0.3F),
|
||||
new Vector3f(0.9F, 0.2F, 0.3F),
|
||||
new Vector3f(0.9F, 0.8F, 0.3F),
|
||||
new Vector3f(0.1F, 0.8F, 0.3F),
|
||||
UVPair.pack(0.25F, 0.5F),
|
||||
UVPair.pack(0.5F, 0.5F),
|
||||
UVPair.pack(0.5F, 0.75F),
|
||||
UVPair.pack(0.25F, 0.75F),
|
||||
Direction.SOUTH,
|
||||
new BakedQuad.MaterialInfo(null, null, null, null, null, -1, null, 3));
|
||||
PoseStack poses = new PoseStack();
|
||||
poses.translate(1.5F, -2.25F, 0.125F);
|
||||
poses.mulPose(new org.joml.Matrix4f().rotateXYZ(0.3F, 1.1F, -0.4F));
|
||||
poses.scale(0.7F, 1.3F, -0.9F);
|
||||
QuadInstance instance = new QuadInstance();
|
||||
instance.setColor(0, 0xFF102030);
|
||||
instance.setLightCoords(2, 0x00F000A0);
|
||||
instance.setOverlayCoords(0x000A0003);
|
||||
|
||||
Recorder game = new Recorder();
|
||||
// The game's own path: VertexConsumer's default, which Recorder doesn't override.
|
||||
game.putBakedQuad(poses.last(), quad, instance);
|
||||
Recorder incari = new Recorder();
|
||||
assertThat(VertexMath.putBakedQuad(incari, poses.last(), quad, instance))
|
||||
.isTrue();
|
||||
|
||||
assertThat(incari.vertices).hasSize(4).isEqualTo(game.vertices);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package incari.client.render.entity;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.testing.TestPlatform;
|
||||
import net.minecraft.client.renderer.RenderPipelines;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Which of the game's pipelines get an instanced copy. */
|
||||
class InstancedPipelinesTest {
|
||||
|
||||
@Test
|
||||
void opaqueEntityPipelinesAreCopied() {
|
||||
TestPlatform.install();
|
||||
assertThat(InstancedPipelines.of(RenderPipelines.ARMOR_CUTOUT_NO_CULL)).isNotNull();
|
||||
assertThat(InstancedPipelines.of(RenderPipelines.ENTITY_CUTOUT)).isNotNull();
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
package incari.client.render.entity;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.vertex.QuadInstance;
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import incari.client.testing.TestPlatform;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import net.minecraft.client.model.geom.builders.UVPair;
|
||||
import net.minecraft.client.resources.model.geometry.BakedQuad;
|
||||
import net.minecraft.core.Direction;
|
||||
import org.joml.Matrix3f;
|
||||
import org.joml.Vector3f;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* An item's quads drawn instanced ({@link ModelMesh#ofQuads}, ADR 0027) land where the game's
|
||||
* {@code putBakedQuad} puts them: each baked vertex placed by the instance's rows as the rewritten
|
||||
* shader places it, against the game's own vertex writes.
|
||||
*/
|
||||
class ItemMeshTest {
|
||||
|
||||
/** The game's vertices: position, texture coordinates, normal. */
|
||||
private static final class Recorder implements VertexConsumer {
|
||||
final List<float[]> vertices = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public VertexConsumer addVertex(float x, float y, float z) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setColor(int red, int green, int blue, int alpha) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setColor(int color) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv(float u, float v) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv1(int u, int v) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv2(int u, int v) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv3(float u, float v) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setNormal(float x, float y, float z) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setLineWidth(float width) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addVertex(
|
||||
float x,
|
||||
float y,
|
||||
float z,
|
||||
int color,
|
||||
float u,
|
||||
float v,
|
||||
int overlay,
|
||||
int light,
|
||||
float nx,
|
||||
float ny,
|
||||
float nz) {
|
||||
vertices.add(new float[] {x, y, z, u, v, nx, ny, nz});
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
static void onTheRenderThread() {
|
||||
TestPlatform.install();
|
||||
// Once per test JVM: another test class may have made this thread the render thread already.
|
||||
if (!RenderSystem.isOnRenderThread()) {
|
||||
RenderSystem.initRenderThread();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("NullAway") // The quads' materials are only asked for their light emission.
|
||||
void placesTheGamesVertices() {
|
||||
BakedQuad.MaterialInfo plain = new BakedQuad.MaterialInfo(null, null, null, null, null, -1, null, 0);
|
||||
List<BakedQuad> quads = List.of(
|
||||
new BakedQuad(
|
||||
new Vector3f(0.1F, 0.2F, 0.3F),
|
||||
new Vector3f(0.9F, 0.2F, 0.3F),
|
||||
new Vector3f(0.9F, 0.8F, 0.3F),
|
||||
new Vector3f(0.1F, 0.8F, 0.3F),
|
||||
UVPair.pack(0.25F, 0.5F),
|
||||
UVPair.pack(0.5F, 0.5F),
|
||||
UVPair.pack(0.5F, 0.75F),
|
||||
UVPair.pack(0.25F, 0.75F),
|
||||
Direction.SOUTH,
|
||||
plain),
|
||||
new BakedQuad(
|
||||
new Vector3f(0.0F, 1.0F, 0.0F),
|
||||
new Vector3f(0.0F, 1.0F, 1.0F),
|
||||
new Vector3f(1.0F, 1.0F, 1.0F),
|
||||
new Vector3f(1.0F, 1.0F, 0.0F),
|
||||
UVPair.pack(0.0F, 0.0F),
|
||||
UVPair.pack(0.0F, 0.0625F),
|
||||
UVPair.pack(0.0625F, 0.0625F),
|
||||
UVPair.pack(0.0625F, 0.0F),
|
||||
Direction.UP,
|
||||
plain));
|
||||
PoseStack poses = new PoseStack();
|
||||
poses.translate(1.5F, -2.25F, 0.125F);
|
||||
poses.mulPose(new org.joml.Matrix4f().rotateXYZ(0.3F, 1.1F, -0.4F));
|
||||
poses.scale(0.7F, 1.3F, -0.9F);
|
||||
|
||||
Recorder game = new Recorder();
|
||||
QuadInstance instance = new QuadInstance();
|
||||
for (BakedQuad quad : quads) {
|
||||
game.putBakedQuad(poses.last(), quad, instance);
|
||||
}
|
||||
|
||||
ModelMesh mesh = Objects.requireNonNull(ModelMesh.ofQuads(quads, "test"));
|
||||
assertThat(mesh.quads()).isEqualTo(2);
|
||||
assertThat(mesh.rows()).isEqualTo(3);
|
||||
float[] rows = new float[12];
|
||||
mesh.writeRows(poses.last(), rows, 0);
|
||||
// As the rewritten shader reads them: the rows' 3x3 as columns is the transpose, whose
|
||||
// inverse is the inverse transpose of the pose.
|
||||
Matrix3f normalMatrix = new Matrix3f(
|
||||
rows[0], rows[4], rows[8], rows[1], rows[5], rows[9], rows[2], rows[6], rows[10])
|
||||
.transpose()
|
||||
.invert();
|
||||
|
||||
ByteBuffer data = Objects.requireNonNull(mesh.vertexData());
|
||||
int stride = ModelMesh.VERTEX.getVertexSize();
|
||||
for (int v = 0; v < game.vertices.size(); v++) {
|
||||
float[] expected = game.vertices.get(v);
|
||||
int at = v * stride;
|
||||
float lx = data.getFloat(at);
|
||||
float ly = data.getFloat(at + 4);
|
||||
float lz = data.getFloat(at + 8);
|
||||
float x = rows[0] * lx + rows[1] * ly + rows[2] * lz + rows[3];
|
||||
float y = rows[4] * lx + rows[5] * ly + rows[6] * lz + rows[7];
|
||||
float z = rows[8] * lx + rows[9] * ly + rows[10] * lz + rows[11];
|
||||
assertThat(new float[] {x, y, z})
|
||||
.as("vertex %d position", v)
|
||||
.containsExactly(new float[] {expected[0], expected[1], expected[2]}, within(1.0E-5F));
|
||||
assertThat(data.getFloat(at + 12)).as("vertex %d u", v).isEqualTo(expected[3]);
|
||||
assertThat(data.getFloat(at + 16)).as("vertex %d v", v).isEqualTo(expected[4]);
|
||||
Vector3f normal = new Vector3f(
|
||||
data.get(at + 20) / 127.0F, data.get(at + 21) / 127.0F, data.get(at + 22) / 127.0F)
|
||||
.mul(normalMatrix)
|
||||
.normalize();
|
||||
assertThat(new float[] {normal.x(), normal.y(), normal.z()})
|
||||
.as("vertex %d normal", v)
|
||||
.containsExactly(new float[] {expected[5], expected[6], expected[7]}, within(1.0E-4F));
|
||||
assertThat(data.getInt(at + 24)).as("vertex %d part", v).isZero();
|
||||
}
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package incari.client.render.entity;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.client.model.geom.builders.UVPair;
|
||||
import net.minecraft.client.resources.model.geometry.BakedQuad;
|
||||
import net.minecraft.core.Direction;
|
||||
import org.joml.Vector3f;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The one color an item drawn instanced gets ({@link ModelBatches#sharedTint},
|
||||
* {@link ModelBatches#itemColor}, ADR 0031): the color the game's {@code ItemFeatureRenderer} gives
|
||||
* each of its quads, for quads that share a tint index.
|
||||
*/
|
||||
class ItemTintTest {
|
||||
|
||||
@SuppressWarnings("NullAway") // Only the tint index is read.
|
||||
private static BakedQuad quad(int tintIndex) {
|
||||
BakedQuad.MaterialInfo material = new BakedQuad.MaterialInfo(null, null, null, null, null, tintIndex, null, 0);
|
||||
Vector3f corner = new Vector3f();
|
||||
long uv = UVPair.pack(0.0F, 0.0F);
|
||||
return new BakedQuad(corner, corner, corner, corner, uv, uv, uv, uv, Direction.UP, material);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedItemLayersShareTheirLayersIndex() {
|
||||
// The game's generated items give every quad of layer 0 the tint index 0.
|
||||
assertThat(ModelBatches.sharedTint(List.of(quad(0), quad(0), quad(0)))).isZero();
|
||||
assertThat(ModelBatches.sharedTint(List.of(quad(-1), quad(-1)))).isEqualTo(-1);
|
||||
assertThat(ModelBatches.sharedTint(List.of(quad(-2)))).isEqualTo(-1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void layersThatTintDifferentlyDontShare() {
|
||||
// A potion: its tinted liquid (0) and its untinted bottle (1).
|
||||
assertThat(ModelBatches.sharedTint(List.of(quad(0), quad(1)))).isEqualTo(Integer.MIN_VALUE);
|
||||
assertThat(ModelBatches.sharedTint(List.of(quad(-1), quad(0)))).isEqualTo(Integer.MIN_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void colorIsTheGamesLayerColor() {
|
||||
int green = 0xFF48B518;
|
||||
// An item with no tint source has no layer colors: its tinted quads draw white, as the game's.
|
||||
assertThat(ModelBatches.itemColor(new int[0], 0)).isEqualTo(-1);
|
||||
assertThat(ModelBatches.itemColor(new int[] {green}, 0)).isEqualTo(green);
|
||||
assertThat(ModelBatches.itemColor(new int[] {green}, 1)).isEqualTo(-1);
|
||||
assertThat(ModelBatches.itemColor(new int[] {green}, -1)).isEqualTo(-1);
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package incari.client.render.entity;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import incari.client.testing.TestPlatform;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import net.minecraft.client.model.geom.ModelPart;
|
||||
import net.minecraft.core.Direction;
|
||||
import org.joml.Vector3f;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* A baked model placed by its part rows lands where the game's own {@code ModelPart.render} puts
|
||||
* its vertices, with the same normals and texture coordinates, for a tree with rotations, a
|
||||
* non-uniform scale, a hidden part and a part that skips its own cubes.
|
||||
*/
|
||||
class ModelMeshTest {
|
||||
|
||||
/** What the game writes per vertex. */
|
||||
private record Written(float x, float y, float z, float u, float v, float nx, float ny, float nz) {}
|
||||
|
||||
/** Collects the game's vertices. */
|
||||
private static final class Capture implements VertexConsumer {
|
||||
final List<Written> vertices = new ArrayList<>();
|
||||
private float x;
|
||||
private float y;
|
||||
private float z;
|
||||
private float u;
|
||||
private float v;
|
||||
|
||||
@Override
|
||||
public VertexConsumer addVertex(float x, float y, float z) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setColor(int r, int g, int b, int a) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setColor(int color) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv(float u, float v) {
|
||||
this.u = u;
|
||||
this.v = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv1(int u, int v) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv2(int u, int v) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setUv3(float u, float v) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setNormal(float nx, float ny, float nz) {
|
||||
// The game sets the normal last: the vertex is complete.
|
||||
vertices.add(new Written(x, y, z, u, v, nx, ny, nz));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexConsumer setLineWidth(float width) {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
private static ModelPart.Cube cube(float minX, float minY, float minZ, float size, boolean mirror) {
|
||||
return new ModelPart.Cube(
|
||||
0,
|
||||
0,
|
||||
minX,
|
||||
minY,
|
||||
minZ,
|
||||
size,
|
||||
size,
|
||||
size,
|
||||
0.25F,
|
||||
0.25F,
|
||||
0.25F,
|
||||
mirror,
|
||||
64,
|
||||
64,
|
||||
EnumSet.allOf(Direction.class));
|
||||
}
|
||||
|
||||
private static ModelPart part(List<ModelPart.Cube> cubes, Map<String, ModelPart> children) {
|
||||
return new ModelPart(cubes, children);
|
||||
}
|
||||
|
||||
/** root → body (turned) → arm (scaled unevenly), head (hidden) → hat, leg (skips its cubes) → foot. */
|
||||
private static ModelPart model() {
|
||||
ModelPart hat = part(List.of(cube(-4, -10, -4, 8, false)), Map.of());
|
||||
ModelPart head = part(List.of(cube(-4, -8, -4, 8, false)), Map.of("hat", hat));
|
||||
head.visible = false;
|
||||
ModelPart arm = part(List.of(cube(-1, -2, -1, 4, true)), Map.of());
|
||||
arm.setPos(5, 2, 0);
|
||||
arm.xRot = 0.7F;
|
||||
arm.xScale = 1.5F;
|
||||
arm.yScale = 0.75F;
|
||||
ModelPart foot = part(List.of(cube(-2, 10, -2, 4, false)), Map.of());
|
||||
foot.zRot = -0.3F;
|
||||
ModelPart leg = part(List.of(cube(-2, 0, -2, 4, false)), Map.of("foot", foot));
|
||||
leg.setPos(2, 12, 0);
|
||||
leg.skipDraw = true;
|
||||
Map<String, ModelPart> bodyChildren = new LinkedHashMap<>();
|
||||
bodyChildren.put("arm", arm);
|
||||
bodyChildren.put("head", head);
|
||||
bodyChildren.put("leg", leg);
|
||||
ModelPart body = part(List.of(cube(-4, 0, -2, 8, false)), bodyChildren);
|
||||
body.setPos(0, 1, 0);
|
||||
body.setRotation(0.1F, 0.8F, -0.2F);
|
||||
return part(List.of(), Map.of("body", body));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRowsPlaceTheBakedVerticesWhereTheGameDraws() {
|
||||
TestPlatform.install();
|
||||
ModelPart root = model();
|
||||
PoseStack placed = new PoseStack();
|
||||
placed.translate(3.0F, -1.5F, 7.0F);
|
||||
placed.rotate(new org.joml.Quaternionf().rotationY(2.2F));
|
||||
placed.scale(-0.9375F, -0.9375F, 0.9375F);
|
||||
|
||||
Capture game = new Capture();
|
||||
root.render(placed, game, 0, 0);
|
||||
|
||||
ModelMesh mesh = ModelMesh.of(root, "test");
|
||||
assertThat(mesh).isNotNull();
|
||||
float[] rows = new float[mesh.rows() * 4];
|
||||
mesh.writeRows(placed.last(), rows, 0);
|
||||
ByteBuffer data = mesh.vertexData();
|
||||
assertThat(data).isNotNull();
|
||||
int stride = ModelMesh.VERTEX.getVertexSize();
|
||||
|
||||
List<Written> ours = new ArrayList<>();
|
||||
for (int vertex = 0; vertex < mesh.quads() * 4; vertex++) {
|
||||
int at = vertex * stride;
|
||||
int part = data.getInt(at + 24);
|
||||
int row = part * 12;
|
||||
float lx = data.getFloat(at);
|
||||
float ly = data.getFloat(at + 4);
|
||||
float lz = data.getFloat(at + 8);
|
||||
float[] p = new float[3];
|
||||
for (int r = 0; r < 3; r++) {
|
||||
p[r] = rows[row + r * 4] * lx
|
||||
+ rows[row + r * 4 + 1] * ly
|
||||
+ rows[row + r * 4 + 2] * lz
|
||||
+ rows[row + r * 4 + 3];
|
||||
}
|
||||
if (p[0] == 0 && p[1] == 0 && p[2] == 0 && rows[row] == 0 && rows[row + 5] == 0) {
|
||||
// A part the game doesn't draw: collapsed.
|
||||
continue;
|
||||
}
|
||||
// The normal as the shader turns it: the inverse transpose of the part's 3×3, normalized.
|
||||
org.joml.Matrix3f m = new org.joml.Matrix3f(
|
||||
rows[row],
|
||||
rows[row + 4],
|
||||
rows[row + 8],
|
||||
rows[row + 1],
|
||||
rows[row + 5],
|
||||
rows[row + 9],
|
||||
rows[row + 2],
|
||||
rows[row + 6],
|
||||
rows[row + 10]);
|
||||
Vector3f n =
|
||||
new Vector3f(data.get(at + 20) / 127.0F, data.get(at + 21) / 127.0F, data.get(at + 22) / 127.0F);
|
||||
m.invert().transpose().transform(n).normalize();
|
||||
ours.add(new Written(p[0], p[1], p[2], data.getFloat(at + 12), data.getFloat(at + 16), n.x, n.y, n.z));
|
||||
}
|
||||
|
||||
// Hidden: the head and the hat below it; skipped: the leg's own cube, not the foot's.
|
||||
assertThat(game.vertices).hasSize(3 * 6 * 4); // The body, the arm and the foot.
|
||||
assertThat(ours).hasSameSizeAs(game.vertices);
|
||||
for (int i = 0; i < ours.size(); i++) {
|
||||
Written expected = game.vertices.get(i);
|
||||
Written actual = ours.get(i);
|
||||
assertThat(actual.x()).isCloseTo(expected.x(), within(1e-5F));
|
||||
assertThat(actual.y()).isCloseTo(expected.y(), within(1e-5F));
|
||||
assertThat(actual.z()).isCloseTo(expected.z(), within(1e-5F));
|
||||
assertThat(actual.u()).isEqualTo(expected.u());
|
||||
assertThat(actual.v()).isEqualTo(expected.v());
|
||||
assertThat(actual.nx()).isCloseTo(expected.nx(), within(1e-4F));
|
||||
assertThat(actual.ny()).isCloseTo(expected.ny(), within(1e-4F));
|
||||
assertThat(actual.nz()).isCloseTo(expected.nz(), within(1e-4F));
|
||||
}
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package incari.client.resources;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import com.google.common.hash.HashCode;
|
||||
import com.google.common.hash.HashFunction;
|
||||
import com.google.common.hash.Hashing;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.OptionalLong;
|
||||
import net.minecraft.util.HttpUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
@SuppressWarnings("deprecation") // SHA-1 is what the protocol names packs by
|
||||
class PackDownloadsTest {
|
||||
|
||||
private static final HashFunction SHA1 = Hashing.sha1();
|
||||
private static final byte[] PACK = "a pack".getBytes(StandardCharsets.UTF_8);
|
||||
private static final HashCode PACK_HASH = SHA1.hashBytes(PACK);
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
private final List<String> fetched = new ArrayList<>();
|
||||
private final Progress progress = new Progress();
|
||||
|
||||
private PackDownloads.Fetch serving(String url, byte[] body) {
|
||||
return (asked, maxBytes) -> {
|
||||
fetched.add(asked);
|
||||
if (!asked.equals(url)) {
|
||||
throw new IOException("blocked");
|
||||
}
|
||||
return body;
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsTheFetchedPackUnderItsHash() throws IOException {
|
||||
Path file = PackDownloads.download(
|
||||
dir,
|
||||
"https://example.com/p.zip",
|
||||
SHA1,
|
||||
PACK_HASH,
|
||||
100,
|
||||
progress,
|
||||
serving("https://example.com/p.zip", PACK));
|
||||
|
||||
assertThat(file).isEqualTo(dir.resolve(PACK_HASH.toString()));
|
||||
assertThat(Files.readAllBytes(file)).isEqualTo(PACK);
|
||||
assertThat(progress.events).containsExactly("start", "download", "bytes " + PACK.length, "finished true");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reusesAKeptPackWithoutFetching() throws IOException {
|
||||
Files.write(dir.resolve(PACK_HASH.toString()), PACK);
|
||||
|
||||
Path file = PackDownloads.download(
|
||||
dir, "https://example.com/p.zip", SHA1, PACK_HASH, 100, progress, serving("nowhere", PACK));
|
||||
|
||||
assertThat(file).isEqualTo(dir.resolve(PACK_HASH.toString()));
|
||||
assertThat(fetched).isEmpty();
|
||||
assertThat(progress.events).containsExactly("start", "finished true");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchesAgainOverAKeptFileThatIsntThePack() throws IOException {
|
||||
Files.write(dir.resolve(PACK_HASH.toString()), "damaged".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Path file = PackDownloads.download(
|
||||
dir,
|
||||
"https://example.com/p.zip",
|
||||
SHA1,
|
||||
PACK_HASH,
|
||||
100,
|
||||
progress,
|
||||
serving("https://example.com/p.zip", PACK));
|
||||
|
||||
assertThat(Files.readAllBytes(file)).isEqualTo(PACK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesAPackWhoseHashIsntTheOneTheServerNamed() {
|
||||
byte[] other = "another pack".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
assertThatThrownBy(() -> PackDownloads.download(
|
||||
dir,
|
||||
"https://example.com/p.zip",
|
||||
SHA1,
|
||||
PACK_HASH,
|
||||
100,
|
||||
progress,
|
||||
serving("https://example.com/p.zip", other)))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasRootCauseMessage(
|
||||
"Its hash is " + SHA1.hashBytes(other) + ", not the " + PACK_HASH + " the server named");
|
||||
assertThat(progress.events).last().isEqualTo("finished false");
|
||||
}
|
||||
|
||||
@Test
|
||||
void namesAPackWithNoHashGivenByItsOwn() throws IOException {
|
||||
Path file = PackDownloads.download(
|
||||
dir,
|
||||
"https://example.com/p.zip",
|
||||
SHA1,
|
||||
null,
|
||||
100,
|
||||
progress,
|
||||
serving("https://example.com/p.zip", PACK));
|
||||
|
||||
assertThat(file).isEqualTo(dir.resolve(PACK_HASH.toString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void triesAnHttpPackOverHttpsWhenHttpFails() throws IOException {
|
||||
byte[] body = PackDownloads.fetchEitherScheme(
|
||||
"http://example.com/p.zip", 100, serving("https://example.com/p.zip", PACK));
|
||||
|
||||
assertThat(body).isEqualTo(PACK);
|
||||
assertThat(fetched).containsExactly("http://example.com/p.zip", "https://example.com/p.zip");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsTheFirstFailureWhenBothSchemesFail() {
|
||||
assertThatThrownBy(() ->
|
||||
PackDownloads.fetchEitherScheme("http://example.com/p.zip", 100, serving("nowhere", PACK)))
|
||||
.isInstanceOf(IOException.class)
|
||||
.hasMessage("blocked")
|
||||
.satisfies(e -> assertThat(e.getSuppressed()).hasSize(1));
|
||||
assertThat(fetched).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void triesAnHttpsPackOnce() {
|
||||
assertThatThrownBy(() ->
|
||||
PackDownloads.fetchEitherScheme("https://example.com/p.zip", 100, serving("nowhere", PACK)))
|
||||
.isInstanceOf(IOException.class);
|
||||
assertThat(fetched).containsExactly("https://example.com/p.zip");
|
||||
}
|
||||
|
||||
private static final class Progress implements HttpUtil.DownloadProgressListener {
|
||||
final List<String> events = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void requestStart() {
|
||||
events.add("start");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void downloadStart(OptionalLong sizeBytes) {
|
||||
events.add("download");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void downloadedBytes(long bytesSoFar) {
|
||||
events.add("bytes " + bytesSoFar);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void requestFinished(boolean success) {
|
||||
events.add("finished " + success);
|
||||
}
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package incari.client.resources;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import net.minecraft.client.resources.language.LanguageManager;
|
||||
import net.minecraft.server.packs.resources.PreparableReloadListener;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class RemoteAssetsTest {
|
||||
|
||||
private static final PreparableReloadListener OTHER =
|
||||
(state, background, barrier, main) -> CompletableFuture.completedFuture(null);
|
||||
|
||||
/** Runs what it's given when asked to, as the background pool does between frames. */
|
||||
private static final class Queue implements Executor {
|
||||
final List<Runnable> tasks = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void execute(Runnable task) {
|
||||
tasks.add(task);
|
||||
}
|
||||
|
||||
void runAll() {
|
||||
while (!tasks.isEmpty()) {
|
||||
tasks.removeFirst().run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeSource() {
|
||||
RemoteAssets.install(null);
|
||||
}
|
||||
|
||||
@SuppressWarnings("NullAway") // The language manager only keeps the game to show an error screen.
|
||||
private static LanguageManager languages(String selected) {
|
||||
return new LanguageManager(null, selected, locale -> {});
|
||||
}
|
||||
|
||||
@Test
|
||||
void englishIsInTheJar() {
|
||||
assertThat(RemoteAssets.assetsFor("en_us")).containsExactly(RemoteAssets.FONT);
|
||||
assertThat(RemoteAssets.assetsFor("de_de")).containsExactly(RemoteAssets.FONT, "minecraft/lang/de_de.json");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReloadOfTheGamesResourcesFetchesInTheBackgroundAndHoldsBackItsReaders() {
|
||||
List<List<String>> fetched = new ArrayList<>();
|
||||
RemoteAssets.install(fetched::add);
|
||||
Queue background = new Queue();
|
||||
LanguageManager languages = languages("fr_fr");
|
||||
|
||||
List<PreparableReloadListener> gated = RemoteAssets.gate(List.of(OTHER, languages), background);
|
||||
assertThat(gated.get(0)).isSameAs(OTHER);
|
||||
assertThat(gated.get(1)).isInstanceOf(RemoteAssets.Gated.class);
|
||||
assertThat(gated.get(1).getName()).isEqualTo(languages.getName());
|
||||
assertThat(fetched).isEmpty();
|
||||
|
||||
background.runAll();
|
||||
assertThat(fetched).containsExactly(RemoteAssets.assetsFor("fr_fr"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGatedListenerReloadsOnTheGamesThreadOnceTheFetchIsDone() {
|
||||
List<String> calls = new ArrayList<>();
|
||||
PreparableReloadListener listener = (state, background, barrier, main) -> {
|
||||
calls.add("reload");
|
||||
return CompletableFuture.completedFuture(null);
|
||||
};
|
||||
CompletableFuture<Void> fetch = new CompletableFuture<>();
|
||||
Queue main = new Queue();
|
||||
|
||||
CompletableFuture<Void> done = new RemoteAssets.Gated(listener, fetch).reload(null, Runnable::run, null, main);
|
||||
assertThat(calls).isEmpty();
|
||||
fetch.complete(null);
|
||||
assertThat(calls).isEmpty();
|
||||
main.runAll();
|
||||
assertThat(calls).containsExactly("reload");
|
||||
assertThat(done).isDone();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedFetchLeavesTheReloadToGoOn() {
|
||||
CompletableFuture<Void> fetched = RemoteAssets.fetch(
|
||||
assets -> {
|
||||
throw new IOException("offline");
|
||||
},
|
||||
List.of(RemoteAssets.FONT),
|
||||
Runnable::run);
|
||||
assertThat(fetched).isCompleted().isNotCompletedExceptionally();
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherReloadsAndTheDesktopAreLeftAlone() {
|
||||
List<PreparableReloadListener> withLanguages = List.of(languages("de_de"));
|
||||
assertThat(RemoteAssets.gate(withLanguages, Runnable::run)).isSameAs(withLanguages);
|
||||
RemoteAssets.install(assets -> {});
|
||||
List<PreparableReloadListener> others = List.of(OTHER);
|
||||
assertThat(RemoteAssets.gate(others, Runnable::run)).isSameAs(others);
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package incari.client.singleplayer;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.platform.api.net.NetConnection;
|
||||
import incari.platform.api.threads.PlatformChannel;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ChannelLinkTest {
|
||||
|
||||
/** A channel that records what it's asked to send. */
|
||||
private static final class Recorded implements PlatformChannel {
|
||||
final List<Integer> kinds = new ArrayList<>();
|
||||
final List<byte[]> messages = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void send(int kind, byte[] bytes, int offset, int length) {
|
||||
kinds.add(kind);
|
||||
messages.add(java.util.Arrays.copyOfRange(bytes, offset, offset + length));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Message receive() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Message poll() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {}
|
||||
}
|
||||
|
||||
/** What the game's channel hears. */
|
||||
private static final class Heard implements NetConnection.Listener {
|
||||
final List<String> events = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void connected() {
|
||||
events.add("connected");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void received(ByteBuffer data) {
|
||||
events.add("packet " + data.get(0));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closed(@Nullable Throwable cause) {
|
||||
events.add("closed");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void packetsBeforeTheChannelOpensAreKeptForIt() {
|
||||
ChannelLink link = new ChannelLink(new Recorded(), 2, 6);
|
||||
link.deliver(new byte[] {1});
|
||||
link.deliver(new byte[] {2});
|
||||
Heard heard = new Heard();
|
||||
|
||||
link.open(heard);
|
||||
link.deliver(new byte[] {3});
|
||||
|
||||
assertThat(heard.events).containsExactly("connected", "packet 1", "packet 2", "packet 3");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCloseBeforeTheChannelOpensComesAfterThePackets() {
|
||||
ChannelLink link = new ChannelLink(new Recorded(), 2, 6);
|
||||
link.deliver(new byte[] {1});
|
||||
link.closedByOtherEnd();
|
||||
Heard heard = new Heard();
|
||||
|
||||
link.open(heard);
|
||||
|
||||
assertThat(heard.events).containsExactly("connected", "packet 1", "closed");
|
||||
assertThat(link.isOpen()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFlushsSendsGoOutAsOneMessageOfItsKind() {
|
||||
Recorded channel = new Recorded();
|
||||
ChannelLink link = new ChannelLink(channel, 2, 6);
|
||||
link.open(new Heard());
|
||||
|
||||
link.send(ByteBuffer.wrap(new byte[] {1, 2}));
|
||||
link.send(ByteBuffer.wrap(new byte[] {3}));
|
||||
assertThat(channel.kinds).isEmpty();
|
||||
link.flush();
|
||||
link.flush();
|
||||
link.send(ByteBuffer.wrap(new byte[40_000]));
|
||||
link.flush();
|
||||
|
||||
assertThat(channel.kinds).containsExactly(2, 2);
|
||||
assertThat(channel.messages.get(0)).containsExactly(1, 2, 3);
|
||||
assertThat(channel.messages.get(1)).hasSize(40_000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingSendsWhatWasntFlushedThenTellsTheOtherEnd() {
|
||||
Recorded channel = new Recorded();
|
||||
ChannelLink link = new ChannelLink(channel, 2, 6);
|
||||
link.open(new Heard());
|
||||
|
||||
link.send(ByteBuffer.wrap(new byte[] {9}));
|
||||
link.close();
|
||||
link.send(ByteBuffer.wrap(new byte[] {9}));
|
||||
link.flush();
|
||||
|
||||
assertThat(channel.kinds).containsExactly(2, 6);
|
||||
assertThat(channel.messages.get(0)).containsExactly(9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package incari.client.skins;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class OwnSkinTest {
|
||||
|
||||
@Test
|
||||
void listsEveryDefaultSkinInBothModelsOnce() {
|
||||
assertThat(OwnSkin.defaultChoices()).hasSize(18);
|
||||
assertThat(OwnSkin.defaultChoices()).extracting(OwnSkin.Choice::key).doesNotHaveDuplicates();
|
||||
assertThat(OwnSkin.defaultChoices())
|
||||
.extracting(OwnSkin.Choice::label)
|
||||
.startsWith("Steve", "Alex", "Ari", "Ari (Slim)")
|
||||
.endsWith("Steve (Slim)", "Alex (Wide)");
|
||||
assertThat(OwnSkin.defaultChoices()).noneMatch(OwnSkin.Choice::custom);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsTheModelFromTheWideArmsColumns() {
|
||||
int[] wide = new int[64 * 64];
|
||||
Arrays.fill(wide, 0xFF336699);
|
||||
assertThat(OwnSkin.looksSlim(wide)).isFalse();
|
||||
|
||||
int[] slim = wide.clone();
|
||||
for (int y = 20; y < 32; y++) {
|
||||
slim[y * 64 + 54] = 0;
|
||||
slim[y * 64 + 55] = 0;
|
||||
}
|
||||
assertThat(OwnSkin.looksSlim(slim)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void namesAnAddedSkinAfterItsFile() {
|
||||
assertThat(OwnSkin.fileBase("My Skin.PNG")).isEqualTo("My Skin");
|
||||
assertThat(OwnSkin.fileBase("a/b?.png")).isEqualTo("a_b_");
|
||||
assertThat(OwnSkin.fileBase(".png")).isEqualTo("skin");
|
||||
assertThat(OwnSkin.fileBase("x".repeat(40) + ".png")).hasSize(32);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package incari.client.skins;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.mojang.authlib.SignatureState;
|
||||
import com.mojang.authlib.minecraft.MinecraftProfileTextures;
|
||||
import com.mojang.authlib.properties.Property;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ProfileTexturesTest {
|
||||
|
||||
private static Property textures(String json, String signature) {
|
||||
String value = Base64.getEncoder().encodeToString(json.getBytes(StandardCharsets.UTF_8));
|
||||
return signature == null ? new Property("textures", value) : new Property("textures", value, signature);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsASignedSkinAndCapeFromMojang() {
|
||||
MinecraftProfileTextures read = ProfileTextures.read(textures("""
|
||||
{"textures":{
|
||||
"SKIN":{"url":"http://textures.minecraft.net/texture/abc","metadata":{"model":"slim"}},
|
||||
"CAPE":{"url":"https://textures.minecraft.net/texture/def"}}}
|
||||
""", "sig"));
|
||||
|
||||
assertThat(read.skin().getUrl()).isEqualTo("http://textures.minecraft.net/texture/abc");
|
||||
assertThat(read.skin().getMetadata("model")).isEqualTo("slim");
|
||||
assertThat(read.cape().getUrl()).isEqualTo("https://textures.minecraft.net/texture/def");
|
||||
assertThat(read.elytra()).isNull();
|
||||
assertThat(read.signatureState()).isEqualTo(SignatureState.SIGNED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsignedPropertyStaysUnsigned() {
|
||||
MinecraftProfileTextures read = ProfileTextures.read(
|
||||
textures("{\"textures\":{\"SKIN\":{\"url\":\"https://textures.minecraft.net/texture/abc\"}}}", null));
|
||||
|
||||
assertThat(read.skin()).isNotNull();
|
||||
assertThat(read.signatureState()).isEqualTo(SignatureState.UNSIGNED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTextureFromAnyOtherHostDropsThemAll() {
|
||||
MinecraftProfileTextures read = ProfileTextures.read(textures("""
|
||||
{"textures":{
|
||||
"SKIN":{"url":"https://textures.minecraft.net/texture/abc"},
|
||||
"CAPE":{"url":"https://evil.example/minecraft.net/cape.png"}}}
|
||||
""", "sig"));
|
||||
|
||||
assertThat(read).isEqualTo(MinecraftProfileTextures.EMPTY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void badDataGivesNoTextures() {
|
||||
assertThat(ProfileTextures.read(new Property("textures", "not base64!")))
|
||||
.isEqualTo(MinecraftProfileTextures.EMPTY);
|
||||
assertThat(ProfileTextures.read(textures("[1,2]", null))).isEqualTo(MinecraftProfileTextures.EMPTY);
|
||||
assertThat(ProfileTextures.read(textures("{\"textures\":{}}", null)).skin())
|
||||
.isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyMojangsDomainsOverHttp() {
|
||||
assertThat(ProfileTextures.fromMojang("https://textures.minecraft.net/texture/abc"))
|
||||
.isTrue();
|
||||
assertThat(ProfileTextures.fromMojang("HTTP://Textures.Minecraft.NET/texture/abc"))
|
||||
.isTrue();
|
||||
assertThat(ProfileTextures.fromMojang("https://minecraft.net.evil.example/a"))
|
||||
.isFalse();
|
||||
assertThat(ProfileTextures.fromMojang("https://evilminecraft.net/a")).isFalse();
|
||||
assertThat(ProfileTextures.fromMojang("file://textures.minecraft.net/a"))
|
||||
.isFalse();
|
||||
assertThat(ProfileTextures.fromMojang("not a url")).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package incari.client.skins;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SkinDownloadsTest {
|
||||
|
||||
@Test
|
||||
void fetchesMojangsHttpTextureUrlsOverHttps() {
|
||||
assertThat(SkinDownloads.secure("http://textures.minecraft.net/texture/abc"))
|
||||
.isEqualTo("https://textures.minecraft.net/texture/abc");
|
||||
assertThat(SkinDownloads.secure("HTTP://textures.minecraft.net/texture/abc"))
|
||||
.isEqualTo("https://textures.minecraft.net/texture/abc");
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesHttpsUrlsAlone() {
|
||||
assertThat(SkinDownloads.secure("https://textures.minecraft.net/texture/abc"))
|
||||
.isEqualTo("https://textures.minecraft.net/texture/abc");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package incari.client.testing;
|
||||
|
||||
import incari.platform.api.Platform;
|
||||
import incari.platform.api.Platforms;
|
||||
import incari.platform.api.threads.PlatformThreads;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
/**
|
||||
* Enough of a platform for game classes to load in tests: building a {@code VertexFormat} runs
|
||||
* {@code Mth}'s static initializer, which reaches {@code Util}'s, which asks the platform how many
|
||||
* background threads to make. Anything else the game asks for fails the test loudly.
|
||||
*/
|
||||
public final class TestPlatform {
|
||||
|
||||
private TestPlatform() {}
|
||||
|
||||
public static void install() {
|
||||
if (Platforms.isInstalled()) {
|
||||
return;
|
||||
}
|
||||
PlatformThreads inline = suggested -> 0;
|
||||
Platforms.install((Platform) Proxy.newProxyInstance(
|
||||
Platform.class.getClassLoader(),
|
||||
new Class<?>[] {Platform.class},
|
||||
(proxy, method, args) -> switch (method.getName()) {
|
||||
case "threads" -> inline;
|
||||
case "description" -> "client tests";
|
||||
case "nanoTime" -> System.nanoTime();
|
||||
case "toString" -> "TestPlatform";
|
||||
default -> throw new UnsupportedOperationException(method.getName());
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package incari.client.testing;
|
||||
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.WorldLoader;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.world.level.WorldDataConfiguration;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The vanilla data pack's registries with their tags, loaded as a server loads a world's: for tests
|
||||
* that need the game's own biomes, noise and structures. Loaded once per test run (a few seconds).
|
||||
*/
|
||||
public final class VanillaRegistries {
|
||||
|
||||
private static RegistryAccess.@Nullable Frozen loaded;
|
||||
|
||||
private VanillaRegistries() {}
|
||||
|
||||
/** Bootstraps the game (with {@link TestPlatform}) and returns the registries. */
|
||||
public static synchronized RegistryAccess.Frozen load() {
|
||||
RegistryAccess.Frozen registries = loaded;
|
||||
if (registries != null) {
|
||||
return registries;
|
||||
}
|
||||
TestPlatform.install();
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
WorldLoader.InitConfig config = new WorldLoader.InitConfig(
|
||||
new WorldLoader.PackConfig(
|
||||
ServerPacksSource.createVanillaTrustedRepository(),
|
||||
WorldDataConfiguration.DEFAULT,
|
||||
false,
|
||||
true),
|
||||
Commands.CommandSelection.DEDICATED,
|
||||
LevelBasedPermissionSet.OWNER);
|
||||
registries = WorldLoader.<RegistryAccess.Frozen, RegistryAccess.Frozen>load(
|
||||
config,
|
||||
context -> new WorldLoader.DataLoadOutput<>(
|
||||
context.datapackDimensions(), context.datapackDimensions()),
|
||||
(resources, managers, layers, cookie) -> layers.compositeAccess(),
|
||||
Util.backgroundExecutor(),
|
||||
Runnable::run)
|
||||
.join();
|
||||
loaded = registries;
|
||||
return registries;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package incari.client.ui;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class UiAtlasShelvesTest {
|
||||
|
||||
@Test
|
||||
void placesAlongAShelfThenStartsTheNextBelowItsTallest() {
|
||||
UiAtlas.Shelves shelves = new UiAtlas.Shelves(16);
|
||||
long a = shelves.place(6, 4);
|
||||
long b = shelves.place(6, 7);
|
||||
long c = shelves.place(6, 2);
|
||||
assertThat(UiAtlas.Shelves.x(a)).isZero();
|
||||
assertThat(UiAtlas.Shelves.y(a)).isZero();
|
||||
assertThat(UiAtlas.Shelves.x(b)).isEqualTo(6);
|
||||
assertThat(UiAtlas.Shelves.y(b)).isZero();
|
||||
// No room left on the first shelf: the second starts below its tallest image, 7.
|
||||
assertThat(UiAtlas.Shelves.x(c)).isZero();
|
||||
assertThat(UiAtlas.Shelves.y(c)).isEqualTo(7);
|
||||
}
|
||||
|
||||
@Test
|
||||
void saysWhenThePageIsFullAndKeepsWhatItHad() {
|
||||
UiAtlas.Shelves shelves = new UiAtlas.Shelves(16);
|
||||
assertThat(shelves.place(16, 10)).isNotEqualTo(UiAtlas.Shelves.FULL);
|
||||
assertThat(shelves.place(4, 7)).isEqualTo(UiAtlas.Shelves.FULL);
|
||||
// A smaller image still fits in what's left.
|
||||
long small = shelves.place(4, 6);
|
||||
assertThat(UiAtlas.Shelves.y(small)).isEqualTo(10);
|
||||
assertThat(shelves.place(17, 1)).isEqualTo(UiAtlas.Shelves.FULL);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package incari.client.world;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.testing.VanillaRegistries;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeManager;
|
||||
import net.minecraft.world.level.biome.BiomeResolver;
|
||||
import net.minecraft.world.level.biome.Biomes;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
/**
|
||||
* Every block's biome from {@link BiomeCells} is the game's blurred one, over biome cells laid out
|
||||
* in large patches with single odd cells among them, for whole chunks and their surroundings.
|
||||
*/
|
||||
class BiomeCellsTest {
|
||||
|
||||
private static List<Holder<Biome>> biomes;
|
||||
|
||||
@BeforeAll
|
||||
static void bootstrap() {
|
||||
Registry<Biome> registry = VanillaRegistries.load().lookupOrThrow(Registries.BIOME);
|
||||
biomes = List.of(
|
||||
registry.getOrThrow(Biomes.PLAINS),
|
||||
registry.getOrThrow(Biomes.FOREST),
|
||||
registry.getOrThrow(Biomes.DESERT),
|
||||
registry.getOrThrow(Biomes.OCEAN),
|
||||
registry.getOrThrow(Biomes.DRIPSTONE_CAVES));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void off() {
|
||||
BiomeCells.setEnabled(false);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(longs = {20260928L, -4172144997902289642L})
|
||||
void everyBlocksBiomeIsTheGames(long seed) {
|
||||
// Patches of 8x4x8 cells, with a twentieth of the cells something else.
|
||||
BiomeResolver cells = (x, y, z) -> {
|
||||
int odd = Math.floorMod((x * 73_856_093) ^ (y * 19_349_663) ^ (z * 83_492_791), 20);
|
||||
int patch = Math.floorMod((x >> 3) * 31 + (y >> 2) * 17 + (z >> 3) * 7, biomes.size());
|
||||
return biomes.get(odd == 0 ? (patch + 1) % biomes.size() : patch);
|
||||
};
|
||||
BiomeManager manager = new BiomeManager(cells, BiomeManager.obfuscateSeed(seed));
|
||||
|
||||
BiomeCells.setEnabled(true);
|
||||
BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
|
||||
for (int chunkX = -2; chunkX <= 2; chunkX++) {
|
||||
for (int chunkZ = -2; chunkZ <= 2; chunkZ++) {
|
||||
int minX = chunkX * 16;
|
||||
int minZ = chunkZ * 16;
|
||||
Function<BlockPos, Holder<Biome>> lookup = BiomeCells.forChunk(manager, minX, -64, minZ, 319);
|
||||
assertThat(lookup).isInstanceOf(BiomeCells.class);
|
||||
// The chunk and two blocks around it, which fall outside its groups.
|
||||
for (int y = 330; y >= -70; y--) {
|
||||
for (int x = minX - 2; x < minX + 18; x++) {
|
||||
for (int z = minZ - 2; z < minZ + 18; z++) {
|
||||
pos.set(x, y, z);
|
||||
assertThat(lookup.apply(pos)).as("%s", pos).isSameAs(manager.getBiome(pos));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package incari.client.world;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import incari.client.testing.TestPlatform;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.NbtOps;
|
||||
import net.minecraft.world.level.biome.BiomeSpecialEffects;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Biome colours sent as plain ints decode opaque. Old servers' biomes (ViaVersion's registry, and
|
||||
* vanilla servers up to 1.21) send {@code water_color} and the others as ints with no alpha byte; read
|
||||
* as they are, water, grass and leaves drew with alpha 0 when biome blend was off.
|
||||
*/
|
||||
class BiomeColorAlphaTest {
|
||||
|
||||
@BeforeAll
|
||||
static void platform() {
|
||||
TestPlatform.install();
|
||||
}
|
||||
|
||||
@Test
|
||||
void intColorsFromOldServersAreOpaque() {
|
||||
CompoundTag effects = new CompoundTag();
|
||||
effects.putInt("water_color", 0x3F76E4);
|
||||
effects.putInt("grass_color", 0x6A7039);
|
||||
effects.putInt("foliage_color", 0x6A7039);
|
||||
effects.putInt("dry_foliage_color", 0x7B5334);
|
||||
|
||||
BiomeSpecialEffects decoded =
|
||||
BiomeSpecialEffects.CODEC.parse(NbtOps.INSTANCE, effects).getOrThrow();
|
||||
|
||||
assertThat(decoded.waterColor()).isEqualTo(0xFF3F76E4);
|
||||
assertThat(decoded.grassColorOverride()).contains(0xFF6A7039);
|
||||
assertThat(decoded.foliageColorOverride()).contains(0xFF6A7039);
|
||||
assertThat(decoded.dryFoliageColorOverride()).contains(0xFF7B5334);
|
||||
}
|
||||
|
||||
@Test
|
||||
void hexColorsDecodeAsBefore() {
|
||||
var json = JsonParser.parseString("{\"water_color\":\"#3f76e4\",\"grass_color\":\"#6a7039\"}");
|
||||
|
||||
BiomeSpecialEffects decoded =
|
||||
BiomeSpecialEffects.CODEC.parse(JsonOps.INSTANCE, json).getOrThrow();
|
||||
|
||||
assertThat(decoded.waterColor()).isEqualTo(0xFF3F76E4);
|
||||
assertThat(decoded.grassColorOverride()).contains(0xFF6A7039);
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodingStillWritesHex() {
|
||||
var decoded =
|
||||
BiomeSpecialEffects.CODEC.parse(NbtOps.INSTANCE, waterOnly()).getOrThrow();
|
||||
|
||||
var encoded =
|
||||
BiomeSpecialEffects.CODEC.encodeStart(JsonOps.INSTANCE, decoded).getOrThrow();
|
||||
|
||||
assertThat(encoded.getAsJsonObject().get("water_color").getAsString()).isEqualToIgnoringCase("#3f76e4");
|
||||
}
|
||||
|
||||
private static CompoundTag waterOnly() {
|
||||
CompoundTag effects = new CompoundTag();
|
||||
effects.putInt("water_color", 0x3F76E4);
|
||||
return effects;
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package incari.client.world;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Random;
|
||||
import java.util.zip.InflaterInputStream;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** {@link ChunkCompression}'s streams inflate back to what was written, the fast one or the game's. */
|
||||
class ChunkCompressionTest {
|
||||
|
||||
@AfterEach
|
||||
void off() {
|
||||
ChunkCompression.setEnabled(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void bothLevelsInflateToTheSameBytes() throws IOException {
|
||||
byte[] chunk = chunkLike();
|
||||
ChunkCompression.setEnabled(false);
|
||||
byte[] game = deflate(chunk);
|
||||
ChunkCompression.setEnabled(true);
|
||||
byte[] fast = deflate(chunk);
|
||||
|
||||
assertThat(inflate(game)).isEqualTo(chunk);
|
||||
assertThat(inflate(fast)).isEqualTo(chunk);
|
||||
// The fast stream really is another level: zlib's header says which (FLEVEL, RFC 1950).
|
||||
assertThat(game[1] & 0xC0).isEqualTo(0x80);
|
||||
assertThat(fast[1] & 0xC0).isEqualTo(0x00);
|
||||
}
|
||||
|
||||
/** Runs of repeated block ids with some noise in them, as a chunk's palette data looks. */
|
||||
private static byte[] chunkLike() {
|
||||
Random random = new Random(26_3);
|
||||
byte[] bytes = new byte[64 * 1024];
|
||||
int i = 0;
|
||||
while (i < bytes.length) {
|
||||
byte value = (byte) random.nextInt(12);
|
||||
int run = 1 + random.nextInt(200);
|
||||
for (int j = 0; j < run && i < bytes.length; j++) {
|
||||
bytes[i++] = random.nextInt(20) == 0 ? (byte) random.nextInt() : value;
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static byte[] deflate(byte[] bytes) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (OutputStream stream = ChunkCompression.deflate(out)) {
|
||||
stream.write(bytes);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] inflate(byte[] bytes) throws IOException {
|
||||
try (InflaterInputStream in = new InflaterInputStream(new ByteArrayInputStream(bytes))) {
|
||||
return in.readAllBytes();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package incari.client.world;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Map;
|
||||
import net.minecraft.world.entity.ai.goal.Goal;
|
||||
import net.minecraft.world.entity.ai.goal.WrappedGoal;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** {@link GoalFlags} answers as the game's flag loops do, for every set of flags a goal can hold. */
|
||||
@SuppressWarnings("EnumOrdinal") // As GoalFlags numbers flags.
|
||||
class GoalFlagsTest {
|
||||
|
||||
private static final Goal.Flag[] FLAGS = Goal.Flag.values();
|
||||
|
||||
@AfterEach
|
||||
void off() {
|
||||
GoalFlags.setEnabled(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void masksAnswerAsTheFlagSetsDo() {
|
||||
int sets = 1 << FLAGS.length;
|
||||
WrappedGoal noGoal = new WrappedGoal(Integer.MAX_VALUE, goal(EnumSet.noneOf(Goal.Flag.class), true));
|
||||
long compared = 0;
|
||||
for (int held = 0; held < sets; held++) {
|
||||
for (int priority : new int[] {0, 3, Integer.MAX_VALUE}) {
|
||||
WrappedGoal goal = new WrappedGoal(priority, goal(flags(held), true));
|
||||
for (int disabled = 0; disabled < sets; disabled++) {
|
||||
EnumSet<Goal.Flag> disabledSet = flags(disabled);
|
||||
for (int lockedBy = 0; lockedBy < sets; lockedBy++) {
|
||||
Map<Goal.Flag, WrappedGoal> locked = new EnumMap<>(Goal.Flag.class);
|
||||
for (Goal.Flag flag : flags(lockedBy)) {
|
||||
// Holders that may and may not be replaced, by priority and interruptibility.
|
||||
locked.put(
|
||||
flag,
|
||||
new WrappedGoal(
|
||||
flag.ordinal() * 2, goal(EnumSet.of(flag), flag.ordinal() % 2 == 0)));
|
||||
}
|
||||
GoalFlags.setEnabled(false);
|
||||
boolean gameContains = GoalFlags.containsAny(goal, disabledSet, disabled);
|
||||
boolean gameReplaces = GoalFlags.canReplaceAll(goal, locked, noGoal);
|
||||
GoalFlags.setEnabled(true);
|
||||
assertThat(GoalFlags.containsAny(goal, disabledSet, GoalFlags.mask(disabledSet)))
|
||||
.isEqualTo(gameContains);
|
||||
assertThat(GoalFlags.canReplaceAll(goal, locked, noGoal))
|
||||
.isEqualTo(gameReplaces);
|
||||
compared++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assertThat(compared).isEqualTo(3L * sets * sets * sets);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGoalsMaskFollowsItsFlags() {
|
||||
Goal goal = goal(EnumSet.of(Goal.Flag.MOVE, Goal.Flag.LOOK), true);
|
||||
assertThat(goal.incariFlagMask()).isEqualTo(GoalFlags.mask(EnumSet.of(Goal.Flag.MOVE, Goal.Flag.LOOK)));
|
||||
goal.setFlags(EnumSet.of(Goal.Flag.JUMP));
|
||||
assertThat(goal.incariFlagMask()).isEqualTo(1 << Goal.Flag.JUMP.ordinal());
|
||||
}
|
||||
|
||||
private static EnumSet<Goal.Flag> flags(int mask) {
|
||||
EnumSet<Goal.Flag> set = EnumSet.noneOf(Goal.Flag.class);
|
||||
for (Goal.Flag flag : FLAGS) {
|
||||
if ((mask & 1 << flag.ordinal()) != 0) {
|
||||
set.add(flag);
|
||||
}
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
private static Goal goal(EnumSet<Goal.Flag> flags, boolean interruptable) {
|
||||
Goal goal = new Goal() {
|
||||
@Override
|
||||
public boolean canUse() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInterruptable() {
|
||||
return interruptable;
|
||||
}
|
||||
};
|
||||
goal.setFlags(flags);
|
||||
return goal;
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package incari.client.world;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.testing.TestPlatform;
|
||||
import java.util.Random;
|
||||
import net.minecraft.world.level.levelgen.LegacyRandomSource;
|
||||
import net.minecraft.world.level.levelgen.PositionalRandomFactory;
|
||||
import net.minecraft.world.level.levelgen.XoroshiroRandomSource;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** {@link PositionalRandoms}' first draws are the ones the game's randoms would make, bit for bit. */
|
||||
class PositionalRandomsTest {
|
||||
|
||||
@BeforeAll
|
||||
static void platform() {
|
||||
// The game's math and utility classes start the platform's services when first loaded.
|
||||
TestPlatform.install();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void off() {
|
||||
PositionalRandoms.setEnabled(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstDrawsAreTheGamesAtEveryPosition() {
|
||||
PositionalRandoms.setEnabled(true);
|
||||
Random seeds = new Random(26_3);
|
||||
for (int factories = 0; factories < 50; factories++) {
|
||||
PositionalRandomFactory factory = new XoroshiroRandomSource(seeds.nextLong()).forkPositional();
|
||||
for (int i = 0; i < 2000; i++) {
|
||||
int x = seeds.nextInt(60_000_000) - 30_000_000;
|
||||
int y = seeds.nextInt(4064) - 2032;
|
||||
int z = seeds.nextInt(60_000_000) - 30_000_000;
|
||||
assertThat(Float.floatToRawIntBits(PositionalRandoms.nextFloatAt(factory, x, y, z)))
|
||||
.isEqualTo(Float.floatToRawIntBits(factory.at(x, y, z).nextFloat()));
|
||||
assertThat(Double.doubleToRawLongBits(PositionalRandoms.nextDoubleAt(factory, x, y, z)))
|
||||
.isEqualTo(
|
||||
Double.doubleToRawLongBits(factory.at(x, y, z).nextDouble()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllZeroSeedTakesTheGeneratorsStandIn() {
|
||||
// A factory whose seeds cancel the position's out at (0, 0, 0): seedLo 0 there, seedHi 0.
|
||||
PositionalRandoms.setEnabled(true);
|
||||
PositionalRandomFactory factory = new XoroshiroRandomSource.XoroshiroPositionalRandomFactory(0L, 0L);
|
||||
assertThat(PositionalRandoms.nextFloatAt(factory, 0, 0, 0))
|
||||
.isEqualTo(factory.at(0, 0, 0).nextFloat());
|
||||
assertThat(PositionalRandoms.nextDoubleAt(factory, 0, 0, 0))
|
||||
.isEqualTo(factory.at(0, 0, 0).nextDouble());
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherFactoriesMakeTheirRandom() {
|
||||
PositionalRandoms.setEnabled(true);
|
||||
PositionalRandomFactory factory = new LegacyRandomSource(42L).forkPositional();
|
||||
assertThat(PositionalRandoms.nextFloatAt(factory, 5, 6, 7))
|
||||
.isEqualTo(factory.at(5, 6, 7).nextFloat());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package incari.client.world;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import incari.client.testing.VanillaRegistries;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import it.unimi.dsi.fastutil.shorts.ShortList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.nbt.NbtOps;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.LevelHeightAccessor;
|
||||
import net.minecraft.world.level.StructureManager;
|
||||
import net.minecraft.world.level.WorldDataConfiguration;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeManager;
|
||||
import net.minecraft.world.level.biome.BiomeResolver;
|
||||
import net.minecraft.world.level.biome.MultiNoiseBiomeSource;
|
||||
import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterLists;
|
||||
import net.minecraft.world.level.chunk.ChunkAccess;
|
||||
import net.minecraft.world.level.chunk.ChunkGenerator;
|
||||
import net.minecraft.world.level.chunk.LevelChunkSection;
|
||||
import net.minecraft.world.level.chunk.PalettedContainerFactory;
|
||||
import net.minecraft.world.level.chunk.ProtoChunk;
|
||||
import net.minecraft.world.level.chunk.UpgradeData;
|
||||
import net.minecraft.world.level.chunk.status.ChunkStatus;
|
||||
import net.minecraft.world.level.levelgen.Beardifier;
|
||||
import net.minecraft.world.level.levelgen.Heightmap;
|
||||
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import net.minecraft.world.level.levelgen.RandomState;
|
||||
import net.minecraft.world.level.levelgen.blending.Blender;
|
||||
import net.minecraft.world.level.levelgen.structure.BoundingBox;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureStart;
|
||||
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
|
||||
import net.minecraft.world.level.levelgen.structure.pools.JigsawJunction;
|
||||
import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
/**
|
||||
* A chunk's terrain built by a helper ({@link RemoteTerrain}, ADR 0042) is the chunk the server
|
||||
* builds itself: the job written from the server's chunks, the helper's own registries and
|
||||
* generator set up from the server's description, its result put into a fresh chunk. Every
|
||||
* section's blocks are compared as the game writes them, palette and all, with the heightmaps and
|
||||
* the fluids to update.
|
||||
*/
|
||||
class RemoteTerrainTest {
|
||||
|
||||
private static final long SEED = 20260928L;
|
||||
private static RegistryAccess.Frozen registries;
|
||||
private static PalettedContainerFactory containers;
|
||||
private static NoiseBasedChunkGenerator generator;
|
||||
private static RandomState randomState;
|
||||
private static Map<Integer, RemoteTerrain.Built> helper;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() throws Exception {
|
||||
registries = VanillaRegistries.load();
|
||||
containers = PalettedContainerFactory.create(registries);
|
||||
Holder<NoiseGeneratorSettings> settings =
|
||||
registries.lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow(NoiseGeneratorSettings.OVERWORLD);
|
||||
generator = new NoiseBasedChunkGenerator(
|
||||
MultiNoiseBiomeSource.createFromPreset(registries
|
||||
.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST)
|
||||
.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD)),
|
||||
settings);
|
||||
randomState = RandomState.create(registries.lookupOrThrow(Registries.NOISE), SEED, settings.value());
|
||||
DynamicOps<Tag> ops = RegistryOps.create(NbtOps.INSTANCE, registries);
|
||||
CompoundTag setup = new CompoundTag();
|
||||
setup.putInt("biomes", RemoteTerrain.biomeNumbering(registries));
|
||||
CompoundTag entry = new CompoundTag();
|
||||
entry.putInt("id", 0);
|
||||
entry.putLong("seed", SEED);
|
||||
entry.putInt("min_y", -64);
|
||||
entry.putInt("height", 384);
|
||||
entry.put("generator", ChunkGenerator.CODEC.encodeStart(ops, generator).getOrThrow());
|
||||
ListTag generators = new ListTag();
|
||||
generators.add(entry);
|
||||
setup.put("generators", generators);
|
||||
helper = RemoteTerrain.setUp(
|
||||
RemoteTerrain.loadRegistries(WorldDataConfiguration.CODEC
|
||||
.encodeStart(NbtOps.INSTANCE, WorldDataConfiguration.DEFAULT)
|
||||
.getOrThrow()),
|
||||
setup);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"0, 0", "37, -112", "-300, 40", "1000, 1000"})
|
||||
void aChunkBuiltByTheHelperIsTheChunkBuiltHere(int chunkX, int chunkZ) {
|
||||
for (int x = chunkX; x < chunkX + 2; x++) {
|
||||
for (int z = chunkZ; z < chunkZ + 2; z++) {
|
||||
Map<ChunkPos, ProtoChunk> here = biomes(x, z);
|
||||
ProtoChunk expected = here.get(new ChunkPos(x, z));
|
||||
buildHere(expected, here);
|
||||
|
||||
Map<ChunkPos, ProtoChunk> there = biomes(x, z);
|
||||
ProtoChunk actual = there.get(new ChunkPos(x, z));
|
||||
byte[] job =
|
||||
TerrainJob.encode(7, 0, actual, (cx, cz) -> there.get(new ChunkPos(cx, cz)), Beardifier.EMPTY);
|
||||
byte[] result = RemoteTerrain.build(job, helper);
|
||||
assertThat(TerrainJob.resultId(result)).isEqualTo(7);
|
||||
TerrainJob.apply(result, actual);
|
||||
|
||||
assertSame(expected, actual);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void structuresNearAChunkCrossAsTheyAre() {
|
||||
Beardifier beardifier = new Beardifier(
|
||||
List.of(new Beardifier.Rigid(new BoundingBox(1, 60, 2, 20, 75, 18), TerrainAdjustment.BEARD_THIN, 3)),
|
||||
List.of(new JigsawJunction(5, 64, 7, -2, StructureTemplatePool.Projection.TERRAIN_MATCHING)),
|
||||
new BoundingBox(-23, 36, -22, 44, 99, 42));
|
||||
Map<ChunkPos, ProtoChunk> chunks = biomes(0, 0);
|
||||
ProtoChunk chunk = chunks.get(new ChunkPos(0, 0));
|
||||
byte[] job = TerrainJob.encode(1, 0, chunk, (cx, cz) -> chunks.get(new ChunkPos(cx, cz)), beardifier);
|
||||
|
||||
TerrainJob.Job read = TerrainJob.decode(job, LevelHeightAccessor.create(-64, 384), containers);
|
||||
|
||||
Beardifier back = read.beardifier();
|
||||
assertThat(back.pieces()).isEqualTo(beardifier.pieces());
|
||||
assertThat(back.affectedBox()).isEqualTo(beardifier.affectedBox());
|
||||
assertThat(back.junctions()).hasSize(1);
|
||||
JigsawJunction junction = back.junctions().getFirst();
|
||||
assertThat(List.of(
|
||||
junction.getSourceX(),
|
||||
junction.getSourceGroundY(),
|
||||
junction.getSourceZ(),
|
||||
junction.getDeltaY()))
|
||||
.containsExactly(5, 64, 7, -2);
|
||||
assertThat(junction.getDestProjection()).isEqualTo(StructureTemplatePool.Projection.TERRAIN_MATCHING);
|
||||
assertThat(read.chunk().getPersistedStatus()).isEqualTo(ChunkStatus.BIOMES);
|
||||
Set<Holder<Biome>> possible = new HashSet<>();
|
||||
for (ProtoChunk around : chunks.values()) {
|
||||
around.collectBiomesInPalette(possible);
|
||||
}
|
||||
assertThat(read.possibleBiomes()).isEqualTo(possible);
|
||||
}
|
||||
|
||||
private static void assertSame(ProtoChunk expected, ProtoChunk actual) {
|
||||
LevelChunkSection[] expectedSections = expected.getSections();
|
||||
LevelChunkSection[] actualSections = actual.getSections();
|
||||
long solid = 0;
|
||||
for (int i = 0; i < expectedSections.length; i++) {
|
||||
assertThat(written(actualSections[i]))
|
||||
.as("%s section %d", expected.getPos(), i)
|
||||
.isEqualTo(written(expectedSections[i]));
|
||||
assertThat(actualSections[i].hasOnlyAir()).isEqualTo(expectedSections[i].hasOnlyAir());
|
||||
assertThat(actualSections[i].hasFluid()).isEqualTo(expectedSections[i].hasFluid());
|
||||
assertThat(actualSections[i].isRandomlyTicking()).isEqualTo(expectedSections[i].isRandomlyTicking());
|
||||
if (!expectedSections[i].hasOnlyAir()) {
|
||||
solid++;
|
||||
}
|
||||
}
|
||||
assertThat(solid).as("terrain was generated").isGreaterThan(3);
|
||||
for (Heightmap.Types type : Heightmap.Types.values()) {
|
||||
assertThat(actual.hasPrimedHeightmap(type)).isEqualTo(expected.hasPrimedHeightmap(type));
|
||||
if (expected.hasPrimedHeightmap(type)) {
|
||||
assertThat(actual.getOrCreateHeightmapUnprimed(type).getRawData())
|
||||
.isEqualTo(expected.getOrCreateHeightmapUnprimed(type).getRawData());
|
||||
}
|
||||
}
|
||||
ShortList[] expectedLists = expected.getPostProcessing();
|
||||
ShortList[] actualLists = actual.getPostProcessing();
|
||||
for (int i = 0; i < expectedLists.length; i++) {
|
||||
assertThat(actualLists[i] == null ? List.of() : List.copyOf(actualLists[i]))
|
||||
.as("%s fluids to update in section %d", expected.getPos(), i)
|
||||
.isEqualTo(expectedLists[i] == null ? List.of() : List.copyOf(expectedLists[i]));
|
||||
}
|
||||
BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
|
||||
pos.set(expected.getPos().getMinBlockX(), 0, expected.getPos().getMinBlockZ());
|
||||
assertThat(actual.getBlockState(pos)).isEqualTo(expected.getBlockState(pos));
|
||||
}
|
||||
|
||||
/** A section's blocks as the game writes them: palette, then the packed ids. */
|
||||
private static byte[] written(LevelChunkSection section) {
|
||||
FriendlyByteBuf out = new FriendlyByteBuf(Unpooled.buffer());
|
||||
section.getStates().write(out);
|
||||
byte[] bytes = new byte[out.readableBytes()];
|
||||
out.readBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/** The chunk at x, z and the eight around it, at the biomes step, as the server has them for its terrain. */
|
||||
private static Map<ChunkPos, ProtoChunk> biomes(int chunkX, int chunkZ) {
|
||||
Map<ChunkPos, ProtoChunk> chunks = new HashMap<>();
|
||||
StructureManager structures = noStructures();
|
||||
for (int x = chunkX - 1; x <= chunkX + 1; x++) {
|
||||
for (int z = chunkZ - 1; z <= chunkZ + 1; z++) {
|
||||
ProtoChunk chunk = new ProtoChunk(
|
||||
new ChunkPos(x, z), UpgradeData.EMPTY, LevelHeightAccessor.create(-64, 384), containers, null);
|
||||
generator
|
||||
.createBiomes(randomState, Blender.empty(), structures, chunk)
|
||||
.join();
|
||||
chunk.setPersistedStatus(ChunkStatus.BIOMES);
|
||||
chunks.put(chunk.getPos(), chunk);
|
||||
}
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/** Builds the chunk's terrain here, as the server does with its region. */
|
||||
private static void buildHere(ProtoChunk chunk, Map<ChunkPos, ProtoChunk> chunks) {
|
||||
BiomeResolver beyond = generator.getBiomeSource().createUncachedResolver(randomState);
|
||||
BiomeManager biomes = new BiomeManager(
|
||||
(x, y, z) -> {
|
||||
ChunkAccess around = chunks.get(new ChunkPos(x >> 2, z >> 2));
|
||||
return around != null ? around.getNoiseBiome(x, y, z) : beyond.getNoiseBiome(x, y, z);
|
||||
},
|
||||
BiomeManager.obfuscateSeed(SEED));
|
||||
Set<Holder<Biome>> possible = new HashSet<>();
|
||||
for (ProtoChunk around : chunks.values()) {
|
||||
around.collectBiomesInPalette(possible);
|
||||
}
|
||||
generator
|
||||
.buildTerrain(chunk, Blender.empty(), randomState, noStructures(), biomes, null, possible)
|
||||
.join();
|
||||
}
|
||||
|
||||
/** A structure manager with no structures anywhere. */
|
||||
@SuppressWarnings("NullAway") // Never reads its level: every lookup is answered here.
|
||||
private static StructureManager noStructures() {
|
||||
return new StructureManager(null, null, null) {
|
||||
@Override
|
||||
public List<StructureStart> startsForStructure(int x, int z, Predicate<Structure> matcher) {
|
||||
return List.of();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package incari.client.world;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.testing.VanillaRegistries;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.biome.BiomeSource;
|
||||
import net.minecraft.world.level.biome.MultiNoiseBiomeSource;
|
||||
import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterLists;
|
||||
import net.minecraft.world.level.chunk.ChunkGeneratorStructureState;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import net.minecraft.world.level.levelgen.RandomState;
|
||||
import net.minecraft.world.level.levelgen.structure.BuiltinStructureSets;
|
||||
import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
/**
|
||||
* The strongholds worked out ring by ring are the game's own, on the vanilla overworld: the same
|
||||
* positions in the same order, and a chunk is one exactly when the game's list holds it.
|
||||
*/
|
||||
class StrongholdRingsTest {
|
||||
|
||||
/** Runs nothing: the searches happen only when the test asks. */
|
||||
private static final Executor NOWHERE = task -> {};
|
||||
|
||||
private static HolderLookup.Provider registries;
|
||||
|
||||
@BeforeAll
|
||||
static void bootstrap() {
|
||||
registries = VanillaRegistries.load();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void off() {
|
||||
StrongholdRings.setEnabled(false);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(longs = {20260928L, -4172144997902289642L})
|
||||
void ringsAreTheGamesInTheGamesOrder(long seed) {
|
||||
World world = new World(seed);
|
||||
List<ChunkPos> game = world.gameRings();
|
||||
|
||||
StrongholdRings.Rings rings = world.lazyRings();
|
||||
assertThat(rings.searched()).isZero();
|
||||
assertThat(new ArrayList<>(rings)).isEqualTo(game);
|
||||
assertThat(rings.searched()).isEqualTo(game.size());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(longs = {20260928L, -4172144997902289642L})
|
||||
void aChunkIsARingPositionExactlyWhenTheGameSaysSo(long seed) {
|
||||
World world = new World(seed);
|
||||
List<ChunkPos> game = world.gameRings();
|
||||
|
||||
StrongholdRings.Rings rings = world.lazyRings();
|
||||
// Spawn's surroundings are far inside the first ring: nothing to search.
|
||||
for (int x = -32; x <= 32; x++) {
|
||||
for (int z = -32; z <= 32; z++) {
|
||||
assertThat(rings.contains(new ChunkPos(x, z))).isFalse();
|
||||
}
|
||||
}
|
||||
assertThat(rings.searched()).isZero();
|
||||
|
||||
for (ChunkPos ring : game.subList(0, 12)) {
|
||||
for (int dx = -9; dx <= 9; dx++) {
|
||||
for (int dz = -9; dz <= 9; dz++) {
|
||||
ChunkPos chunk = new ChunkPos(ring.x() + dx, ring.z() + dz);
|
||||
assertThat(rings.contains(chunk)).as("%s", chunk).isEqualTo(game.contains(chunk));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A vanilla overworld's biomes and noise for {@code seed}. */
|
||||
private static final class World {
|
||||
private final long seed;
|
||||
private final BiomeSource biomes;
|
||||
private final RandomState randomState;
|
||||
private final ConcentricRingsStructurePlacement placement;
|
||||
|
||||
World(long seed) {
|
||||
this.seed = seed;
|
||||
biomes = MultiNoiseBiomeSource.createFromPreset(registries
|
||||
.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST)
|
||||
.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD));
|
||||
NoiseGeneratorSettings settings = registries
|
||||
.lookupOrThrow(Registries.NOISE_SETTINGS)
|
||||
.getOrThrow(NoiseGeneratorSettings.OVERWORLD)
|
||||
.value();
|
||||
randomState = RandomState.create(registries.lookupOrThrow(Registries.NOISE), seed, settings);
|
||||
placement = (ConcentricRingsStructurePlacement) registries
|
||||
.lookupOrThrow(Registries.STRUCTURE_SET)
|
||||
.getOrThrow(BuiltinStructureSets.STRONGHOLDS)
|
||||
.value()
|
||||
.placement();
|
||||
}
|
||||
|
||||
List<ChunkPos> gameRings() {
|
||||
StrongholdRings.setEnabled(false);
|
||||
ChunkGeneratorStructureState state = ChunkGeneratorStructureState.createForNormal(
|
||||
randomState, seed, ChunkPos.ZERO, biomes, registries.lookupOrThrow(Registries.STRUCTURE_SET));
|
||||
List<ChunkPos> rings = state.getRingPositionsFor(placement);
|
||||
assertThat(rings).hasSize(placement.count());
|
||||
return List.copyOf(rings);
|
||||
}
|
||||
|
||||
StrongholdRings.Rings lazyRings() {
|
||||
StrongholdRings.setEnabled(true);
|
||||
var future = StrongholdRings.plan(placement, seed, biomes, randomState, NOWHERE);
|
||||
assertThat(future).isNotNull();
|
||||
return (StrongholdRings.Rings) future.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package incari.client.world;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.testing.VanillaRegistries;
|
||||
import java.util.Random;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.LevelHeightAccessor;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.chunk.PalettedContainerFactory;
|
||||
import net.minecraft.world.level.chunk.ProtoChunk;
|
||||
import net.minecraft.world.level.chunk.UpgradeData;
|
||||
import net.minecraft.world.level.chunk.status.ChunkStatus;
|
||||
import net.minecraft.world.level.levelgen.Heightmap;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Writing a chunk's surface through {@link SurfaceWrites} leaves it as the game's own writes do:
|
||||
* the same blocks and the same heightmaps, after the same writes to two copies of a chunk, and the
|
||||
* same blocks read back along the way.
|
||||
*/
|
||||
class SurfaceWritesTest {
|
||||
|
||||
/** What the writes put down; filled once the game is bootstrapped. */
|
||||
private static BlockState[] states;
|
||||
|
||||
private static BlockState[] states() {
|
||||
return new BlockState[] {
|
||||
Blocks.STONE.defaultBlockState(),
|
||||
Blocks.DEEPSLATE.defaultBlockState(),
|
||||
Blocks.DIRT.defaultBlockState(),
|
||||
Blocks.GRASS_BLOCK.defaultBlockState(),
|
||||
Blocks.SAND.defaultBlockState(),
|
||||
Blocks.GRAVEL.defaultBlockState(),
|
||||
Blocks.WATER.defaultBlockState(),
|
||||
Blocks.AIR.defaultBlockState(),
|
||||
Blocks.CAVE_AIR.defaultBlockState(),
|
||||
Blocks.SNOW.defaultBlockState(),
|
||||
Blocks.PACKED_ICE.defaultBlockState(),
|
||||
Blocks.OAK_LEAVES.defaultBlockState(),
|
||||
Blocks.GLASS.defaultBlockState(),
|
||||
Blocks.BEDROCK.defaultBlockState(),
|
||||
};
|
||||
}
|
||||
|
||||
private static PalettedContainerFactory containers;
|
||||
|
||||
@BeforeAll
|
||||
static void bootstrap() {
|
||||
containers = PalettedContainerFactory.create(VanillaRegistries.load());
|
||||
states = states();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void off() {
|
||||
SurfaceWrites.setEnabled(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesLeaveTheChunkAsTheGamesWritesDo() {
|
||||
Random random = new Random(26_3L);
|
||||
ChunkPos at = new ChunkPos(3, -2);
|
||||
ProtoChunk game = terrain(at, new Random(7));
|
||||
ProtoChunk ours = terrain(at, new Random(7));
|
||||
|
||||
SurfaceWrites.setEnabled(true);
|
||||
SurfaceWrites writes = SurfaceWrites.of(ours);
|
||||
assertThat(writes).isNotNull();
|
||||
|
||||
BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
|
||||
for (int i = 0; i < 40_000; i++) {
|
||||
int x = at.getMinBlockX() + random.nextInt(16);
|
||||
int z = at.getMinBlockZ() + random.nextInt(16);
|
||||
// Mostly around the surface and below it, as surface rules write; now and then out of range.
|
||||
int y =
|
||||
switch (random.nextInt(10)) {
|
||||
case 0 -> -70 + random.nextInt(8);
|
||||
case 1 -> 315 + random.nextInt(10);
|
||||
default -> -64 + random.nextInt(200);
|
||||
};
|
||||
pos.set(x, y, z);
|
||||
assertThat(writes.get(pos)).as("before %s", pos).isEqualTo(game.getBlockState(pos));
|
||||
BlockState state = states[random.nextInt(states.length)];
|
||||
game.setBlockState(pos, state);
|
||||
writes.set(pos, state);
|
||||
}
|
||||
|
||||
for (int y = -70; y < 330; y++) {
|
||||
for (int x = 0; x < 16; x++) {
|
||||
for (int z = 0; z < 16; z++) {
|
||||
pos.set(at.getMinBlockX() + x, y, at.getMinBlockZ() + z);
|
||||
assertThat(ours.getBlockState(pos)).as("%s", pos).isEqualTo(game.getBlockState(pos));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Heightmap.Types type : ChunkStatus.BIOMES.heightmapsAfter()) {
|
||||
assertThat(ours.getOrCreateHeightmapUnprimed(type).getRawData())
|
||||
.as("%s", type)
|
||||
.isEqualTo(game.getOrCreateHeightmapUnprimed(type).getRawData());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void chunksPastLightOrWithoutHeightmapsAreLeftToTheGame() {
|
||||
SurfaceWrites.setEnabled(true);
|
||||
ProtoChunk lit = terrain(new ChunkPos(0, 0), new Random(1));
|
||||
lit.setPersistedStatus(ChunkStatus.INITIALIZE_LIGHT);
|
||||
assertThat(SurfaceWrites.of(lit)).isNull();
|
||||
|
||||
ProtoChunk bare = new ProtoChunk(new ChunkPos(0, 0), UpgradeData.EMPTY, height(), containers, null);
|
||||
bare.setPersistedStatus(ChunkStatus.BIOMES);
|
||||
assertThat(SurfaceWrites.of(bare)).isNull();
|
||||
|
||||
SurfaceWrites.setEnabled(false);
|
||||
assertThat(SurfaceWrites.of(terrain(new ChunkPos(0, 0), new Random(1)))).isNull();
|
||||
}
|
||||
|
||||
/** A chunk of hills and seas, as noise leaves one for its surface: stone, deepslate below 0, water to 62. */
|
||||
private static ProtoChunk terrain(ChunkPos at, Random random) {
|
||||
ProtoChunk chunk = new ProtoChunk(at, UpgradeData.EMPTY, height(), containers, null);
|
||||
BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
|
||||
for (int x = 0; x < 16; x++) {
|
||||
for (int z = 0; z < 16; z++) {
|
||||
int top = -20 + random.nextInt(120);
|
||||
for (int y = -64; y <= Math.max(top, 62); y++) {
|
||||
BlockState state = y <= top
|
||||
? (y < 0 ? Blocks.DEEPSLATE : Blocks.STONE).defaultBlockState()
|
||||
: Blocks.WATER.defaultBlockState();
|
||||
chunk.setBlockState(pos.set(at.getMinBlockX() + x, y, at.getMinBlockZ() + z), state);
|
||||
}
|
||||
}
|
||||
}
|
||||
chunk.setPersistedStatus(ChunkStatus.BIOMES);
|
||||
return chunk;
|
||||
}
|
||||
|
||||
private static LevelHeightAccessor height() {
|
||||
return LevelHeightAccessor.create(-64, 384);
|
||||
}
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
package incari.client.world;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.client.testing.VanillaRegistries;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.LevelHeightAccessor;
|
||||
import net.minecraft.world.level.StructureManager;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeManager;
|
||||
import net.minecraft.world.level.biome.MultiNoiseBiomeSource;
|
||||
import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterLists;
|
||||
import net.minecraft.world.level.chunk.PalettedContainerFactory;
|
||||
import net.minecraft.world.level.chunk.ProtoChunk;
|
||||
import net.minecraft.world.level.chunk.UpgradeData;
|
||||
import net.minecraft.world.level.chunk.status.ChunkStatus;
|
||||
import net.minecraft.world.level.levelgen.Heightmap;
|
||||
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import net.minecraft.world.level.levelgen.RandomState;
|
||||
import net.minecraft.world.level.levelgen.blending.Blender;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureStart;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
/**
|
||||
* The vanilla overworld's terrain step (biomes, then noise, surface and carvers) leaves every
|
||||
* block and heightmap of a chunk the same with ADR 0041's to 0043's changes as without them: the
|
||||
* surface writer, the biome cells, the cached heights, the density functions' lazy range choices,
|
||||
* the positional randoms' first draws and the surface's reused density buffers, on
|
||||
* areas of three worlds.
|
||||
*
|
||||
* <p>A whole world can't be compared this way between two runs of the server: the features one
|
||||
* chunk places in its neighbours land in the order chunks happen to generate, which differs from
|
||||
* run to run even without any change. The terrain step reads nothing but its own chunk and the
|
||||
* biomes around it, so here each chunk is generated alone, twice. No structures: the structure
|
||||
* manager here has none, the same both ways.
|
||||
*/
|
||||
class TerrainEquivalenceTest {
|
||||
|
||||
private static RegistryAccess.Frozen registries;
|
||||
private static PalettedContainerFactory containers;
|
||||
|
||||
@BeforeAll
|
||||
static void bootstrap() {
|
||||
registries = VanillaRegistries.load();
|
||||
containers = PalettedContainerFactory.create(registries);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void off() {
|
||||
changes(false);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"20260928, 0, 0", "20260928, 37, -112", "-4172144997902289642, -300, 40", "1, 1000, 1000"})
|
||||
void terrainIsTheSameWithTheChangesAsWithout(long seed, int chunkX, int chunkZ) {
|
||||
World world = new World(seed);
|
||||
changes(false);
|
||||
Map<ChunkPos, ProtoChunk> game = world.terrain(chunkX, chunkZ);
|
||||
changes(true);
|
||||
Map<ChunkPos, ProtoChunk> ours = world.terrain(chunkX, chunkZ);
|
||||
|
||||
BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
|
||||
long blocks = 0;
|
||||
long solid = 0;
|
||||
for (Map.Entry<ChunkPos, ProtoChunk> entry : game.entrySet()) {
|
||||
ProtoChunk expected = entry.getValue();
|
||||
ProtoChunk actual = ours.get(entry.getKey());
|
||||
for (int y = expected.getMinY(); y <= expected.getMaxY(); y++) {
|
||||
for (int x = 0; x < 16; x++) {
|
||||
for (int z = 0; z < 16; z++) {
|
||||
pos.set(
|
||||
entry.getKey().getMinBlockX() + x,
|
||||
y,
|
||||
entry.getKey().getMinBlockZ() + z);
|
||||
if (!actual.getBlockState(pos).equals(expected.getBlockState(pos))) {
|
||||
assertThat(actual.getBlockState(pos)).as("%s", pos).isEqualTo(expected.getBlockState(pos));
|
||||
}
|
||||
blocks++;
|
||||
if (!expected.getBlockState(pos).isAir()) {
|
||||
solid++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Heightmap.Types type : Heightmap.Types.values()) {
|
||||
if (expected.hasPrimedHeightmap(type)) {
|
||||
assertThat(actual.getOrCreateHeightmapUnprimed(type).getRawData())
|
||||
.as("%s %s", entry.getKey(), type)
|
||||
.isEqualTo(
|
||||
expected.getOrCreateHeightmapUnprimed(type).getRawData());
|
||||
}
|
||||
}
|
||||
}
|
||||
assertThat(blocks).isEqualTo(384L * 256 * game.size());
|
||||
assertThat(solid).as("terrain was generated").isGreaterThan(blocks / 10);
|
||||
}
|
||||
|
||||
private static void changes(boolean on) {
|
||||
SurfaceWrites.setEnabled(on);
|
||||
BiomeCells.setEnabled(on);
|
||||
Heights.setEnabled(on);
|
||||
DensityBranches.setEnabled(on);
|
||||
PositionalRandoms.setEnabled(on);
|
||||
SurfaceBuffers.setEnabled(on);
|
||||
}
|
||||
|
||||
/** The vanilla overworld for a seed. */
|
||||
private static final class World {
|
||||
private final NoiseBasedChunkGenerator generator;
|
||||
private final RandomState randomState;
|
||||
private final long seed;
|
||||
|
||||
World(long seed) {
|
||||
this.seed = seed;
|
||||
Holder<NoiseGeneratorSettings> settings =
|
||||
registries.lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow(NoiseGeneratorSettings.OVERWORLD);
|
||||
generator = new NoiseBasedChunkGenerator(
|
||||
MultiNoiseBiomeSource.createFromPreset(registries
|
||||
.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST)
|
||||
.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD)),
|
||||
settings);
|
||||
randomState = RandomState.create(registries.lookupOrThrow(Registries.NOISE), seed, settings.value());
|
||||
}
|
||||
|
||||
/**
|
||||
* The terrain of the 4x4 chunks from {@code chunkX}, {@code chunkZ}, with biomes made for a
|
||||
* chunk's width around them too, as the game has them by then.
|
||||
*/
|
||||
Map<ChunkPos, ProtoChunk> terrain(int chunkX, int chunkZ) {
|
||||
Map<ChunkPos, ProtoChunk> chunks = new HashMap<>();
|
||||
StructureManager structures = noStructures();
|
||||
for (int x = chunkX - 1; x <= chunkX + 4; x++) {
|
||||
for (int z = chunkZ - 1; z <= chunkZ + 4; z++) {
|
||||
ProtoChunk chunk = new ProtoChunk(
|
||||
new ChunkPos(x, z),
|
||||
UpgradeData.EMPTY,
|
||||
LevelHeightAccessor.create(-64, 384),
|
||||
containers,
|
||||
null);
|
||||
generator
|
||||
.createBiomes(randomState, Blender.empty(), structures, chunk)
|
||||
.join();
|
||||
chunk.setPersistedStatus(ChunkStatus.BIOMES);
|
||||
chunks.put(chunk.getPos(), chunk);
|
||||
}
|
||||
}
|
||||
BiomeManager biomes = new BiomeManager(
|
||||
(x, y, z) -> chunks.get(new ChunkPos(x >> 2, z >> 2)).getNoiseBiome(x, y, z),
|
||||
BiomeManager.obfuscateSeed(seed));
|
||||
Map<ChunkPos, ProtoChunk> built = new HashMap<>();
|
||||
for (int x = chunkX; x < chunkX + 4; x++) {
|
||||
for (int z = chunkZ; z < chunkZ + 4; z++) {
|
||||
ProtoChunk chunk = chunks.get(new ChunkPos(x, z));
|
||||
generator
|
||||
.buildTerrain(
|
||||
chunk,
|
||||
Blender.empty(),
|
||||
randomState,
|
||||
structures,
|
||||
biomes,
|
||||
null,
|
||||
possibleBiomes(chunks, x, z))
|
||||
.join();
|
||||
built.put(chunk.getPos(), chunk);
|
||||
}
|
||||
}
|
||||
return built;
|
||||
}
|
||||
|
||||
/** The biomes of the chunk and its neighbours, as the game collects them for its surface. */
|
||||
private static Set<Holder<Biome>> possibleBiomes(Map<ChunkPos, ProtoChunk> chunks, int chunkX, int chunkZ) {
|
||||
Set<Holder<Biome>> biomes = new HashSet<>();
|
||||
for (int x = chunkX - 1; x <= chunkX + 1; x++) {
|
||||
for (int z = chunkZ - 1; z <= chunkZ + 1; z++) {
|
||||
ProtoChunk chunk = chunks.get(new ChunkPos(x, z));
|
||||
for (int qy = -16; qy < 80; qy++) {
|
||||
for (int qx = 0; qx < 4; qx++) {
|
||||
for (int qz = 0; qz < 4; qz++) {
|
||||
biomes.add(chunk.getNoiseBiome(x * 4 + qx, qy, z * 4 + qz));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return biomes;
|
||||
}
|
||||
|
||||
/** A structure manager with no structures anywhere. */
|
||||
@SuppressWarnings("NullAway") // Never reads its level: every lookup is answered here.
|
||||
private static StructureManager noStructures() {
|
||||
return new StructureManager(null, null, null) {
|
||||
@Override
|
||||
public List<StructureStart> startsForStructure(int x, int z, Predicate<Structure> matcher) {
|
||||
return List.of();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package incari.client.world;
|
||||
|
||||
import incari.client.testing.VanillaRegistries;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.LevelHeightAccessor;
|
||||
import net.minecraft.world.level.StructureManager;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeManager;
|
||||
import net.minecraft.world.level.biome.MultiNoiseBiomeSource;
|
||||
import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterLists;
|
||||
import net.minecraft.world.level.chunk.PalettedContainerFactory;
|
||||
import net.minecraft.world.level.chunk.ProtoChunk;
|
||||
import net.minecraft.world.level.chunk.UpgradeData;
|
||||
import net.minecraft.world.level.chunk.status.ChunkStatus;
|
||||
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import net.minecraft.world.level.levelgen.RandomState;
|
||||
import net.minecraft.world.level.levelgen.blending.Blender;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureStart;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Times the overworld's terrain step (biomes, then noise, surface and carvers) on the JVM, with the
|
||||
* browser's world generation changes on: 48 chunks a round, 16 rounds, the last 8 reported. For
|
||||
* comparing a world generation change before a browser build; JVM shares don't transfer to the page
|
||||
* exactly, but this step is plain computation in both. Runs only with {@code INCARI_BENCH} set:
|
||||
* {@code INCARI_BENCH=1 ./gradlew :client:test --tests '*TerrainStepBench*' -i}.
|
||||
*/
|
||||
class TerrainStepBench {
|
||||
|
||||
private static final int ROUNDS = 16;
|
||||
|
||||
@Test
|
||||
void terrainStep() {
|
||||
Assumptions.assumeTrue(System.getenv("INCARI_BENCH") != null, "INCARI_BENCH not set");
|
||||
RegistryAccess.Frozen registries = VanillaRegistries.load();
|
||||
PalettedContainerFactory containers = PalettedContainerFactory.create(registries);
|
||||
SurfaceWrites.setEnabled(true);
|
||||
BiomeCells.setEnabled(true);
|
||||
Heights.setEnabled(true);
|
||||
DensityBranches.setEnabled(on("densitychoices"));
|
||||
PositionalRandoms.setEnabled(on("randoms"));
|
||||
SurfaceBuffers.setEnabled(on("surfacebuffers"));
|
||||
Holder<NoiseGeneratorSettings> settings =
|
||||
registries.lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow(NoiseGeneratorSettings.OVERWORLD);
|
||||
NoiseBasedChunkGenerator generator = new NoiseBasedChunkGenerator(
|
||||
MultiNoiseBiomeSource.createFromPreset(registries
|
||||
.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST)
|
||||
.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD)),
|
||||
settings);
|
||||
long seed = 20260928L;
|
||||
RandomState randomState =
|
||||
RandomState.create(registries.lookupOrThrow(Registries.NOISE), seed, settings.value());
|
||||
StructureManager structures = noStructures();
|
||||
long total = 0;
|
||||
for (int round = 0; round < ROUNDS; round++) {
|
||||
// A new area each round, as a flight over fresh terrain.
|
||||
int chunkX = round * 8;
|
||||
Map<ChunkPos, ProtoChunk> chunks = new HashMap<>();
|
||||
for (int x = chunkX - 1; x <= chunkX + 8; x++) {
|
||||
for (int z = -1; z <= 6; z++) {
|
||||
ProtoChunk chunk = new ProtoChunk(
|
||||
new ChunkPos(x, z),
|
||||
UpgradeData.EMPTY,
|
||||
LevelHeightAccessor.create(-64, 384),
|
||||
containers,
|
||||
null);
|
||||
generator
|
||||
.createBiomes(randomState, Blender.empty(), structures, chunk)
|
||||
.join();
|
||||
chunk.setPersistedStatus(ChunkStatus.BIOMES);
|
||||
chunks.put(chunk.getPos(), chunk);
|
||||
}
|
||||
}
|
||||
BiomeManager biomes = new BiomeManager(
|
||||
(x, y, z) -> chunks.get(new ChunkPos(x >> 2, z >> 2)).getNoiseBiome(x, y, z),
|
||||
BiomeManager.obfuscateSeed(seed));
|
||||
long start = System.nanoTime();
|
||||
for (int x = chunkX; x < chunkX + 8; x++) {
|
||||
for (int z = 0; z < 6; z++) {
|
||||
ProtoChunk chunk = chunks.get(new ChunkPos(x, z));
|
||||
generator
|
||||
.buildTerrain(
|
||||
chunk,
|
||||
Blender.empty(),
|
||||
randomState,
|
||||
structures,
|
||||
biomes,
|
||||
null,
|
||||
possibleBiomes(chunks, x, z))
|
||||
.join();
|
||||
}
|
||||
}
|
||||
long elapsed = System.nanoTime() - start;
|
||||
if (round >= ROUNDS / 2) {
|
||||
total += elapsed;
|
||||
}
|
||||
System.out.printf("round %2d: %.2f ms a chunk%n", round, elapsed / 48.0 / 1e6);
|
||||
}
|
||||
System.out.printf(
|
||||
"terrain step: %.3f ms a chunk over the last %d rounds%n",
|
||||
total / 48.0 / (ROUNDS / 2) / 1e6, ROUNDS / 2);
|
||||
}
|
||||
|
||||
/** A change is on unless {@code INCARI_BENCH_OFF} names it (comma-separated), to compare. */
|
||||
private static boolean on(String name) {
|
||||
String off = System.getenv("INCARI_BENCH_OFF");
|
||||
return off == null || !List.of(off.split(",")).contains(name);
|
||||
}
|
||||
|
||||
private static Set<Holder<Biome>> possibleBiomes(Map<ChunkPos, ProtoChunk> chunks, int chunkX, int chunkZ) {
|
||||
Set<Holder<Biome>> biomes = new HashSet<>();
|
||||
for (int x = chunkX - 1; x <= chunkX + 1; x++) {
|
||||
for (int z = chunkZ - 1; z <= chunkZ + 1; z++) {
|
||||
ProtoChunk chunk = chunks.get(new ChunkPos(x, z));
|
||||
for (int qy = -16; qy < 80; qy++) {
|
||||
for (int qx = 0; qx < 4; qx++) {
|
||||
for (int qz = 0; qz < 4; qz++) {
|
||||
biomes.add(chunk.getNoiseBiome(x * 4 + qx, qy, z * 4 + qz));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return biomes;
|
||||
}
|
||||
|
||||
@SuppressWarnings("NullAway") // Never reads its level: every lookup is answered here.
|
||||
private static StructureManager noStructures() {
|
||||
return new StructureManager(null, null, null) {
|
||||
@Override
|
||||
public List<StructureStart> startsForStructure(int x, int z, Predicate<Structure> matcher) {
|
||||
return List.of();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package incari.client.world;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class WorldImportTest {
|
||||
|
||||
@TempDir
|
||||
Path temp;
|
||||
|
||||
private Path world(String name) throws IOException {
|
||||
Path world = temp.resolve("source").resolve(name);
|
||||
Files.createDirectories(world.resolve("region"));
|
||||
Files.writeString(world.resolve("level.dat"), "level " + name);
|
||||
Files.writeString(world.resolve("session.lock"), "lock");
|
||||
Files.write(world.resolve("region").resolve("r.0.0.mca"), new byte[] {1, 2, 3, 4});
|
||||
return world;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDownloadedWorldComesBackUnderItsOwnName() throws IOException {
|
||||
Path world = world("Castle");
|
||||
Path zip = temp.resolve("Castle.zip");
|
||||
try (OutputStream out = Files.newOutputStream(zip)) {
|
||||
FolderDownloads.zip(world, "Castle", out);
|
||||
}
|
||||
Path saves = temp.resolve("saves");
|
||||
|
||||
assertThat(WorldImport.importOne(zip, saves)).isEqualTo("Castle");
|
||||
assertThat(Files.readString(saves.resolve("Castle/level.dat"))).isEqualTo("level Castle");
|
||||
assertThat(Files.readAllBytes(saves.resolve("Castle/region/r.0.0.mca"))).containsExactly(1, 2, 3, 4);
|
||||
assertThat(saves.resolve("Castle/session.lock")).doesNotExist();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImportNeverReplacesAWorld() throws IOException {
|
||||
Path world = world("Castle");
|
||||
Path zip = temp.resolve("Castle.zip");
|
||||
try (OutputStream out = Files.newOutputStream(zip)) {
|
||||
FolderDownloads.zip(world, "Castle", out);
|
||||
}
|
||||
Path saves = temp.resolve("saves");
|
||||
|
||||
String first = WorldImport.importOne(zip, saves);
|
||||
String second = WorldImport.importOne(zip, saves);
|
||||
|
||||
assertThat(first).isEqualTo("Castle");
|
||||
assertThat(second).isNotEqualTo("Castle").startsWith("Castle");
|
||||
assertThat(saves.resolve(second).resolve("level.dat")).exists();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aZipWithTheWorldAtItsRootIsNamedAfterTheZip() throws IOException {
|
||||
Path zip = temp.resolve("Island.zip");
|
||||
try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(zip))) {
|
||||
out.putNextEntry(new ZipEntry("level.dat"));
|
||||
out.write("island".getBytes(StandardCharsets.UTF_8));
|
||||
out.closeEntry();
|
||||
}
|
||||
|
||||
assertThat(WorldImport.importOne(zip, temp.resolve("saves"))).isEqualTo("Island");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFolderIsCopiedInWithoutItsLock() throws IOException {
|
||||
Path saves = temp.resolve("saves");
|
||||
|
||||
assertThat(WorldImport.importOne(world("Farm"), saves)).isEqualTo("Farm");
|
||||
assertThat(saves.resolve("Farm/region/r.0.0.mca")).exists();
|
||||
assertThat(saves.resolve("Farm/session.lock")).doesNotExist();
|
||||
}
|
||||
|
||||
@Test
|
||||
void somethingThatIsNoWorldIsTurnedDown() throws IOException {
|
||||
Path zip = temp.resolve("pack.zip");
|
||||
try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(zip))) {
|
||||
out.putNextEntry(new ZipEntry("pack.mcmeta"));
|
||||
out.closeEntry();
|
||||
}
|
||||
|
||||
assertThat(WorldImport.importOne(zip, temp.resolve("saves"))).isNull();
|
||||
assertThat(WorldImport.importOne(temp.resolve("notes.txt"), temp.resolve("saves")))
|
||||
.isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEntryOutsideTheWorldIsRefused() throws IOException {
|
||||
Path zip = temp.resolve("Evil.zip");
|
||||
try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(zip))) {
|
||||
out.putNextEntry(new ZipEntry("level.dat"));
|
||||
out.closeEntry();
|
||||
out.putNextEntry(new ZipEntry("../../outside.txt"));
|
||||
out.closeEntry();
|
||||
}
|
||||
|
||||
assertThatThrownBy(() -> WorldImport.importOne(zip, temp.resolve("saves")))
|
||||
.isInstanceOf(IOException.class);
|
||||
assertThat(temp.resolve("outside.txt")).doesNotExist();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user