Merge remote-tracking branch 'origin/t3/achieve-full-parity' into parity/rendering-anim
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.server.IntegratedServer;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
|
||||
/**
|
||||
* The vanilla client as the reference LAN host for the multiplayer harness
|
||||
* (tools/test_lan_vanilla_client.py): it runs net.minecraft.client.main.Main
|
||||
* unchanged, and once the singleplayer world is up it turns off the
|
||||
* integrated server's authentication (it always authenticates guests against
|
||||
* Mojang's session servers, which offline test clients cannot pass) and opens
|
||||
* the world to LAN on the port in -Dhorizon.lanPort, with commands allowed,
|
||||
* as the "Open to LAN" screen does.
|
||||
*/
|
||||
public final class OfflineLanHost {
|
||||
public static void main(String[] args) throws Exception {
|
||||
int port = Integer.getInteger("horizon.lanPort", 0);
|
||||
Thread watcher = new Thread(() -> {
|
||||
boolean published = false;
|
||||
while (!published) {
|
||||
try {
|
||||
Thread.sleep(500);
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
IntegratedServer server = mc == null ? null : mc.getSingleplayerServer();
|
||||
if (server == null || mc.player == null || !server.isReady()) continue;
|
||||
server.setUsesAuthentication(false);
|
||||
mc.execute(() -> {
|
||||
boolean ok = server.publishServer(MinecraftServer.MultiplayerScope.LAN, true, port);
|
||||
System.out.println("[OfflineLanHost] published=" + ok + " port=" + server.getPort());
|
||||
});
|
||||
published = true;
|
||||
} catch (Throwable t) {
|
||||
// The game is still starting.
|
||||
}
|
||||
}
|
||||
}, "horizon-offline-lan");
|
||||
watcher.setDaemon(true);
|
||||
watcher.start();
|
||||
net.minecraft.client.main.Main.main(args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.Camera;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.client.resources.sounds.*;
|
||||
import net.minecraft.client.sounds.ChannelAccess;
|
||||
import net.minecraft.client.sounds.SoundEngine;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.tags.FluidTags;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.attribute.*;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.LightLayer;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.BubbleColumnBlock;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.level.material.Fluid;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Runs the local player's real ambient sound path over the real SoundEngine
|
||||
* (VanillaSoundRig): LocalPlayer.updateIsUnderwater (enter/exit sounds through
|
||||
* ClientLevel.playLocalSound and the UnderLiquidAmbientSoundInstance), the
|
||||
* UnderwaterAmbientSoundHandler and the BiomeAmbientSoundsHandler, then
|
||||
* SoundManager.tick, once per client tick. Inputs: the AMBIENT_SOUNDS value
|
||||
* (a constant attribute layer), the player's position, eye height, whether
|
||||
* its eyes are in water, spectator and removed flags, and the level's sky and
|
||||
* block brightness (a hash of the position). Prints the level random's next
|
||||
* long (without drawing it), the handlers' state and every playing instance.
|
||||
*/
|
||||
public final class VanillaAmbientOracle {
|
||||
public static final class Actor extends LocalPlayer {
|
||||
boolean eyeInWater, spectator;
|
||||
|
||||
Actor() {
|
||||
super(null, null, null, null, null, null, false, null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEyeInFluid(final TagKey<Fluid> type) {
|
||||
return type == FluidTags.WATER && eyeInWater;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSpectator() {
|
||||
return spectator;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Lvl extends ClientLevel {
|
||||
int mode;
|
||||
final Map<BlockPos, Boolean> columns = new HashMap<>();
|
||||
|
||||
Lvl() {
|
||||
super(null, null, null, null, 0, 0, null, false, 0L, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBrightness(final LightLayer layer, final BlockPos pos) {
|
||||
return light(mode, pos.getX(), pos.getY(), pos.getZ())[layer == LightLayer.SKY ? 0 : 1];
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockState getBlockState(final BlockPos pos) {
|
||||
Boolean drag = columns.get(pos);
|
||||
return drag == null ? Blocks.AIR.defaultBlockState() : Blocks.BUBBLE_COLUMN.defaultBlockState().setValue(BubbleColumnBlock.DRAG_DOWN, drag);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasChunksAt(final int x0, final int y0, final int z0, final int x1, final int y1, final int z1) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** The scripted brightness: (sky, block) for a light mode and block. */
|
||||
static int[] light(int mode, int x, int y, int z) {
|
||||
int h = x * 73856093 ^ y * 19349663 ^ z * 83492791;
|
||||
return switch (mode) {
|
||||
case 0 -> new int[]{15, 0};
|
||||
case 1 -> new int[]{0, 0};
|
||||
case 2 -> new int[]{0, (h >>> 4) & 15};
|
||||
default -> new int[]{(h & 3) == 0 ? (h >>> 8) & 15 : 0, (h >>> 12) & 15};
|
||||
};
|
||||
}
|
||||
|
||||
/** The player's box (EntityDimensions.makeBoundingBox, width 0.6F). */
|
||||
static AABB box(Vec3 at, float height) {
|
||||
return new AABB(at.x - 0.3F, at.y, at.z - 0.3F, at.x + 0.3F, at.y + height, at.z + 0.3F);
|
||||
}
|
||||
|
||||
static float f(String hex) {
|
||||
return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16));
|
||||
}
|
||||
|
||||
static double d(String hex) {
|
||||
return Double.longBitsToDouble(Long.parseUnsignedLong(hex, 16));
|
||||
}
|
||||
|
||||
static Holder<SoundEvent> event(String id) {
|
||||
return Holder.direct(SoundEvent.createVariableRangeEvent(Identifier.parse(id)));
|
||||
}
|
||||
|
||||
/** "loop|- mood|- addition..." with mood "sound,delay,extent,offsetbits" and additions "sound,chancebits". */
|
||||
static AmbientSounds sounds(String[] a) {
|
||||
Optional<Holder<SoundEvent>> loop = a[1].equals("-") ? Optional.empty() : Optional.of(event(a[1]));
|
||||
Optional<AmbientMoodSettings> mood = Optional.empty();
|
||||
if (!a[2].equals("-")) {
|
||||
String[] m = a[2].split(",");
|
||||
mood = Optional.of(new AmbientMoodSettings(event(m[0]), Integer.parseInt(m[1]), Integer.parseInt(m[2]), d(m[3])));
|
||||
}
|
||||
var additions = new ArrayList<AmbientAdditionsSettings>();
|
||||
for (int i = 3; i < a.length; i++) {
|
||||
String[] p = a[i].split(",");
|
||||
additions.add(new AmbientAdditionsSettings(event(p[0]), d(p[1])));
|
||||
}
|
||||
return new AmbientSounds(loop, mood, additions);
|
||||
}
|
||||
|
||||
/** LegacyRandomSource's next nextLong(), read from its state. */
|
||||
static long peek(RandomSource random) throws Exception {
|
||||
long s = ((java.util.concurrent.atomic.AtomicLong) VanillaSoundRig.get(random,
|
||||
Class.forName("net.minecraft.world.level.levelgen.LegacyRandomSource"), "seed")).get();
|
||||
long m = 0x5DEECE66DL, mask = (1L << 48) - 1;
|
||||
long s1 = (s * m + 0xBL) & mask;
|
||||
long s2 = (s1 * m + 0xBL) & mask;
|
||||
return ((long) (int) (s1 >>> 16) << 32) + (int) (s2 >>> 16);
|
||||
}
|
||||
|
||||
static String bits(double v) {
|
||||
return String.format("%016x", Double.doubleToRawLongBits(v));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var rig = new VanillaSoundRig(Path.of(args[0]));
|
||||
var mc = VanillaSoundRig.make(Minecraft.class);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "soundManager", rig.manager);
|
||||
var renderer = VanillaSoundRig.make(GameRenderer.class);
|
||||
VanillaSoundRig.set(renderer, GameRenderer.class, "mainCamera", VanillaSoundRig.make(Camera.class));
|
||||
VanillaSoundRig.set(VanillaSoundRig.get(renderer, GameRenderer.class, "mainCamera"), Camera.class, "position", Vec3.ZERO);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "gameRenderer", renderer);
|
||||
Method update = LocalPlayer.class.getDeclaredMethod("updateIsUnderwater");
|
||||
update.setAccessible(true);
|
||||
var instanceToChannel = VanillaSoundRig.field(SoundEngine.class, "instanceToChannel");
|
||||
Lvl level = null;
|
||||
Actor actor = null;
|
||||
UnderwaterAmbientSoundHandler underwater = null;
|
||||
BiomeAmbientSoundsHandler biome = null;
|
||||
BubbleColumnAmbientSoundHandler bubble = null;
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) {
|
||||
for (String line : Files.readAllLines(Path.of(args[1]))) {
|
||||
out.println(line);
|
||||
String[] a = line.split(" ");
|
||||
switch (a[0]) {
|
||||
case "start" -> {
|
||||
// A new level and player: fresh handlers on a seeded level random.
|
||||
rig.manager.stop();
|
||||
level = VanillaSoundRig.make(Lvl.class);
|
||||
VanillaSoundRig.set(level, Level.class, "random", RandomSource.create(Long.parseLong(a[1])));
|
||||
VanillaSoundRig.set(level, ClientLevel.class, "minecraft", mc);
|
||||
VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", EnvironmentAttributeSystem.builder().build());
|
||||
actor = VanillaSoundRig.make(Actor.class);
|
||||
VanillaSoundRig.set(actor, Entity.class, "level", level);
|
||||
VanillaSoundRig.set(actor, Entity.class, "position", Vec3.ZERO);
|
||||
VanillaSoundRig.set(actor, Entity.class, "bb", box(Vec3.ZERO, 1.8F));
|
||||
VanillaSoundRig.set(level, Lvl.class, "columns", new HashMap<BlockPos, Boolean>());
|
||||
VanillaSoundRig.set(actor, LocalPlayer.class, "minecraft", mc);
|
||||
underwater = new UnderwaterAmbientSoundHandler(actor, rig.manager);
|
||||
bubble = new BubbleColumnAmbientSoundHandler(actor);
|
||||
biome = new BiomeAmbientSoundsHandler(actor, rig.manager);
|
||||
}
|
||||
case "sounds" -> {
|
||||
AmbientSounds value = sounds(a);
|
||||
var system = EnvironmentAttributeSystem.builder()
|
||||
.addConstantLayer(EnvironmentAttributes.AMBIENT_SOUNDS, base -> value)
|
||||
.build();
|
||||
VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", system);
|
||||
}
|
||||
case "player" -> {
|
||||
// player x y z eyeHeight eyeInWater spectator removed lightMode
|
||||
VanillaSoundRig.set(actor, Entity.class, "position", new Vec3(d(a[1]), d(a[2]), d(a[3])));
|
||||
VanillaSoundRig.set(actor, Entity.class, "eyeHeight", f(a[4]));
|
||||
actor.eyeInWater = a[5].equals("1");
|
||||
actor.spectator = a[6].equals("1");
|
||||
VanillaSoundRig.set(actor, Entity.class, "removalReason", a[7].equals("1") ? Entity.RemovalReason.DISCARDED : null);
|
||||
level.mode = Integer.parseInt(a[8]);
|
||||
var at = new Vec3(d(a[1]), d(a[2]), d(a[3]));
|
||||
VanillaSoundRig.set(actor, Entity.class, "bb", box(at, f(a[9])));
|
||||
level.columns.clear();
|
||||
for (int i = 10; i < a.length; i++) {
|
||||
String[] c = a[i].split(",");
|
||||
level.columns.put(new BlockPos(Integer.parseInt(c[0]), Integer.parseInt(c[1]), Integer.parseInt(c[2])), c[3].equals("1"));
|
||||
}
|
||||
}
|
||||
case "volume" -> {
|
||||
rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2]));
|
||||
rig.manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]);
|
||||
}
|
||||
case "tick" -> {
|
||||
update.invoke(actor);
|
||||
underwater.tick();
|
||||
bubble.tick();
|
||||
biome.tick();
|
||||
rig.manager.tick(false);
|
||||
}
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
out.printf(" rand=%d mood=%08x underwater=%s delay=%d%n", peek(level.getRandom()), Float.floatToRawIntBits(biome.getMoodiness()),
|
||||
actor.isUnderWater(), (int) VanillaSoundRig.get(underwater, UnderwaterAmbientSoundHandler.class, "tickDelay"));
|
||||
var loops = (Map<Holder<SoundEvent>, BiomeAmbientSoundsHandler.LoopSoundInstance>) VanillaSoundRig.get(biome,
|
||||
BiomeAmbientSoundsHandler.class, "loopSounds");
|
||||
for (var e : loops.entrySet()) {
|
||||
var loop = e.getValue();
|
||||
out.printf(" loop %s fade=%d direction=%d stopped=%s active=%s%n", e.getKey().value().location(),
|
||||
(int) VanillaSoundRig.get(loop, BiomeAmbientSoundsHandler.LoopSoundInstance.class, "fade"),
|
||||
(int) VanillaSoundRig.get(loop, BiomeAmbientSoundsHandler.LoopSoundInstance.class, "fadeDirection"), loop.isStopped(),
|
||||
rig.manager.isActive(loop));
|
||||
}
|
||||
var playing = new ArrayList<String>();
|
||||
for (SoundInstance i : ((Map<SoundInstance, ChannelAccess.ChannelHandle>) instanceToChannel.get(rig.engine)).keySet()) {
|
||||
float volume = (float) VanillaSoundRig.get(i, AbstractSoundInstance.class, "volume");
|
||||
playing.add(String.format(" playing %s volume=%08x looping=%s relative=%s at=%s,%s,%s stopped=%s", i.getIdentifier(),
|
||||
Float.floatToRawIntBits(volume), i.isLooping(), i.isRelative(), bits(i.getX()), bits(i.getY()), bits(i.getZ()),
|
||||
i instanceof TickableSoundInstance t && t.isStopped()));
|
||||
}
|
||||
Collections.sort(playing);
|
||||
for (String p : playing) out.println(p);
|
||||
rig.flush(out);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.sounds.Music;
|
||||
import net.minecraft.sounds.Musics;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.world.attribute.*;
|
||||
import net.minecraft.world.clock.*;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* The audio environment attributes as the vanilla EnvironmentAttributeSystem
|
||||
* evaluates them from the vanilla data pack (dimension layer, the biome's
|
||||
* positional layer, the dimension timelines and weather layers):
|
||||
* BACKGROUND_MUSIC with BackgroundMusic.select for every creative/underwater
|
||||
* combination, MUSIC_VOLUME and AMBIENT_SOUNDS, for lines "dimension biome
|
||||
* ticks"; plus the Musics constants.
|
||||
*/
|
||||
public final class VanillaAudioAttributesOracle {
|
||||
static String music(Music m) {
|
||||
return m == null ? "-" : m.sound().value().location() + "," + m.minDelay() + "," + m.maxDelay() + "," + m.replaceCurrentMusic();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private static void addBiome(EnvironmentAttributeSystem.Builder b, EnvironmentAttribute attr, Biome biome) {
|
||||
b.addPositionalLayer(attr, (base, pos, w) -> biome.getAttributes().applyModifier(attr, base));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
var repo = ServerPacksSource.createVanillaTrustedRepository();
|
||||
repo.reload();
|
||||
repo.setSelected(List.of("vanilla"));
|
||||
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
|
||||
var layers = RegistryLayer.createRegistryAccess();
|
||||
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
|
||||
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
|
||||
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
var dimensions = world.lookupOrThrow(Registries.DIMENSION_TYPE);
|
||||
var biomes = world.lookupOrThrow(Registries.BIOME);
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
w.println("MENU " + music(Musics.MENU));
|
||||
w.println("CREDITS " + music(Musics.CREDITS));
|
||||
w.println("END_BOSS " + music(Musics.END_BOSS));
|
||||
w.println("CREATIVE " + music(Musics.CREATIVE));
|
||||
w.println("END " + music(Musics.END));
|
||||
w.println("UNDER_WATER " + music(Musics.UNDER_WATER));
|
||||
w.println("GAME " + music(Musics.GAME));
|
||||
for (String line : Files.readAllLines(Path.of(args[0]), StandardCharsets.UTF_8)) {
|
||||
String[] f = line.split(" ");
|
||||
DimensionType dim = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(f[0]))).value();
|
||||
Biome biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(f[1]))).value();
|
||||
long ticks = Long.parseLong(f[2]);
|
||||
ClockManager clocks = h -> new ClockInstance() {
|
||||
public long totalTicks() { return ticks; }
|
||||
public float partialTick() { return 0.0F; }
|
||||
public float rate() { return 1.0F; }
|
||||
public boolean isPaused() { return false; }
|
||||
};
|
||||
var b = EnvironmentAttributeSystem.builder();
|
||||
b.addConstantLayer(dim.attributes());
|
||||
for (EnvironmentAttribute<?> attr : biome.getAttributes().keySet()) addBiome(b, attr, biome);
|
||||
dim.timelines().forEach(t -> b.addTimelineLayer(t, clocks));
|
||||
if (dim.hasSkyLight() && !dim.hasCeiling()) {
|
||||
WeatherAttributes.addBuiltinLayers(b, new WeatherAttributes.WeatherAccess() {
|
||||
public float rainLevel() { return 0.0F; }
|
||||
public float thunderLevel() { return 0.0F; }
|
||||
});
|
||||
}
|
||||
var system = b.build();
|
||||
BackgroundMusic bg = system.getValue(EnvironmentAttributes.BACKGROUND_MUSIC, Vec3.ZERO);
|
||||
StringBuilder sb = new StringBuilder(line);
|
||||
sb.append(" default=").append(music(bg.defaultMusic().orElse(null)))
|
||||
.append(" creative=").append(music(bg.creativeMusic().orElse(null)))
|
||||
.append(" underwater=").append(music(bg.underwaterMusic().orElse(null)));
|
||||
for (boolean creative : new boolean[]{false, true}) {
|
||||
for (boolean underwater : new boolean[]{false, true}) {
|
||||
sb.append(" select=").append(music(bg.select(creative, underwater).orElse(null)));
|
||||
}
|
||||
}
|
||||
sb.append(String.format(" volume=%08x", Float.floatToRawIntBits(system.getValue(EnvironmentAttributes.MUSIC_VOLUME, Vec3.ZERO))));
|
||||
AmbientSounds ambient = system.getValue(EnvironmentAttributes.AMBIENT_SOUNDS, Vec3.ZERO);
|
||||
sb.append(" loop=").append(ambient.loop().map(s -> s.value().location().toString()).orElse("-"));
|
||||
sb.append(" mood=").append(ambient.mood().map(m -> m.soundEvent().value().location() + "," + m.tickDelay() + ","
|
||||
+ m.blockSearchExtent() + "," + String.format("%016x", Double.doubleToRawLongBits(m.soundPositionOffset()))).orElse("-"));
|
||||
for (AmbientAdditionsSettings a : ambient.additions()) {
|
||||
sb.append(" addition=").append(a.soundEvent().value().location()).append(String.format(",%016x", Double.doubleToRawLongBits(a.tickChance())));
|
||||
}
|
||||
w.println(sb);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.player.ClientInput;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.world.effect.*;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.player.Input;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
import net.minecraft.world.phys.*;
|
||||
import net.minecraft.world.phys.shapes.VoxelShape;
|
||||
import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*;
|
||||
|
||||
/**
|
||||
* Runs the real LocalPlayer.updateAutoJump (with canAutoJump, getBlockJumpFactor,
|
||||
* CollisionGetter.getCollisions/BlockCollisions and the player's collision
|
||||
* context) on a LocalPlayer shell standing in an independently constructed copy
|
||||
* of the client's resident test scene, with each case's blocks placed.
|
||||
*/
|
||||
public final class VanillaAutoJumpOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T make(Class<T> type) throws Exception {
|
||||
return (T) allocate.invoke(unsafe, type);
|
||||
}
|
||||
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
Field f = type.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
static float f(JsonElement v) {
|
||||
return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(), 16));
|
||||
}
|
||||
|
||||
static double d(JsonElement v) {
|
||||
return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(), 16));
|
||||
}
|
||||
|
||||
static Map<Long, Chunk> chunks;
|
||||
|
||||
static final class AutoLevel extends net.minecraft.server.level.ServerLevel {
|
||||
AutoLevel() {
|
||||
super(null, null, null, null, null, null, false, 0L, List.of(), false);
|
||||
}
|
||||
|
||||
@Override public BlockState getBlockState(BlockPos p) { return chunks.get(key(p.getX() >> 4, p.getZ() >> 4)).getBlockState(p); }
|
||||
@Override public BlockGetter getChunkForCollisions(int x, int z) { return chunks.get(key(x, z)); }
|
||||
@Override public List<VoxelShape> getEntityCollisions(Entity entity, AABB bounds) { return List.of(); }
|
||||
}
|
||||
|
||||
static final class Jumper extends LocalPlayer {
|
||||
boolean ground;
|
||||
net.minecraft.world.entity.ai.attributes.AttributeMap attributes;
|
||||
|
||||
Jumper() {
|
||||
super(null, null, null, null, null, Input.EMPTY, false, null, null);
|
||||
}
|
||||
|
||||
@Override public boolean onGround() { return ground; }
|
||||
@Override public net.minecraft.world.entity.ai.attributes.AttributeMap getAttributes() { return attributes; }
|
||||
@Override public ItemStack getMainHandItem() { return ItemStack.EMPTY; }
|
||||
@Override public ItemStack getItemBySlot(EquipmentSlot slot) { return ItemStack.EMPTY; }
|
||||
}
|
||||
|
||||
static <T extends Comparable<T>> BlockState with(BlockState state, Property<T> key, String value) {
|
||||
return state.setValue(key, key.getValue(value).orElseThrow());
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
unsafe = field(u, "theUnsafe").get(null);
|
||||
allocate = u.getMethod("allocateInstance", Class.class);
|
||||
Path resources = Path.of(args[2]);
|
||||
VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(resources.resolve("block-tags.json"))).getAsJsonObject());
|
||||
var description = JsonParser.parseString(Files.readString(Path.of(args[3]))).getAsJsonObject();
|
||||
var trace = new Trace();
|
||||
trace.out = new PrintWriter(OutputStream.nullOutputStream());
|
||||
trace.fail = -1;
|
||||
chunks = VanillaSceneCollisionOracle.scene(description, trace);
|
||||
AutoLevel level = make(AutoLevel.class);
|
||||
var update = LocalPlayer.class.getDeclaredMethod("updateAutoJump", float.class, float.class);
|
||||
update.setAccessible(true);
|
||||
var enabled = field(LocalPlayer.class, "autoJumpEnabled");
|
||||
var time = field(LocalPlayer.class, "autoJumpTime");
|
||||
var moveVector = field(ClientInput.class, "moveVector");
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
int n = 0;
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
out.println("== " + n++);
|
||||
var restore = new ArrayList<Object[]>();
|
||||
for (var e : c.getAsJsonArray("blocks")) {
|
||||
var b = e.getAsJsonArray();
|
||||
var pos = new BlockPos(b.get(0).getAsInt(), b.get(1).getAsInt(), b.get(2).getAsInt());
|
||||
BlockState state = VanillaSceneCollisionOracle.state(b.get(3).getAsString());
|
||||
for (var p : b.get(4).getAsJsonObject().entrySet()) {
|
||||
state = with(state, Objects.requireNonNull(state.getBlock().getStateDefinition().getProperty(p.getKey())), p.getValue().getAsString());
|
||||
}
|
||||
restore.add(new Object[] {pos, level.getBlockState(pos)});
|
||||
VanillaSceneCollisionOracle.put(chunks, pos.getX(), pos.getY(), pos.getZ(), state);
|
||||
}
|
||||
var p = c.getAsJsonObject("player");
|
||||
Jumper player = make(Jumper.class);
|
||||
field(Entity.class, "level").set(player, level);
|
||||
var position = new Vec3(d(p.getAsJsonArray("pos").get(0)), d(p.getAsJsonArray("pos").get(1)), d(p.getAsJsonArray("pos").get(2)));
|
||||
field(Entity.class, "position").set(player, position);
|
||||
field(Entity.class, "blockPosition").set(player, BlockPos.containing(position));
|
||||
player.mainSupportingBlockPos = Optional.empty();
|
||||
var dimensions = EntityDimensions.scalable(f(p.get("width")), f(p.get("height")));
|
||||
field(Entity.class, "dimensions").set(player, dimensions);
|
||||
player.setBoundingBox(dimensions.makeBoundingBox(position));
|
||||
player.ground = p.get("ground").getAsBoolean();
|
||||
field(Entity.class, "yRot").setFloat(player, f(p.get("yr")));
|
||||
field(Entity.class, "xRot").setFloat(player, f(p.get("xr")));
|
||||
// Player.getSpeed reads the movement speed attribute.
|
||||
player.attributes = new net.minecraft.world.entity.ai.attributes.AttributeMap(Player.createAttributes().build());
|
||||
player.attributes.getInstance(net.minecraft.world.entity.ai.attributes.Attributes.MOVEMENT_SPEED).setBaseValue(f(p.get("speed")));
|
||||
var input = new ClientInput();
|
||||
boolean shift = p.get("shift").getAsBoolean();
|
||||
input.keyPresses = new Input(false, false, false, false, false, shift, false);
|
||||
var move = p.getAsJsonArray("move");
|
||||
moveVector.set(input, new Vec2(f(move.get(0)), f(move.get(1))));
|
||||
player.input = input;
|
||||
var effects = new HashMap<net.minecraft.core.Holder<MobEffect>, MobEffectInstance>();
|
||||
if (!p.get("boost").isJsonNull()) {
|
||||
effects.put(MobEffects.JUMP_BOOST, new MobEffectInstance(MobEffects.JUMP_BOOST, 100, p.get("boost").getAsInt()));
|
||||
}
|
||||
field(LivingEntity.class, "activeEffects").set(player, effects);
|
||||
enabled.setBoolean(player, p.get("enabled").getAsBoolean());
|
||||
time.setInt(player, p.get("time").getAsInt());
|
||||
update.invoke(player, f(c.get("xa")), f(c.get("za")));
|
||||
out.println("jump " + time.getInt(player));
|
||||
Collections.reverse(restore);
|
||||
for (var r : restore) {
|
||||
var pos = (BlockPos) r[0];
|
||||
VanillaSceneCollisionOracle.put(chunks, pos.getX(), pos.getY(), pos.getZ(), (BlockState) r[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.*;
|
||||
import net.minecraft.client.entity.ClientAvatarState;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.client.renderer.state.GameRenderState;
|
||||
import net.minecraft.client.renderer.state.level.CameraRenderState;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.attribute.EnvironmentAttributeProbe;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.ai.attributes.*;
|
||||
import net.minecraft.world.entity.player.*;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.*;
|
||||
import net.minecraft.world.phys.*;
|
||||
import net.minecraft.world.phys.shapes.*;
|
||||
import org.joml.Matrix4f;
|
||||
|
||||
/**
|
||||
* Drives the real Camera (tick, tickFov, alignWithEntity with getMaxZoom over
|
||||
* Level.clip, calculateFov, calculateHudFov), AbstractClientPlayer
|
||||
* .getFieldOfViewModifier and updateBob, ClientAvatarState and
|
||||
* GameRenderer.bobHurt/bobView with scripted entity states, and prints every
|
||||
* observable bit-exactly. Entities, the level and the renderer are
|
||||
* uninitialised shells (Unsafe) with controlled queries; block visual shapes
|
||||
* come from the case.
|
||||
*/
|
||||
public final class VanillaCameraOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T make(Class<T> type) throws Exception {
|
||||
return (T) allocate.invoke(unsafe, type);
|
||||
}
|
||||
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
Field f = type.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
static Method method(Class<?> type, String name, Class<?>... args) throws Exception {
|
||||
Method m = type.getDeclaredMethod(name, args);
|
||||
m.setAccessible(true);
|
||||
return m;
|
||||
}
|
||||
|
||||
static float f(JsonElement v) {
|
||||
return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(), 16));
|
||||
}
|
||||
|
||||
static double d(JsonElement v) {
|
||||
return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(), 16));
|
||||
}
|
||||
|
||||
static String fb(float v) {
|
||||
return String.format("%08x", Float.isNaN(v) ? 0x7fc00000 : Float.floatToRawIntBits(v));
|
||||
}
|
||||
|
||||
static String db(double v) {
|
||||
return String.format("%016x", Double.isNaN(v) ? 0x7ff8000000000000L : Double.doubleToRawLongBits(v));
|
||||
}
|
||||
|
||||
static Vec3 vec(JsonElement v) {
|
||||
var a = v.getAsJsonArray();
|
||||
return new Vec3(d(a.get(0)), d(a.get(1)), d(a.get(2)));
|
||||
}
|
||||
|
||||
// ---- level with controlled visual shapes ----------------------------------------------
|
||||
static final class State extends BlockState {
|
||||
VoxelShape visual;
|
||||
|
||||
State() {
|
||||
super(null, null, null);
|
||||
}
|
||||
|
||||
@Override public VoxelShape getVisualShape(BlockGetter w, BlockPos p, CollisionContext c) { return visual; }
|
||||
@Override public VoxelShape getInteractionShape(BlockGetter w, BlockPos p) { return Shapes.empty(); }
|
||||
}
|
||||
|
||||
static final class Level extends net.minecraft.server.level.ServerLevel {
|
||||
Map<BlockPos, State> cells = new HashMap<>();
|
||||
State air;
|
||||
|
||||
Level() {
|
||||
super(null, null, null, null, null, null, false, 0L, List.of(), false);
|
||||
}
|
||||
|
||||
@Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, air); }
|
||||
@Override public FluidState getFluidState(BlockPos p) { return Fluids.EMPTY.defaultFluidState(); }
|
||||
}
|
||||
|
||||
static final class NoProbe extends EnvironmentAttributeProbe {
|
||||
@Override public void tick(net.minecraft.world.level.Level level, Vec3 position) { }
|
||||
}
|
||||
|
||||
static final class StubCamera extends Camera {
|
||||
net.minecraft.world.level.material.FogType fluid = net.minecraft.world.level.material.FogType.NONE;
|
||||
|
||||
@Override public net.minecraft.world.level.material.FogType getFluidInCamera() { return fluid; }
|
||||
}
|
||||
|
||||
// ---- camera entities ----------------------------------------------------------------
|
||||
static final class StubPlayer extends LocalPlayer {
|
||||
AttributeMap attributes;
|
||||
boolean using, dead, sleeping, swimming, ground;
|
||||
ItemStack useItem = ItemStack.EMPTY;
|
||||
int useTicks;
|
||||
Direction bed;
|
||||
Vec3 motion = Vec3.ZERO;
|
||||
|
||||
StubPlayer() {
|
||||
super(null, null, null, null, null, Input.EMPTY, false, null, null);
|
||||
}
|
||||
|
||||
@Override public AttributeMap getAttributes() { return attributes; }
|
||||
@Override public boolean isUsingItem() { return using; }
|
||||
@Override public ItemStack getUseItem() { return useItem; }
|
||||
@Override public int getTicksUsingItem() { return useTicks; }
|
||||
@Override public boolean isDeadOrDying() { return dead; }
|
||||
@Override public boolean isSleeping() { return sleeping; }
|
||||
@Override public Direction getBedOrientation() { return bed; }
|
||||
@Override public boolean isDescending() { return false; }
|
||||
@Override public ItemStack getMainHandItem() { return ItemStack.EMPTY; }
|
||||
@Override public boolean isSwimming() { return swimming; }
|
||||
@Override public boolean onGround() { return ground; }
|
||||
@Override public Vec3 getDeltaMovement() { return motion; }
|
||||
@Override public boolean isSpectator() { return false; }
|
||||
}
|
||||
|
||||
static final class StubMarker extends Marker {
|
||||
StubMarker() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
@Override public boolean isDescending() { return false; }
|
||||
}
|
||||
|
||||
static Minecraft shell;
|
||||
static Options options;
|
||||
static Field position, xRot, yRot, eyeHeight, vehicle, abilities;
|
||||
static Constructor<ItemStack> stack;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
unsafe = field(u, "theUnsafe").get(null);
|
||||
allocate = u.getMethod("allocateInstance", Class.class);
|
||||
shell = make(Minecraft.class);
|
||||
field(Minecraft.class, "fixerUpper").set(shell, net.minecraft.util.datafix.DataFixers.getDataFixer());
|
||||
field(Minecraft.class, "instance").set(null, shell);
|
||||
options = new Options(shell, Files.createTempDirectory("opts").toFile());
|
||||
field(Minecraft.class, "options").set(shell, options);
|
||||
position = field(Entity.class, "position");
|
||||
xRot = field(Entity.class, "xRot");
|
||||
yRot = field(Entity.class, "yRot");
|
||||
eyeHeight = field(Entity.class, "eyeHeight");
|
||||
vehicle = field(Entity.class, "vehicle");
|
||||
abilities = field(Player.class, "abilities");
|
||||
stack = ItemStack.class.getDeclaredConstructor(Holder.class, int.class, net.minecraft.core.component.PatchedDataComponentMap.class);
|
||||
stack.setAccessible(true);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
int n = 0;
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
out.println("== " + n++);
|
||||
switch (c.get("t").getAsString()) {
|
||||
case "fov" -> out.println(fb(player(c).getFieldOfViewModifier(c.get("fp").getAsBoolean(), f(c.get("scale")))));
|
||||
case "camera" -> camera(c, out);
|
||||
case "bob" -> bob(c, out);
|
||||
case "avatar" -> avatar(c, out);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
static AttributeMap attributes(double scale, double distance, double speed) {
|
||||
var map = new AttributeMap(Player.createAttributes().build());
|
||||
map.getInstance(Attributes.SCALE).setBaseValue(scale);
|
||||
map.getInstance(Attributes.CAMERA_DISTANCE).setBaseValue(distance);
|
||||
map.getInstance(Attributes.MOVEMENT_SPEED).setBaseValue(speed);
|
||||
return map;
|
||||
}
|
||||
|
||||
/** A player shell from the "fov" fields of a case or an entity op. */
|
||||
static StubPlayer player(JsonObject c) throws Exception {
|
||||
StubPlayer p = make(StubPlayer.class);
|
||||
fill(p, c);
|
||||
return p;
|
||||
}
|
||||
|
||||
static void fill(StubPlayer p, JsonObject c) throws Exception {
|
||||
var a = new Abilities();
|
||||
a.flying = c.get("flying").getAsBoolean();
|
||||
a.setWalkingSpeed(f(c.get("ws")));
|
||||
abilities.set(p, a);
|
||||
double scale = c.has("scale_attr") ? d(c.get("scale_attr")) : 1.0;
|
||||
double distance = c.has("dist") ? d(c.get("dist")) : 4.0;
|
||||
p.attributes = attributes(scale, distance, d(c.get("speed")));
|
||||
var use = c.get("use");
|
||||
p.using = !use.isJsonNull();
|
||||
if (p.using) {
|
||||
var u = use.getAsJsonArray();
|
||||
Item item = switch (u.get(0).getAsString()) {
|
||||
case "bow" -> Items.BOW;
|
||||
case "spyglass" -> Items.SPYGLASS;
|
||||
default -> Items.STICK;
|
||||
};
|
||||
p.useItem = stack.newInstance(Holder.direct(item), 1,
|
||||
new net.minecraft.core.component.PatchedDataComponentMap(net.minecraft.core.component.DataComponentMap.EMPTY));
|
||||
p.useTicks = u.get(1).getAsInt();
|
||||
}
|
||||
}
|
||||
|
||||
static void camera(JsonObject c, PrintWriter out) throws Exception {
|
||||
var level = make(Level.class);
|
||||
level.cells = new HashMap<>();
|
||||
level.air = make(State.class);
|
||||
level.air.visual = Shapes.empty();
|
||||
for (var e : c.getAsJsonObject("cells").entrySet()) {
|
||||
var at = e.getKey().split(" ");
|
||||
var s = make(State.class);
|
||||
VoxelShape shape = Shapes.empty();
|
||||
for (var b : e.getValue().getAsJsonArray()) {
|
||||
var a = b.getAsJsonArray();
|
||||
shape = Shapes.or(shape, Shapes.box(d(a.get(0)), d(a.get(1)), d(a.get(2)), d(a.get(3)), d(a.get(4)), d(a.get(5))));
|
||||
}
|
||||
s.visual = shape;
|
||||
level.cells.put(new BlockPos(Integer.parseInt(at[0]), Integer.parseInt(at[1]), Integer.parseInt(at[2])), s);
|
||||
}
|
||||
options.fov().set(c.get("fov").getAsInt());
|
||||
options.fovEffectScale().set(d(c.get("effect")));
|
||||
options.setCameraType(CameraType.values()[c.get("type").getAsInt()]);
|
||||
var camera = new StubCamera();
|
||||
field(Camera.class, "attributeProbe").set(camera, new NoProbe());
|
||||
field(Camera.class, "level").set(camera, level);
|
||||
GameRenderer renderer = make(GameRenderer.class);
|
||||
field(GameRenderer.class, "mainCamera").set(renderer, camera);
|
||||
field(Minecraft.class, "gameRenderer").set(shell, renderer);
|
||||
var align = method(Camera.class, "alignWithEntity", float.class);
|
||||
var fov = method(Camera.class, "calculateFov", float.class);
|
||||
var hud = method(Camera.class, "calculateHudFov", float.class);
|
||||
var panoramic = field(Camera.class, "isPanoramicMode");
|
||||
var eye = field(Camera.class, "eyeHeight");
|
||||
var eyeOld = field(Camera.class, "eyeHeightOld");
|
||||
var mod = field(Camera.class, "fovModifier");
|
||||
var modOld = field(Camera.class, "oldFovModifier");
|
||||
Entity entity = null;
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
switch (op.get(0).getAsString()) {
|
||||
case "entity" -> {
|
||||
var s = op.get(1).getAsJsonObject();
|
||||
entity = entity(s, entity);
|
||||
camera.setEntity(entity);
|
||||
out.println("entity");
|
||||
}
|
||||
case "type" -> {
|
||||
options.setCameraType(CameraType.values()[op.get(1).getAsInt()]);
|
||||
out.println("type");
|
||||
}
|
||||
case "tick" -> {
|
||||
camera.tick();
|
||||
out.println("tick " + fb(eye.getFloat(camera)) + " " + fb(eyeOld.getFloat(camera)) + " "
|
||||
+ fb(mod.getFloat(camera)) + " " + fb(modOld.getFloat(camera)));
|
||||
}
|
||||
case "frame" -> {
|
||||
float pt = f(op.get(1));
|
||||
camera.fluid = net.minecraft.world.level.material.FogType.valueOf(
|
||||
new String[] {"NONE", "WATER", "LAVA", "POWDER_SNOW"}[op.get(2).getAsInt()]);
|
||||
panoramic.setBoolean(camera, op.get(3).getAsBoolean());
|
||||
align.invoke(camera, pt);
|
||||
float fv = (float) fov.invoke(camera, pt);
|
||||
float hv = (float) hud.invoke(camera, pt);
|
||||
var p = camera.position();
|
||||
var q = camera.rotation();
|
||||
var fw = camera.forwardVector();
|
||||
var up = camera.upVector();
|
||||
var left = camera.leftVector();
|
||||
out.println("frame " + db(p.x) + " " + db(p.y) + " " + db(p.z) + " " + fb(camera.xRot()) + " " + fb(camera.yRot())
|
||||
+ " " + fb(q.x) + " " + fb(q.y) + " " + fb(q.z) + " " + fb(q.w)
|
||||
+ " " + fb(fw.x()) + " " + fb(fw.y()) + " " + fb(fw.z())
|
||||
+ " " + fb(up.x()) + " " + fb(up.y()) + " " + fb(up.z())
|
||||
+ " " + fb(left.x()) + " " + fb(left.y()) + " " + fb(left.z())
|
||||
+ " " + camera.isDetached() + " " + fb(fv) + " " + fb(hv));
|
||||
}
|
||||
default -> throw new IllegalArgumentException(op.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Applies an entity op: a player (with fov fields) or a non-living marker. */
|
||||
static Entity entity(JsonObject s, Entity previous) throws Exception {
|
||||
Entity entity;
|
||||
if (s.get("kind").getAsString().equals("player")) {
|
||||
StubPlayer p = previous instanceof StubPlayer old ? old : make(StubPlayer.class);
|
||||
fill(p, s);
|
||||
p.dead = !s.get("dead").isJsonNull();
|
||||
if (p.dead) {
|
||||
p.deathTime = s.get("dead").getAsInt();
|
||||
}
|
||||
p.sleeping = !s.get("sleeping").isJsonNull();
|
||||
p.bed = null;
|
||||
if (p.sleeping && !s.get("sleeping").getAsJsonArray().get(0).isJsonNull()) {
|
||||
p.bed = Direction.from2DDataValue(s.get("sleeping").getAsJsonArray().get(0).getAsInt());
|
||||
}
|
||||
var mount = s.get("mount");
|
||||
if (mount.isJsonNull()) {
|
||||
vehicle.set(p, null);
|
||||
} else {
|
||||
StubPlayer m = make(StubPlayer.class);
|
||||
var a = mount.getAsJsonArray();
|
||||
m.attributes = attributes(d(a.get(0)), d(a.get(1)), 0.1);
|
||||
vehicle.set(p, m);
|
||||
}
|
||||
entity = p;
|
||||
} else {
|
||||
entity = previous instanceof StubMarker old ? old : make(StubMarker.class);
|
||||
}
|
||||
position.set(entity, vec(s.get("pos")));
|
||||
var prev = vec(s.get("prev"));
|
||||
entity.xo = prev.x;
|
||||
entity.yo = prev.y;
|
||||
entity.zo = prev.z;
|
||||
xRot.setFloat(entity, f(s.get("xr")));
|
||||
yRot.setFloat(entity, f(s.get("yr")));
|
||||
entity.xRotO = f(s.get("xro"));
|
||||
entity.yRotO = f(s.get("yro"));
|
||||
eyeHeight.setFloat(entity, f(s.get("eye")));
|
||||
return entity;
|
||||
}
|
||||
|
||||
static void bob(JsonObject c, PrintWriter out) throws Exception {
|
||||
GameRenderer renderer = make(GameRenderer.class);
|
||||
var state = new GameRenderState();
|
||||
field(GameRenderer.class, "gameRenderState").set(renderer, state);
|
||||
state.optionsRenderState.damageTiltStrength = d(c.get("tilt"));
|
||||
state.optionsRenderState.bobView = c.get("view").getAsBoolean();
|
||||
var camera = new CameraRenderState();
|
||||
var es = camera.entityRenderState;
|
||||
var living = c.get("living");
|
||||
es.isLiving = !living.isJsonNull();
|
||||
if (es.isLiving) {
|
||||
var l = living.getAsJsonObject();
|
||||
es.hurtTime = f(l.get("hurt"));
|
||||
es.hurtDuration = l.get("duration").getAsInt();
|
||||
es.hurtDir = f(l.get("dir"));
|
||||
es.isDeadOrDying = !l.get("death").isJsonNull();
|
||||
if (es.isDeadOrDying) {
|
||||
es.deathTime = f(l.get("death"));
|
||||
}
|
||||
}
|
||||
var player = c.get("player");
|
||||
es.isPlayer = !player.isJsonNull();
|
||||
if (es.isPlayer) {
|
||||
es.backwardsInterpolatedWalkDistance = f(player.getAsJsonArray().get(0));
|
||||
es.bob = f(player.getAsJsonArray().get(1));
|
||||
}
|
||||
var stack = new PoseStack();
|
||||
method(GameRenderer.class, "bobHurt", CameraRenderState.class, PoseStack.class).invoke(renderer, camera, stack);
|
||||
if (state.optionsRenderState.bobView) {
|
||||
method(GameRenderer.class, "bobView", CameraRenderState.class, PoseStack.class).invoke(renderer, camera, stack);
|
||||
}
|
||||
Matrix4f m = stack.last().pose();
|
||||
var sb = new StringBuilder("bob");
|
||||
for (int col = 0; col < 4; col++) {
|
||||
for (int row = 0; row < 4; row++) {
|
||||
sb.append(' ').append(fb(m.get(col, row)));
|
||||
}
|
||||
}
|
||||
sb.append(' ').append(m.properties());
|
||||
out.println(sb);
|
||||
}
|
||||
|
||||
static void avatar(JsonObject c, PrintWriter out) throws Exception {
|
||||
StubPlayer p = make(StubPlayer.class);
|
||||
var state = new ClientAvatarState();
|
||||
field(net.minecraft.client.player.AbstractClientPlayer.class, "clientAvatarState").set(p, state);
|
||||
var updateBob = method(net.minecraft.client.player.AbstractClientPlayer.class, "updateBob");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
switch (op.get(0).getAsString()) {
|
||||
case "tick" -> state.tick(Vec3.ZERO, Vec3.ZERO);
|
||||
case "move" -> state.addWalkDistance(Mth.length(f(op.get(1)), f(op.get(2))) * 0.6F);
|
||||
case "bob" -> {
|
||||
p.ground = op.get(1).getAsBoolean();
|
||||
p.dead = op.get(2).getAsBoolean();
|
||||
p.swimming = op.get(3).getAsBoolean();
|
||||
p.motion = vec(op.get(4));
|
||||
updateBob.invoke(p);
|
||||
}
|
||||
case "reset" -> state.resetBob();
|
||||
case "frame" -> {
|
||||
float pt = f(op.get(1));
|
||||
out.println("frame " + fb(state.getInterpolatedBob(pt)) + " " + fb(state.getBackwardsInterpolatedWalkDistance(pt)));
|
||||
continue;
|
||||
}
|
||||
default -> throw new IllegalArgumentException(op.toString());
|
||||
}
|
||||
out.println(op.get(0).getAsString());
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.mojang.brigadier.tree.ArgumentCommandNode;
|
||||
import com.mojang.brigadier.tree.CommandNode;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.synchronization.SuggestionProviders;
|
||||
|
||||
/**
|
||||
* Lists the argument nodes of vanilla's full command tree (Commands with
|
||||
* CommandSelection.ALL, the tree the commands report shows) that carry a
|
||||
* custom suggestion provider, with the provider's network name
|
||||
* (SuggestionProviders.getName: ask_server unless it is one of the named
|
||||
* client-side providers). ClientboundCommandsPacket sends that name; the
|
||||
* report does not include it. One line per node: the path of node names
|
||||
* from the root, space separated, a tab, the provider id.
|
||||
*/
|
||||
public final class VanillaCommandSuggestionsExporter {
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
Commands commands = new Commands(Commands.CommandSelection.ALL, Commands.createValidationContext(ParityData.lookup));
|
||||
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0])))) {
|
||||
walk(commands.getDispatcher().getRoot(), "", out);
|
||||
}
|
||||
}
|
||||
|
||||
static void walk(CommandNode<CommandSourceStack> node, String path, PrintWriter out) {
|
||||
for (CommandNode<CommandSourceStack> child : node.getChildren()) {
|
||||
String childPath = path.isEmpty() ? child.getName() : path + " " + child.getName();
|
||||
if (child instanceof ArgumentCommandNode<CommandSourceStack, ?> arg && arg.getCustomSuggestions() != null) {
|
||||
out.println(childPath + "\t" + SuggestionProviders.getName(arg.getCustomSuggestions()));
|
||||
}
|
||||
walk(child, childPath, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.ReloadableServerRegistries;
|
||||
import net.minecraft.server.ReloadableServerResources;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.DifficultyInstance;
|
||||
import net.minecraft.world.RandomSequences;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
import net.minecraft.world.damagesource.DamageSources;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.ai.attributes.Attributes;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.DyeColor;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.entity.EntityTypeTest;
|
||||
import net.minecraft.world.level.gamerules.GameRules;
|
||||
import net.minecraft.world.level.levelgen.WorldGenSettings;
|
||||
import net.minecraft.world.level.levelgen.WorldOptions;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
|
||||
/**
|
||||
* Original oracle: entity death drops. Each input line describes a victim, its
|
||||
* equipment and state, a killer and a damage source; the oracle creates the
|
||||
* real entities on a stand-in ServerLevel (whose addFreshEntity records the
|
||||
* spawned item entities and experience orbs) and runs LivingEntity.die's drop
|
||||
* step: the source entity's killedEntity hook, then dropAllDeathLoot (loot
|
||||
* table with the world's random sequence, dropCustomDeathLoot with the entity
|
||||
* random, dropEquipment, dropExperience). Loot table randoms come from a fresh
|
||||
* RandomSequences per case; each case kills `kills` identical victims in turn.
|
||||
*/
|
||||
public final class VanillaEntityDeathLootOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate, putObject, objectFieldOffset;
|
||||
|
||||
static Object alloc(Class<?> c) throws Exception { return allocate.invoke(unsafe, c); }
|
||||
|
||||
static void put(Object target, Class<?> owner, String field, Object value) throws Exception {
|
||||
Field f = owner.getDeclaredField(field);
|
||||
long offset = (long) objectFieldOffset.invoke(unsafe, f);
|
||||
putObject.invoke(unsafe, target, offset, value);
|
||||
}
|
||||
|
||||
static final class Lvl extends ServerLevel {
|
||||
Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); }
|
||||
MinecraftServer fake;
|
||||
RegistryAccess registries;
|
||||
GameRules rules;
|
||||
List<String> out;
|
||||
int next = 1;
|
||||
@Override public MinecraftServer getServer() { return fake; }
|
||||
@Override public RegistryAccess registryAccess() { return registries; }
|
||||
@Override public net.minecraft.world.Difficulty getDifficulty() { return net.minecraft.world.Difficulty.NORMAL; }
|
||||
@Override public long getGameTime() { return 0L; }
|
||||
@Override public int getNextEntityId() { return next++; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
|
||||
@Override public GameRules getGameRules() { return rules; }
|
||||
@Override public boolean addFreshEntity(Entity entity) {
|
||||
if (entity instanceof ItemEntity item) out.add("drop " + stack(item.getItem()));
|
||||
else if (entity instanceof ExperienceOrb orb) out.add("orb " + orb.getValue());
|
||||
else out.add("entity " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()));
|
||||
return true;
|
||||
}
|
||||
@Override public <T extends Entity> List<T> getEntities(EntityTypeTest<Entity, T> type, AABB bb, Predicate<? super T> selector) { return new ArrayList<>(); }
|
||||
net.minecraft.world.attribute.EnvironmentAttributeSystem attributes;
|
||||
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; }
|
||||
@Override public int getSeaLevel() { return 63; }
|
||||
@Override public net.minecraft.world.entity.raid.Raid getRaidAt(BlockPos pos) { return null; }
|
||||
@Override public net.minecraft.world.level.BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return null; }
|
||||
@Override public List<net.minecraft.world.phys.shapes.VoxelShape> getEntityCollisions(Entity source, AABB area) { return List.of(); }
|
||||
@Override public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { return new DifficultyInstance(net.minecraft.world.Difficulty.NORMAL, 0L, 0L, 0.0F); }
|
||||
}
|
||||
|
||||
static final class OraclePlayer extends Player {
|
||||
OraclePlayer(Level level) { super(level, new GameProfile(new UUID(1L, 2L), "oracle")); }
|
||||
@Override public GameType gameMode() { return GameType.SURVIVAL; }
|
||||
@Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return net.minecraft.world.item.component.ResolvableProfile.createResolved(this.getGameProfile()); }
|
||||
}
|
||||
|
||||
static String stack(ItemStack stack) {
|
||||
StringBuilder line = new StringBuilder(BuiltInRegistries.ITEM.getKey(stack.getItem()) + " " + stack.getCount());
|
||||
if (stack.getDamageValue() != 0) line.append(" damage=").append(stack.getDamageValue());
|
||||
var enchantments = stack.getOrDefault(DataComponents.ENCHANTMENTS, net.minecraft.world.item.enchantment.ItemEnchantments.EMPTY);
|
||||
for (var e : enchantments.entrySet()) line.append(" ench=").append(e.getKey().unwrapKey().get().identifier()).append(':').append(e.getIntValue());
|
||||
var potion = stack.get(DataComponents.POTION_CONTENTS);
|
||||
if (potion != null && potion.potion().isPresent()) line.append(" potion=").append(potion.potion().get().unwrapKey().get().identifier());
|
||||
var ominous = stack.get(DataComponents.OMINOUS_BOTTLE_AMPLIFIER);
|
||||
if (ominous != null) line.append(" ominous=").append(ominous.value());
|
||||
return line.toString();
|
||||
}
|
||||
|
||||
static Map<String, String> parse(String line) {
|
||||
Map<String, String> m = new LinkedHashMap<>();
|
||||
for (String token : line.trim().split("\\s+")) {
|
||||
int eq = token.indexOf('=');
|
||||
if (eq < 0) m.put("name", token); else m.put(token.substring(0, eq), token.substring(eq + 1));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class);
|
||||
objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class);
|
||||
|
||||
var repo = ServerPacksSource.createVanillaTrustedRepository();
|
||||
repo.reload();
|
||||
repo.setSelected(List.of("vanilla"));
|
||||
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
|
||||
var layers = RegistryLayer.createRegistryAccess();
|
||||
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
|
||||
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
|
||||
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
|
||||
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world);
|
||||
var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
|
||||
HolderLookup.Provider lookup = loaded.lookupWithUpdatedTags();
|
||||
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply);
|
||||
RegistryAccess access = loaded.layers().compositeAccess();
|
||||
|
||||
// A server that only answers reloadableRegistries, getRandomSequence and debug subscribers.
|
||||
MinecraftServer server = (MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class);
|
||||
put(server, MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class));
|
||||
ReloadableServerResources managers = (ReloadableServerResources) alloc(ReloadableServerResources.class);
|
||||
put(managers, ReloadableServerResources.class, "fullRegistryHolder", new ReloadableServerRegistries.Holder(lookup));
|
||||
Class<?> holderRecord = Class.forName("net.minecraft.server.MinecraftServer$ReloadableResources");
|
||||
Constructor<?> rr = holderRecord.getDeclaredConstructors()[0];
|
||||
rr.setAccessible(true);
|
||||
put(server, MinecraftServer.class, "resources", rr.newInstance(null, managers));
|
||||
var recipes = new net.minecraft.world.item.crafting.RecipeManager(lookup);
|
||||
recipes.finalizeRecipeLoading(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags());
|
||||
put(managers, ReloadableServerResources.class, "recipes", recipes);
|
||||
put(server, MinecraftServer.class, "scoreboard", new net.minecraft.server.ServerScoreboard(server));
|
||||
|
||||
Lvl level = (Lvl) alloc(Lvl.class);
|
||||
level.fake = server;
|
||||
level.registries = access;
|
||||
put(level, ServerLevel.class, "server", server);
|
||||
level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build();
|
||||
level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags());
|
||||
put(level, Level.class, "damageSources", new DamageSources(access));
|
||||
put(level, Level.class, "random", RandomSource.create(0L));
|
||||
Method dropAll = LivingEntity.class.getDeclaredMethod("dropAllDeathLoot", ServerLevel.class, DamageSource.class);
|
||||
dropAll.setAccessible(true);
|
||||
var enchantments = access.lookupOrThrow(Registries.ENCHANTMENT);
|
||||
|
||||
if (args.length > 2 && args[2].equals("facts")) {
|
||||
// Per-type facts the death step reads (a debugging aid, not compared).
|
||||
Field xp = Mob.class.getDeclaredField("xpReward");
|
||||
xp.setAccessible(true);
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (var type : BuiltInRegistries.ENTITY_TYPE) {
|
||||
Entity e;
|
||||
try { e = type.create(level, EntitySpawnReason.LOAD); } catch (Throwable t) { continue; }
|
||||
if (!(e instanceof Mob mob)) continue;
|
||||
StringBuilder sb = new StringBuilder(BuiltInRegistries.ENTITY_TYPE.getKey(type).toString());
|
||||
sb.append(" monster=").append(e instanceof net.minecraft.world.entity.monster.Monster).append(" xp=").append(xp.get(mob))
|
||||
.append(" baby=").append(mob.isBaby()).append(" class=").append(e.getClass().getSimpleName())
|
||||
.append(" animal=").append(e instanceof net.minecraft.world.entity.animal.Animal)
|
||||
.append(" agwater=").append(e instanceof net.minecraft.world.entity.animal.AgeableWaterCreature)
|
||||
.append(" water=").append(e instanceof net.minecraft.world.entity.animal.fish.WaterAnimal)
|
||||
.append(" ageable=").append(e instanceof AgeableMob);
|
||||
mob.setBaby(true);
|
||||
sb.append(" canbaby=").append(mob.isBaby());
|
||||
for (EquipmentSlot slot : EquipmentSlot.VALUES) if (mob.getDropChances().byEquipment(slot) != 0.085F) sb.append(' ').append(slot.getName()).append('=').append(mob.getDropChances().byEquipment(slot));
|
||||
w.println(sb);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
List<String> lines = Files.readAllLines(Path.of(args[0]));
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (String raw : lines) {
|
||||
if (raw.isBlank() || raw.startsWith("#")) continue;
|
||||
Map<String, String> c = parse(raw);
|
||||
w.println("== " + c.get("name"));
|
||||
List<String> out = new ArrayList<>();
|
||||
level.out = out;
|
||||
try {
|
||||
long worldSeed = Long.parseLong(c.getOrDefault("seed", "0"));
|
||||
put(server, MinecraftServer.class, "worldGenSettings", new WorldGenSettings(new WorldOptions(worldSeed, false, false), null));
|
||||
put(server, MinecraftServer.class, "randomSequences", new RandomSequences());
|
||||
int kills = Integer.parseInt(c.getOrDefault("kills", "1"));
|
||||
long rand = Long.parseLong(c.getOrDefault("rand", "0"));
|
||||
for (int k = 0; k < kills; k++) {
|
||||
out.add("kill " + k);
|
||||
run(level, access, enchantments, c, rand + k, dropAll);
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
Throwable cause = t instanceof InvocationTargetException ite ? ite.getCause() : t;
|
||||
StringBuilder trace = new StringBuilder("error " + cause);
|
||||
if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) trace.append("\n at ").append(frame);
|
||||
out.add(trace.toString());
|
||||
}
|
||||
out.forEach(w::println);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
static ItemStack item(HolderLookup.RegistryLookup<net.minecraft.world.item.enchantment.Enchantment> enchantments, String spec) {
|
||||
// id[;enchantment:level...]
|
||||
String[] parts = spec.split(";");
|
||||
ItemStack stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(parts[0])));
|
||||
for (int i = 1; i < parts.length; i++) {
|
||||
int colon = parts[i].lastIndexOf(':');
|
||||
String name = parts[i].substring(0, colon);
|
||||
if (!name.contains(":")) name = "minecraft:" + name;
|
||||
stack.enchant(enchantments.getOrThrow(ResourceKey.create(Registries.ENCHANTMENT, Identifier.parse(name))), Integer.parseInt(parts[i].substring(colon + 1)));
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
|
||||
static Entity create(Lvl level, String id) {
|
||||
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(id));
|
||||
return type.create(level, EntitySpawnReason.LOAD);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static void run(Lvl level, RegistryAccess access, HolderLookup.RegistryLookup<net.minecraft.world.item.enchantment.Enchantment> enchantments,
|
||||
Map<String, String> c, long rand, Method dropAll) throws Exception {
|
||||
LivingEntity victim = (LivingEntity) create(level, c.get("type"));
|
||||
victim.setPos(0.5, 64.0, 0.5);
|
||||
if (c.containsKey("baby") && victim instanceof Mob mob) mob.setBaby(c.get("baby").equals("1"));
|
||||
if (c.getOrDefault("fire", "0").equals("1")) victim.setRemainingFireTicks(100);
|
||||
if (c.containsKey("size")) victim.getClass().getMethod("setSize", int.class, boolean.class).invoke(victim, Integer.parseInt(c.get("size")), true);
|
||||
if (c.containsKey("color") && victim instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setColor(DyeColor.byName(c.get("color"), DyeColor.WHITE));
|
||||
if (c.getOrDefault("sheared", "0").equals("1") && victim instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setSheared(true);
|
||||
if (c.getOrDefault("leader", "0").equals("1")) ((net.minecraft.world.entity.monster.PatrollingMonster) victim).setPatrolLeader(true);
|
||||
if (c.getOrDefault("captain", "0").equals("1"))
|
||||
victim.setItemSlot(EquipmentSlot.HEAD, net.minecraft.world.entity.raid.Raid.getOminousBannerInstance(access.lookupOrThrow(Registries.BANNER_PATTERN)));
|
||||
for (EquipmentSlot slot : EquipmentSlot.VALUES) {
|
||||
String spec = c.get(slot.getName());
|
||||
if (spec != null) victim.setItemSlot(slot, item(enchantments, spec));
|
||||
String chance = c.get("chance_" + slot.getName());
|
||||
if (chance != null && victim instanceof Mob mob) mob.setDropChance(slot, Float.parseFloat(chance));
|
||||
}
|
||||
if (c.containsKey("vehicle")) {
|
||||
Entity vehicle = create(level, c.get("vehicle"));
|
||||
vehicle.setPos(0.5, 64.0, 0.5);
|
||||
if (!victim.startRiding(vehicle, true, false)) throw new IllegalStateException("could not ride");
|
||||
}
|
||||
// Killer and damage source.
|
||||
Player player = null;
|
||||
LivingEntity killer = null;
|
||||
String killerId = c.getOrDefault("killer", "none");
|
||||
if (killerId.equals("player") || c.getOrDefault("pkill", "0").equals("1")) {
|
||||
player = new OraclePlayer(level);
|
||||
player.setPos(2.5, 64.0, 0.5);
|
||||
if (c.containsKey("luck")) player.getAttribute(Attributes.LUCK).setBaseValue(Double.parseDouble(c.get("luck")));
|
||||
if (killerId.equals("player") && c.containsKey("weapon")) player.setItemSlot(EquipmentSlot.MAINHAND, item(enchantments, c.get("weapon")));
|
||||
}
|
||||
if (killerId.equals("player")) killer = player;
|
||||
else if (!killerId.equals("none")) {
|
||||
killer = (LivingEntity) create(level, killerId);
|
||||
killer.setPos(2.5, 64.0, 0.5);
|
||||
if (c.containsKey("weapon")) killer.setItemSlot(EquipmentSlot.MAINHAND, item(enchantments, c.get("weapon")));
|
||||
if (c.containsKey("frog")) killer.setComponent(DataComponents.FROG_VARIANT,
|
||||
access.lookupOrThrow(Registries.FROG_VARIANT).getOrThrow(ResourceKey.create(Registries.FROG_VARIANT, Identifier.parse(c.get("frog")))));
|
||||
if (c.getOrDefault("charged", "0").equals("1")) {
|
||||
Field powered = net.minecraft.world.entity.monster.Creeper.class.getDeclaredField("DATA_IS_POWERED");
|
||||
powered.setAccessible(true);
|
||||
killer.getEntityData().set((net.minecraft.network.syncher.EntityDataAccessor<Boolean>) powered.get(null), true);
|
||||
}
|
||||
}
|
||||
if (player != null && c.getOrDefault("pkill", killerId.equals("player") ? "1" : "0").equals("1")) victim.setLastHurtByPlayer(player, 100);
|
||||
DamageSources sources = level.damageSources();
|
||||
DamageSource source = switch (c.getOrDefault("source", "attack")) {
|
||||
case "attack" -> killer == null ? sources.generic() : killer instanceof Player p ? sources.playerAttack(p) : sources.mobAttack(killer);
|
||||
case "arrow" -> {
|
||||
var arrow = new net.minecraft.world.entity.projectile.arrow.Arrow(EntityTypes.ARROW, level);
|
||||
arrow.setPos(1.5, 64.0, 0.5);
|
||||
yield sources.arrow(arrow, killer);
|
||||
}
|
||||
case "fireball" -> {
|
||||
var fireball = new net.minecraft.world.entity.projectile.hurtingprojectile.LargeFireball(EntityTypes.FIREBALL, level);
|
||||
fireball.setPos(1.5, 64.0, 0.5);
|
||||
yield sources.fireball(fireball, killer);
|
||||
}
|
||||
case "explosion" -> sources.explosion(killer, killer);
|
||||
case "lightning" -> sources.lightningBolt();
|
||||
case "fire" -> sources.onFire();
|
||||
default -> sources.generic();
|
||||
};
|
||||
victim.getRandom().setSeed(rand);
|
||||
Entity sourceEntity = source.getEntity();
|
||||
if (sourceEntity == null || sourceEntity.killedEntity(level, victim, source)) dropAll.invoke(victim, level, source);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.*;
|
||||
import java.lang.classfile.*;
|
||||
import java.lang.classfile.instruction.InvokeInstruction;
|
||||
import java.lang.constant.ClassDesc;
|
||||
import java.lang.constant.MethodTypeDesc;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Runs the real FramerateLimiter.limitDisplayFPS from the client jar with its
|
||||
* clock calls (System.nanoTime, LockSupport.parkNanos, Thread.interrupted,
|
||||
* Thread.onSpinWait) redirected by a ClassFile rewrite to a scripted virtual
|
||||
* clock, and the Minecraft.runTick condition (limits below 260), printing the
|
||||
* limiter state and clock interaction of every frame.
|
||||
*/
|
||||
public final class VanillaFrameLimiterOracle {
|
||||
/** The scripted clock the rewritten limiter calls. */
|
||||
public static final class Clock {
|
||||
static long now, call, spin;
|
||||
static long[] overshoot;
|
||||
static int nextOvershoot;
|
||||
static boolean[] interrupts;
|
||||
static int nextInterrupt;
|
||||
static List<Long> parks = new ArrayList<>();
|
||||
static long spins, queries;
|
||||
|
||||
public static long nanoTime() {
|
||||
queries++;
|
||||
long t = now;
|
||||
now += call;
|
||||
return t;
|
||||
}
|
||||
|
||||
public static void parkNanos(long nanos) {
|
||||
parks.add(nanos);
|
||||
long o = overshoot[nextOvershoot++ % overshoot.length];
|
||||
now += Math.max(Math.max(nanos, 0) + o, 1);
|
||||
}
|
||||
|
||||
public static void onSpinWait() {
|
||||
spins++;
|
||||
now += spin;
|
||||
}
|
||||
|
||||
public static boolean interrupted() {
|
||||
return interrupts[nextInterrupt++ % interrupts.length];
|
||||
}
|
||||
}
|
||||
|
||||
static final ClassDesc CLOCK = ClassDesc.of(Clock.class.getName());
|
||||
|
||||
/** Loads FramerateLimiter itself, rewritten; everything else from the parent. */
|
||||
static final class Rewriting extends ClassLoader {
|
||||
Rewriting(ClassLoader parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
|
||||
if (!name.equals("net.minecraft.client.FramerateLimiter")) {
|
||||
return super.loadClass(name, resolve);
|
||||
}
|
||||
synchronized (getClassLoadingLock(name)) {
|
||||
Class<?> loaded = findLoadedClass(name);
|
||||
if (loaded == null) {
|
||||
try (var in = getParent().getResourceAsStream("net/minecraft/client/FramerateLimiter.class")) {
|
||||
byte[] bytes = rewrite(in.readAllBytes());
|
||||
loaded = defineClass(name, bytes, 0, bytes.length);
|
||||
} catch (IOException e) {
|
||||
throw new ClassNotFoundException(name, e);
|
||||
}
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int rewrites;
|
||||
|
||||
static byte[] rewrite(byte[] bytes) {
|
||||
var cf = ClassFile.of();
|
||||
ClassModel model = cf.parse(bytes);
|
||||
return cf.transformClass(model, ClassTransform.transformingMethodBodies((builder, element) -> {
|
||||
if (element instanceof InvokeInstruction call && call.opcode() == Opcode.INVOKESTATIC) {
|
||||
String owner = call.owner().asInternalName();
|
||||
String name = call.name().stringValue();
|
||||
String target = switch (owner + "." + name) {
|
||||
case "java/lang/System.nanoTime" -> "nanoTime";
|
||||
case "java/util/concurrent/locks/LockSupport.parkNanos" -> "parkNanos";
|
||||
case "java/lang/Thread.interrupted" -> "interrupted";
|
||||
case "java/lang/Thread.onSpinWait" -> "onSpinWait";
|
||||
default -> null;
|
||||
};
|
||||
if (target != null) {
|
||||
rewrites++;
|
||||
builder.invokestatic(CLOCK, target, MethodTypeDesc.ofDescriptor(call.type().stringValue()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
builder.with(element);
|
||||
}));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Clock.overshoot = new long[] {0};
|
||||
Clock.interrupts = new boolean[] {false};
|
||||
Class<?> limiter = Class.forName("net.minecraft.client.FramerateLimiter", true,
|
||||
new Rewriting(VanillaFrameLimiterOracle.class.getClassLoader()));
|
||||
// System.nanoTime x4 (and once in the static initialiser), parkNanos, interrupted, onSpinWait.
|
||||
if (rewrites != 8) {
|
||||
throw new AssertionError("unexpected clock calls in FramerateLimiter: " + rewrites);
|
||||
}
|
||||
Method limit = limiter.getMethod("limitDisplayFPS", int.class);
|
||||
Field last = limiter.getDeclaredField("lastFrameTime");
|
||||
Field average = limiter.getDeclaredField("averageOvershootNs");
|
||||
Field lastLimit = limiter.getDeclaredField("lastFramerateLimit");
|
||||
for (Field f : List.of(last, average, lastLimit)) {
|
||||
f.setAccessible(true);
|
||||
}
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
int n = 0;
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
out.println("== " + n++);
|
||||
Clock.now = c.get("now").getAsLong();
|
||||
Clock.call = c.get("call").getAsLong();
|
||||
Clock.spin = c.get("spin").getAsLong();
|
||||
var o = c.getAsJsonArray("overshoot");
|
||||
Clock.overshoot = new long[o.size()];
|
||||
for (int i = 0; i < o.size(); i++) {
|
||||
Clock.overshoot[i] = o.get(i).getAsLong();
|
||||
}
|
||||
var in = c.getAsJsonArray("interrupts");
|
||||
Clock.interrupts = new boolean[in.size()];
|
||||
for (int i = 0; i < in.size(); i++) {
|
||||
Clock.interrupts[i] = in.get(i).getAsBoolean();
|
||||
}
|
||||
Clock.nextOvershoot = 0;
|
||||
Clock.nextInterrupt = 0;
|
||||
last.setLong(null, c.get("last").getAsLong());
|
||||
average.setLong(null, c.get("average").getAsLong());
|
||||
lastLimit.setInt(null, c.get("last_limit").getAsInt());
|
||||
for (var e : c.getAsJsonArray("frames")) {
|
||||
var frame = e.getAsJsonArray();
|
||||
Clock.now += frame.get(0).getAsLong();
|
||||
Clock.parks.clear();
|
||||
Clock.spins = 0;
|
||||
Clock.queries = 0;
|
||||
int framerateLimit = frame.get(1).getAsInt();
|
||||
// Minecraft.runTick: "if (framerateLimit < 260) FramerateLimiter.limitDisplayFPS(framerateLimit)".
|
||||
if (framerateLimit < 260) {
|
||||
limit.invoke(null, framerateLimit);
|
||||
}
|
||||
var parks = new StringJoiner(",");
|
||||
for (long p : Clock.parks) {
|
||||
parks.add(Long.toString(p));
|
||||
}
|
||||
out.println("frame " + Clock.now + " " + last.getLong(null) + " " + average.getLong(null) + " "
|
||||
+ lastLimit.getInt(null) + " queries " + Clock.queries + " spins " + Clock.spins + " parks [" + parks + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.serialization.Lifecycle;
|
||||
import io.netty.channel.embedded.EmbeddedChannel;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.Proxy;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.SystemReport;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.arguments.blocks.BlockStateParser;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.GlobalPos;
|
||||
import net.minecraft.core.MappedRegistry;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.gametest.framework.GameTestServer;
|
||||
import net.minecraft.gizmos.GizmoCollector;
|
||||
import net.minecraft.gizmos.Gizmos;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.PacketFlow;
|
||||
import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.Services;
|
||||
import net.minecraft.server.WorldLoader;
|
||||
import net.minecraft.server.WorldStem;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.level.progress.LoggingLevelLoadListener;
|
||||
import net.minecraft.server.network.CommonListenerCookie;
|
||||
import net.minecraft.server.notifications.EmptyNotificationService;
|
||||
import net.minecraft.server.notifications.NotificationManager;
|
||||
import net.minecraft.server.packs.repository.PackRepository;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
||||
import net.minecraft.server.permissions.PermissionSet;
|
||||
import net.minecraft.server.players.NameAndId;
|
||||
import net.minecraft.server.players.PlayerList;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.util.datafix.DataFixers;
|
||||
import net.minecraft.util.debugchart.LocalSampleLogger;
|
||||
import net.minecraft.util.debugchart.SampleLogger;
|
||||
import net.minecraft.world.clock.WorldClocks;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntitySpawnReason;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.entity.Mob;
|
||||
import net.minecraft.world.entity.AgeableMob;
|
||||
import net.minecraft.world.entity.ai.Brain;
|
||||
import net.minecraft.world.entity.ai.behavior.BlockPosTracker;
|
||||
import net.minecraft.world.entity.ai.behavior.EntityTracker;
|
||||
import net.minecraft.world.entity.ai.control.LookControl;
|
||||
import net.minecraft.world.entity.ai.control.MoveControl;
|
||||
import net.minecraft.world.entity.ai.goal.GoalSelector;
|
||||
import net.minecraft.world.entity.ai.goal.WrappedGoal;
|
||||
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
|
||||
import net.minecraft.world.entity.ai.memory.WalkTarget;
|
||||
import net.minecraft.world.entity.ai.navigation.PathNavigation;
|
||||
import net.minecraft.world.entity.ai.sensing.Sensor;
|
||||
import net.minecraft.world.flag.FeatureFlagSet;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.level.DataPackConfig;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.LevelSettings;
|
||||
import net.minecraft.world.level.WorldDataConfiguration;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.dimension.LevelStem;
|
||||
import net.minecraft.world.level.gamerules.GameRules;
|
||||
import net.minecraft.world.level.levelgen.WorldDimensions;
|
||||
import net.minecraft.world.level.levelgen.WorldGenSettings;
|
||||
import net.minecraft.world.level.levelgen.WorldOptions;
|
||||
import net.minecraft.world.level.levelgen.presets.WorldPresets;
|
||||
import net.minecraft.world.level.storage.LevelDataAndDimensions;
|
||||
import net.minecraft.world.level.storage.LevelStorageSource;
|
||||
import net.minecraft.world.level.storage.PrimaryLevelData;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Mob AI oracle: a real (headless, flat, structure-free) vanilla server level. Each scenario
|
||||
* builds blocks, places a target player and mobs with seeded random sources, then ticks the
|
||||
* mobs exactly as ServerLevel.tick does (despawn check, then tickNonPassenger) while the rest of
|
||||
* the level stands still (no block ticks, weather, spawning or random ticks), printing the
|
||||
* AI-visible state of every mob after each tick: position, motion, rotations, running goals,
|
||||
* targets, navigation, move/look/jump controls, brain activities and memories, and sounds.
|
||||
*/
|
||||
public final class VanillaMobAiOracle {
|
||||
static final List<Scenario> SCENARIOS = new ArrayList<>();
|
||||
static PrintWriter out;
|
||||
static final List<String> SOUNDS = new ArrayList<>();
|
||||
|
||||
/** Draws of a traced mob random: the caller frames of each draw (AI_TRACE=scenario:from-to). */
|
||||
static final class TracingRandom extends net.minecraft.world.level.levelgen.LegacyRandomSource {
|
||||
static int tick;
|
||||
static boolean on;
|
||||
final List<String> log;
|
||||
final int who;
|
||||
TracingRandom(long seed, List<String> log, int who) { super(seed); this.log = log; this.who = who; }
|
||||
@Override
|
||||
public int next(int bits) {
|
||||
int v = super.next(bits);
|
||||
if (on) {
|
||||
StringBuilder sb = new StringBuilder(tick + " trace " + who + " " + bits + "=" + Integer.toHexString(v) + ":");
|
||||
int n = 0;
|
||||
for (StackTraceElement e : new Throwable().getStackTrace()) {
|
||||
String c = e.getClassName();
|
||||
if (c.contains("RandomSource") || c.contains("TracingRandom") || c.contains("Mth")) continue;
|
||||
sb.append(' ').append(c.substring(c.lastIndexOf('.') + 1)).append('.').append(e.getMethodName()).append(':').append(e.getLineNumber());
|
||||
if (++n == 7) break;
|
||||
}
|
||||
log.add(sb.toString());
|
||||
}
|
||||
return v;
|
||||
}
|
||||
}
|
||||
static final List<String> TRACE = new ArrayList<>();
|
||||
|
||||
static final class MobSpec {
|
||||
String type;
|
||||
double x, y, z;
|
||||
float yaw;
|
||||
long seed;
|
||||
boolean baby;
|
||||
List<String> flags = new ArrayList<>();
|
||||
}
|
||||
|
||||
static final class Scenario {
|
||||
String name;
|
||||
int ticks;
|
||||
long time = 6000;
|
||||
boolean rain, thunder;
|
||||
int originX, originZ;
|
||||
List<String[]> blocks = new ArrayList<>();
|
||||
double[] player;
|
||||
boolean creative;
|
||||
List<MobSpec> mobs = new ArrayList<>();
|
||||
long levelSeed = 0;
|
||||
}
|
||||
|
||||
static void parse(Path path) throws Exception {
|
||||
Scenario s = null;
|
||||
for (String raw : Files.readAllLines(path)) {
|
||||
String line = raw.strip();
|
||||
if (line.isEmpty() || line.startsWith("#")) continue;
|
||||
String[] f = line.split("\\s+");
|
||||
switch (f[0]) {
|
||||
case "scenario" -> {
|
||||
s = new Scenario();
|
||||
s.name = f[1];
|
||||
for (int i = 2; i < f.length; i++) {
|
||||
String[] kv = f[i].split("=", 2);
|
||||
switch (kv[0]) {
|
||||
case "ticks" -> s.ticks = Integer.parseInt(kv[1]);
|
||||
case "time" -> s.time = Long.parseLong(kv[1]);
|
||||
case "rain" -> s.rain = true;
|
||||
case "thunder" -> s.thunder = true;
|
||||
case "levelseed" -> s.levelSeed = Long.parseLong(kv[1]);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
case "origin" -> { s.originX = Integer.parseInt(f[1]); s.originZ = Integer.parseInt(f[2]); }
|
||||
case "fill", "block" -> s.blocks.add(f);
|
||||
case "player" -> {
|
||||
s.player = new double[] {Double.parseDouble(f[1]), Double.parseDouble(f[2]), Double.parseDouble(f[3])};
|
||||
s.creative = f.length > 4 && f[4].equals("creative");
|
||||
}
|
||||
case "mob" -> {
|
||||
MobSpec m = new MobSpec();
|
||||
m.type = f[1];
|
||||
m.x = Double.parseDouble(f[2]);
|
||||
m.y = Double.parseDouble(f[3]);
|
||||
m.z = Double.parseDouble(f[4]);
|
||||
m.yaw = Float.parseFloat(f[5]);
|
||||
m.seed = Long.parseLong(f[6]);
|
||||
for (int i = 7; i < f.length; i++) {
|
||||
if (f[i].equals("baby")) m.baby = true; else m.flags.add(f[i]);
|
||||
}
|
||||
s.mobs.add(m);
|
||||
}
|
||||
case "end" -> { SCENARIOS.add(s); s = null; }
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
parse(Path.of(args[0]));
|
||||
out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])));
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
Util.startTimerHackThread();
|
||||
Path universe = Files.createTempDirectory("horizon-mob-ai");
|
||||
LevelStorageSource.LevelStorageAccess access = LevelStorageSource.createDefault(universe).createAccess("aiworld");
|
||||
PackRepository packs = ServerPacksSource.createPackRepository(access);
|
||||
MinecraftServer.spin(thread -> Server.create(thread, access, packs));
|
||||
}
|
||||
|
||||
static String traceSpec() { String v = System.getenv("AI_TRACE"); return v == null ? "" : v; }
|
||||
// Every mob random is traced unless AI_TRACE=0.
|
||||
static boolean tracing(Scenario s) { return !traceSpec().equals("0"); }
|
||||
static int traceFrom() { return 0; }
|
||||
static int traceTo() { return Integer.MAX_VALUE; }
|
||||
|
||||
static String d(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); }
|
||||
static String f(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); }
|
||||
|
||||
static Field field(Class<?> c, String name) throws Exception {
|
||||
for (Class<?> k = c; k != null; k = k.getSuperclass()) {
|
||||
try {
|
||||
Field fl = k.getDeclaredField(name);
|
||||
fl.setAccessible(true);
|
||||
return fl;
|
||||
} catch (NoSuchFieldException e) {
|
||||
// keep looking
|
||||
}
|
||||
}
|
||||
throw new NoSuchFieldException(name);
|
||||
}
|
||||
|
||||
static Method method(Class<?> c, String name, Class<?>... types) throws Exception {
|
||||
for (Class<?> k = c; k != null; k = k.getSuperclass()) {
|
||||
try {
|
||||
Method m = k.getDeclaredMethod(name, types);
|
||||
m.setAccessible(true);
|
||||
return m;
|
||||
} catch (NoSuchMethodException e) {
|
||||
// keep looking
|
||||
}
|
||||
}
|
||||
throw new NoSuchMethodException(name);
|
||||
}
|
||||
|
||||
static Object get(Object o, String name) throws Exception { return field(o.getClass(), name).get(o); }
|
||||
|
||||
static final class Server extends MinecraftServer {
|
||||
static final FeatureFlagSet FEATURES = FeatureFlags.REGISTRY
|
||||
.allFlags()
|
||||
.subtract(FeatureFlagSet.of(FeatureFlags.REDSTONE_EXPERIMENTS, FeatureFlags.MINECART_IMPROVEMENTS));
|
||||
final LocalSampleLogger sampleLogger = new LocalSampleLogger(4);
|
||||
int scenario = 0;
|
||||
int phase = 0;
|
||||
int wait = 0;
|
||||
ServerPlayer player;
|
||||
int failures = 0;
|
||||
|
||||
static Server create(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs) {
|
||||
try {
|
||||
packs.reload();
|
||||
ArrayList<String> enabled = new ArrayList<>(packs.getAvailableIds());
|
||||
enabled.remove("vanilla");
|
||||
enabled.addFirst("vanilla");
|
||||
WorldDataConfiguration config = new WorldDataConfiguration(new DataPackConfig(enabled, List.of()), FEATURES);
|
||||
LevelSettings settings = new LevelSettings("AI Level", GameType.SURVIVAL, LevelSettings.DifficultySettings.DEFAULT, true, config);
|
||||
WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packs, config, false, true);
|
||||
WorldLoader.InitConfig init = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, LevelBasedPermissionSet.OWNER);
|
||||
WorldStem stem = Util.<WorldStem>blockUntilDone(executor -> WorldLoader.load(init, context -> {
|
||||
Registry<LevelStem> none = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze();
|
||||
WorldDimensions dims = context.datapackWorldRegistries().lookupOrThrow(Registries.WORLD_PRESET)
|
||||
.getOrThrow(WorldPresets.FLAT).value().createWorldDimensions();
|
||||
WorldDimensions.Complete complete = dims.bake(none);
|
||||
PrimaryLevelData data = new PrimaryLevelData(settings, complete.specialWorldProperty(), complete.lifecycle());
|
||||
return new WorldLoader.DataLoadOutput<>(
|
||||
new LevelDataAndDimensions.WorldDataAndGenSettings(data, new WorldGenSettings(new WorldOptions(0L, false, false), dims)),
|
||||
complete.dimensionsRegistryAccess());
|
||||
}, WorldStem::new, Util.backgroundExecutor(), executor)).get();
|
||||
GameRules rules = new GameRules(FEATURES);
|
||||
rules.set(GameRules.SPAWN_MOBS, false, null);
|
||||
rules.set(GameRules.SPAWN_MONSTERS, false, null);
|
||||
rules.set(GameRules.SPAWN_PATROLS, false, null);
|
||||
rules.set(GameRules.SPAWN_PHANTOMS, false, null);
|
||||
rules.set(GameRules.SPAWN_WANDERING_TRADERS, false, null);
|
||||
rules.set(GameRules.SPAWN_WARDENS, false, null);
|
||||
rules.set(GameRules.ADVANCE_TIME, false, null);
|
||||
rules.set(GameRules.ADVANCE_WEATHER, false, null);
|
||||
rules.set(GameRules.RAIDS, false, null);
|
||||
Field nf = GameTestServer.class.getDeclaredField("NO_SERVICES");
|
||||
nf.setAccessible(true);
|
||||
return new Server(thread, access, packs, stem, rules, (Services) nf.get(null));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(2);
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
Server(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs, WorldStem stem, GameRules rules, Services services) {
|
||||
super(thread, access, packs, stem, Optional.of(rules), Proxy.NO_PROXY, DataFixers.getDataFixer(), services,
|
||||
LoggingLevelLoadListener.forDedicatedServer(), false, new NotificationManager());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean initServer() {
|
||||
this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, new EmptyNotificationService()) {
|
||||
@Override
|
||||
public void broadcast(Player except, double x, double y, double z, double range, ResourceKey<Level> dim, Packet<?> packet) {
|
||||
capture(packet);
|
||||
}
|
||||
});
|
||||
Gizmos.withCollector(GizmoCollector.NOOP);
|
||||
this.loadLevel();
|
||||
return true;
|
||||
}
|
||||
|
||||
static void capture(Packet<?> packet) {
|
||||
if (packet instanceof ClientboundSoundPacket p) {
|
||||
SOUNDS.add(p.getSound().value().location() + " " + f(p.getVolume()) + " " + f(p.getPitch()));
|
||||
} else if (packet instanceof ClientboundSoundEntityPacket p) {
|
||||
SOUNDS.add(p.getSound().value().location() + " " + f(p.getVolume()) + " " + f(p.getPitch()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tickServer(BooleanSupplier haveTime) {
|
||||
try {
|
||||
step(haveTime);
|
||||
} catch (Throwable t) {
|
||||
t.printStackTrace();
|
||||
out.flush();
|
||||
System.exit(3);
|
||||
}
|
||||
}
|
||||
|
||||
ServerLevel level() { return this.overworld(); }
|
||||
|
||||
void step(BooleanSupplier haveTime) throws Exception {
|
||||
if (scenario >= SCENARIOS.size()) {
|
||||
out.close();
|
||||
// Nothing to save: skip the shutdown.
|
||||
Runtime.getRuntime().halt(0);
|
||||
return;
|
||||
}
|
||||
Scenario s = SCENARIOS.get(scenario);
|
||||
ServerLevel level = level();
|
||||
int cx = s.originX >> 4, cz = s.originZ >> 4;
|
||||
switch (phase) {
|
||||
case 0 -> {
|
||||
for (int dx = -4; dx <= 4; dx++)
|
||||
for (int dz = -4; dz <= 4; dz++)
|
||||
level.setChunkForced(cx + dx, cz + dz, true);
|
||||
phase = 1;
|
||||
super.tickServer(haveTime);
|
||||
}
|
||||
case 1 -> {
|
||||
super.tickServer(haveTime);
|
||||
boolean ready = true;
|
||||
for (int dx = -4; dx <= 4 && ready; dx++)
|
||||
for (int dz = -4; dz <= 4 && ready; dz++)
|
||||
ready = level.isPositionEntityTicking(new BlockPos((cx + dx) * 16, -60, (cz + dz) * 16));
|
||||
if (ready) {
|
||||
build(s, level);
|
||||
phase = 2;
|
||||
wait = 0;
|
||||
}
|
||||
}
|
||||
case 2 -> {
|
||||
super.tickServer(haveTime);
|
||||
if (!level.getChunkSource().getLightEngine().hasLightWork() && ++wait > 5) {
|
||||
run(s, level);
|
||||
for (int dx = -4; dx <= 4; dx++)
|
||||
for (int dz = -4; dz <= 4; dz++)
|
||||
level.setChunkForced(cx + dx, cz + dz, false);
|
||||
scenario++;
|
||||
phase = 0;
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
void build(Scenario s, ServerLevel level) throws Exception {
|
||||
var blocks = level.holderLookup(Registries.BLOCK);
|
||||
for (String[] b : s.blocks) {
|
||||
if (b[0].equals("block")) {
|
||||
BlockState state = BlockStateParser.parseForBlock(blocks, b[4], false).blockState();
|
||||
level.setBlock(new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])), state, 2 | 16);
|
||||
} else {
|
||||
BlockState state = BlockStateParser.parseForBlock(blocks, b[7], false).blockState();
|
||||
int x0 = Integer.parseInt(b[1]), y0 = Integer.parseInt(b[2]), z0 = Integer.parseInt(b[3]);
|
||||
int x1 = Integer.parseInt(b[4]), y1 = Integer.parseInt(b[5]), z1 = Integer.parseInt(b[6]);
|
||||
for (int x = Math.min(x0, x1); x <= Math.max(x0, x1); x++)
|
||||
for (int y = Math.min(y0, y1); y <= Math.max(y0, y1); y++)
|
||||
for (int z = Math.min(z0, z1); z <= Math.max(z0, z1); z++)
|
||||
level.setBlock(new BlockPos(x, y, z), state, 2 | 16);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void run(Scenario s, ServerLevel level) throws Exception {
|
||||
out.println("== " + s.name);
|
||||
var clock = level.registryAccess().lookupOrThrow(Registries.WORLD_CLOCK).getOrThrow(WorldClocks.OVERWORLD);
|
||||
this.clockManager().setTotalTicks(clock, s.time);
|
||||
// Every scenario starts at game time 1000.
|
||||
this.getWorldData().overworldData().setGameTime(1000L);
|
||||
// isRaining/isThundering read the rain and thunder levels only.
|
||||
level.setRainLevel(s.rain ? 1.0F : 0.0F);
|
||||
level.setThunderLevel(s.thunder ? 1.0F : 0.0F);
|
||||
if (s.player != null) {
|
||||
if (player == null) {
|
||||
CommonListenerCookie cookie = CommonListenerCookie.createInitial(new GameProfile(new UUID(0x1234L, 0x5678L), "horizon-ai"), false);
|
||||
player = new ServerPlayer(this, level, cookie.gameProfile(), cookie.clientInformation());
|
||||
Connection connection = new Connection(PacketFlow.SERVERBOUND);
|
||||
new EmbeddedChannel(connection);
|
||||
this.getPlayerList().placeNewPlayer(connection, player, cookie);
|
||||
}
|
||||
player.setGameMode(s.creative ? GameType.CREATIVE : GameType.SURVIVAL);
|
||||
player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F);
|
||||
player.setDeltaMovement(Vec3.ZERO);
|
||||
} else if (player != null) {
|
||||
player.snapTo(s.originX + 5000, -60, s.originZ, 0.0F, 0.0F);
|
||||
}
|
||||
List<Mob> mobs = new ArrayList<>();
|
||||
int id = 100000;
|
||||
for (MobSpec spec : s.mobs) {
|
||||
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(net.minecraft.resources.Identifier.parse(spec.type));
|
||||
Mob mob = (Mob) type.create(level, EntitySpawnReason.COMMAND);
|
||||
if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, mobs.size()));
|
||||
mob.setId(id++);
|
||||
mob.snapTo(spec.x, spec.y, spec.z, spec.yaw, 0.0F);
|
||||
mob.setYHeadRot(spec.yaw);
|
||||
mob.setYBodyRot(spec.yaw);
|
||||
if (spec.baby) {
|
||||
if (mob instanceof AgeableMob a) a.setBaby(true);
|
||||
else mob.setBaby(true);
|
||||
}
|
||||
for (String flag : spec.flags) {
|
||||
if (flag.equals("persistent")) mob.setPersistenceRequired();
|
||||
else if (flag.equals("noai")) mob.setNoAi(true);
|
||||
else throw new IllegalArgumentException(flag);
|
||||
}
|
||||
level.addFreshEntity(mob);
|
||||
mob.getRandom().setSeed(spec.seed);
|
||||
Brain<?> brain = mob.getBrain();
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<Object, Sensor<?>> sensors = (Map<Object, Sensor<?>>) get(brain, "sensors");
|
||||
for (Sensor<?> sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom());
|
||||
mobs.add(mob);
|
||||
}
|
||||
level.getRandom().setSeed(s.levelSeed);
|
||||
SOUNDS.clear();
|
||||
Method tickTime = method(ServerLevel.class, "tickTime");
|
||||
Object manager = get(level, "entityManager");
|
||||
Method managerTick = method(manager.getClass(), "tick");
|
||||
for (int i = 0; i < mobs.size(); i++) print(0, i, mobs.get(i));
|
||||
for (int t = 1; t <= s.ticks; t++) {
|
||||
level.environmentAttributes().invalidateTickCache();
|
||||
level.updateSkyBrightness();
|
||||
tickTime.invoke(level);
|
||||
if (player != null && s.player != null) {
|
||||
player.setHealth(player.getMaxHealth());
|
||||
player.setInvulnerableTime(0);
|
||||
player.hurtTime = 0;
|
||||
player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F);
|
||||
player.setDeltaMovement(Vec3.ZERO);
|
||||
}
|
||||
TracingRandom.tick = t;
|
||||
TracingRandom.on = tracing(s) && t >= traceFrom() && t <= traceTo();
|
||||
SOUNDS.clear();
|
||||
for (Mob mob : mobs) {
|
||||
if (mob.isRemoved()) continue;
|
||||
mob.checkDespawn();
|
||||
if (mob.isRemoved()) continue;
|
||||
level.tickNonPassenger(mob);
|
||||
}
|
||||
managerTick.invoke(manager);
|
||||
for (int i = 0; i < mobs.size(); i++) print(t, i, mobs.get(i));
|
||||
for (String sound : SOUNDS) out.println(t + " sound " + sound);
|
||||
for (String line : TRACE) out.println(line);
|
||||
TRACE.clear();
|
||||
}
|
||||
for (Mob mob : mobs) mob.discard();
|
||||
managerTick.invoke(manager);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
static String who(Entity e) {
|
||||
if (e == null) return "none";
|
||||
if (e instanceof ServerPlayer) return "player";
|
||||
return "e" + e.getId();
|
||||
}
|
||||
|
||||
static String goals(GoalSelector selector) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (WrappedGoal g : selector.getAvailableGoals()) {
|
||||
if (!g.isRunning()) continue;
|
||||
if (sb.length() > 0) sb.append('|');
|
||||
Class<?> c = g.getGoal().getClass();
|
||||
String name = c.getSimpleName();
|
||||
if (name.isEmpty()) name = c.getName().substring(c.getName().lastIndexOf('.') + 1);
|
||||
sb.append(name);
|
||||
}
|
||||
return sb.length() == 0 ? "-" : sb.toString();
|
||||
}
|
||||
|
||||
static String pos(BlockPos p) { return p.getX() + "," + p.getY() + "," + p.getZ(); }
|
||||
|
||||
static String value(Object v) {
|
||||
if (v == null) return "null";
|
||||
if (v instanceof Entity e) return who(e);
|
||||
if (v instanceof BlockPos p) return pos(p);
|
||||
if (v instanceof GlobalPos g) return pos(g.pos());
|
||||
if (v instanceof WalkTarget w) return value(w.getTarget()) + "/" + f(w.getSpeedModifier()) + "/" + w.getCloseEnoughDist();
|
||||
if (v instanceof EntityTracker e) return who(e.getEntity());
|
||||
if (v instanceof BlockPosTracker b) return pos(b.currentBlockPosition());
|
||||
if (v instanceof Boolean || v instanceof Integer || v instanceof Long) return v.toString();
|
||||
if (v instanceof net.minecraft.util.Unit) return "u";
|
||||
if (v instanceof Collection<?> c) return "n" + c.size();
|
||||
if (v instanceof net.minecraft.world.level.pathfinder.Path p) return "path" + pos(p.getTarget());
|
||||
return v.getClass().getSimpleName();
|
||||
}
|
||||
|
||||
void print(int t, int i, Mob m) throws Exception {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(t).append(' ').append(i);
|
||||
if (m.isRemoved()) {
|
||||
out.println(sb.append(" removed ").append(m.getRemovalReason()));
|
||||
return;
|
||||
}
|
||||
sb.append("\tp ").append(d(m.getX())).append(',').append(d(m.getY())).append(',').append(d(m.getZ()));
|
||||
Vec3 v = m.getDeltaMovement();
|
||||
sb.append("\tv ").append(d(v.x)).append(',').append(d(v.y)).append(',').append(d(v.z));
|
||||
sb.append("\tr ").append(f(m.getYRot())).append(',').append(f(m.getXRot())).append(',').append(f(m.getYHeadRot())).append(',').append(f(m.yBodyRot));
|
||||
sb.append("\tg ").append(m.onGround() ? 1 : 0).append(m.horizontalCollision ? 1 : 0);
|
||||
sb.append("\thp ").append(f(m.getHealth()));
|
||||
sb.append("\tgoals ").append(goals((GoalSelector) get(m, "goalSelector")));
|
||||
sb.append("\ttargets ").append(goals((GoalSelector) get(m, "targetSelector")));
|
||||
sb.append("\ttarget ").append(who(m.getTarget()));
|
||||
PathNavigation nav = m.getNavigation();
|
||||
var path = nav.getPath();
|
||||
sb.append("\tnav ");
|
||||
if (path == null) sb.append("none");
|
||||
else sb.append(pos(path.getTarget())).append(' ').append(path.getNextNodeIndex()).append('/').append(path.getNodeCount())
|
||||
.append(path.isDone() ? " done" : "");
|
||||
MoveControl mc = m.getMoveControl();
|
||||
sb.append("\tmove ").append(get(mc, "operation")).append(' ').append(d((double) get(mc, "wantedX"))).append(',')
|
||||
.append(d((double) get(mc, "wantedY"))).append(',').append(d((double) get(mc, "wantedZ"))).append(' ')
|
||||
.append(d((double) get(mc, "speedModifier")));
|
||||
LookControl lc = m.getLookControl();
|
||||
sb.append("\tlook ").append(get(lc, "lookAtCooldown")).append(' ').append(d((double) get(lc, "wantedX"))).append(',')
|
||||
.append(d((double) get(lc, "wantedY"))).append(',').append(d((double) get(lc, "wantedZ")));
|
||||
sb.append("\tin ").append(f(m.xxa)).append(',').append(f(m.zza)).append(',').append(f(m.getSpeed())).append(',')
|
||||
.append(field(LivingEntity.class, "jumping").getBoolean(m) ? 1 : 0);
|
||||
sb.append("\trng ").append(Long.toHexString(((java.util.concurrent.atomic.AtomicLong) field(net.minecraft.world.level.levelgen.LegacyRandomSource.class, "seed").get(m.getRandom())).get()));
|
||||
Brain<?> brain = m.getBrain();
|
||||
if (!brain.getActiveActivities().isEmpty() && !((Map<?, ?>) get(brain, "sensors")).isEmpty()) {
|
||||
List<String> acts = new ArrayList<>();
|
||||
for (var a : brain.getActiveActivities()) acts.add(a.getName());
|
||||
acts.sort(null);
|
||||
sb.append("\tact ").append(String.join("|", acts));
|
||||
List<String> mem = new ArrayList<>();
|
||||
brain.forEach(new Brain.Visitor() {
|
||||
@Override public <U> void acceptEmpty(MemoryModuleType<U> type) {}
|
||||
@Override public <U> void accept(MemoryModuleType<U> type, U value) { mem.add(name(type) + "=" + value(value)); }
|
||||
@Override public <U> void accept(MemoryModuleType<U> type, U value, long ttl) { mem.add(name(type) + "=" + value(value) + "@" + ttl); }
|
||||
});
|
||||
mem.sort(null);
|
||||
sb.append("\tmem ").append(String.join(" ", mem));
|
||||
}
|
||||
out.println(sb);
|
||||
}
|
||||
|
||||
static String name(MemoryModuleType<?> type) {
|
||||
return BuiltInRegistries.MEMORY_MODULE_TYPE.getKey(type).getPath();
|
||||
}
|
||||
|
||||
@Override protected SampleLogger getTickTimeLogger() { return sampleLogger; }
|
||||
@Override public boolean isTickTimeLoggingEnabled() { return false; }
|
||||
@Override protected void waitUntilNextTick() { this.runAllTasks(); }
|
||||
@Override public SystemReport fillServerSystemReport(SystemReport report) { report.setDetail("Type", "Mob AI oracle"); return report; }
|
||||
@Override protected void onServerExit() { super.onServerExit(); System.exit(0); }
|
||||
@Override protected void onServerCrash(net.minecraft.CrashReport report) { super.onServerCrash(report); System.exit(1); }
|
||||
@Override public boolean isHardcore() { return false; }
|
||||
@Override public LevelBasedPermissionSet operatorUserPermissions() { return LevelBasedPermissionSet.ALL; }
|
||||
@Override public PermissionSet getFunctionCompilationPermissions() { return LevelBasedPermissionSet.OWNER; }
|
||||
@Override public boolean shouldRconBroadcast() { return false; }
|
||||
@Override public boolean isDedicatedServer() { return false; }
|
||||
@Override public int getRateLimitPacketsPerSecond() { return 0; }
|
||||
@Override public int getCommandSpamThresholdSeconds() { return 0; }
|
||||
@Override public int getChatSpamThresholdSeconds() { return 0; }
|
||||
@Override public boolean useNativeTransport() { return false; }
|
||||
@Override public boolean isPublished() { return false; }
|
||||
@Override public boolean shouldInformAdmins() { return false; }
|
||||
@Override public boolean isSingleplayerOwner(NameAndId nameAndId) { return false; }
|
||||
@Override public int getMaxPlayers() { return 1; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.Gui;
|
||||
import net.minecraft.client.gui.components.toasts.ToastManager;
|
||||
import net.minecraft.client.gui.screens.LevelLoadingScreen;
|
||||
import net.minecraft.client.resources.sounds.SoundInstance;
|
||||
import net.minecraft.client.sounds.MusicManager;
|
||||
import net.minecraft.client.sounds.SoundEngine;
|
||||
import net.minecraft.client.sounds.SoundManager;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.sounds.Music;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.util.RandomSource;
|
||||
|
||||
/**
|
||||
* Drives the real MusicManager over the real SoundEngine (VanillaSoundRig).
|
||||
* The situation, Minecraft.getSituationalMusic and getMusicVolume, is the
|
||||
* script's input; the loading screen is a LevelLoadingScreen in the Gui; the
|
||||
* toast manager records showNowPlayingToast/hideNowPlayingToast. Each client
|
||||
* tick is musicManager.tick() then soundManager.tick(pause), as Minecraft.tick
|
||||
* runs them. Prints the manager's state and the music channel every step.
|
||||
*/
|
||||
public final class VanillaMusicOracle {
|
||||
public static final class Mc extends Minecraft {
|
||||
Music music;
|
||||
float volume = 1.0F;
|
||||
|
||||
Mc() {
|
||||
super(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Music getSituationalMusic() {
|
||||
return music;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getMusicVolume() {
|
||||
return volume;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Toasts extends ToastManager {
|
||||
final List<String> calls = new ArrayList<>();
|
||||
|
||||
Toasts() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showNowPlayingToast() {
|
||||
calls.add("show");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void hideNowPlayingToast() {
|
||||
calls.add("hide");
|
||||
}
|
||||
}
|
||||
|
||||
static Music music(String spec) {
|
||||
if (spec.equals("-")) return null;
|
||||
String[] p = spec.split(",");
|
||||
return new Music(Holder.direct(SoundEvent.createVariableRangeEvent(Identifier.parse(p[0]))), Integer.parseInt(p[1]),
|
||||
Integer.parseInt(p[2]), p[3].equals("1"));
|
||||
}
|
||||
|
||||
static float f(String hex) {
|
||||
return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var rig = new VanillaSoundRig(Path.of(args[0]));
|
||||
Mc mc = VanillaSoundRig.make(Mc.class);
|
||||
Gui gui = VanillaSoundRig.make(Gui.class);
|
||||
Toasts toasts = VanillaSoundRig.make(Toasts.class);
|
||||
VanillaSoundRig.set(toasts, Toasts.class, "calls", new ArrayList<String>());
|
||||
VanillaSoundRig.set(gui, Gui.class, "toastManager", toasts);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "gui", gui);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "soundManager", rig.manager);
|
||||
var loading = VanillaSoundRig.make(LevelLoadingScreen.class);
|
||||
MusicManager manager = null;
|
||||
var gains = VanillaSoundRig.field(SoundEngine.class, "gainBySource");
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) {
|
||||
for (String line : Files.readAllLines(Path.of(args[1]))) {
|
||||
out.println(line);
|
||||
String[] a = line.split(" ");
|
||||
switch (a[0]) {
|
||||
case "start" -> {
|
||||
// A fresh manager: MusicManager(minecraft) with a seeded random.
|
||||
manager = VanillaSoundRig.make(MusicManager.class);
|
||||
VanillaSoundRig.set(manager, MusicManager.class, "minecraft", mc);
|
||||
VanillaSoundRig.set(manager, MusicManager.class, "random", RandomSource.create(Long.parseLong(a[1])));
|
||||
VanillaSoundRig.set(manager, MusicManager.class, "gameMusicFrequency", MusicManager.MusicFrequency.valueOf(a[2]));
|
||||
VanillaSoundRig.set(manager, MusicManager.class, "currentGain", 1.0F);
|
||||
VanillaSoundRig.set(manager, MusicManager.class, "nextSongDelay", 100);
|
||||
rig.manager.stop();
|
||||
}
|
||||
case "situation" -> {
|
||||
mc.music = music(a[1]);
|
||||
mc.volume = f(a[2]);
|
||||
}
|
||||
case "tick" -> {
|
||||
VanillaSoundRig.set(gui, Gui.class, "screen", a[1].equals("1") ? loading : null);
|
||||
manager.tick();
|
||||
rig.manager.tick(a[2].equals("1"));
|
||||
}
|
||||
case "finish" -> {
|
||||
var current = (SoundInstance) VanillaSoundRig.get(manager, MusicManager.class, "currentMusic");
|
||||
if (current != null) rig.finish(current);
|
||||
}
|
||||
case "stop" -> manager.stopPlaying();
|
||||
case "stopmusic" -> manager.stopPlaying(music(a[1]));
|
||||
case "freq" -> manager.setMinutesBetweenSongs(MusicManager.MusicFrequency.valueOf(a[1]));
|
||||
case "toast" -> manager.showNowPlayingToastIfNeeded();
|
||||
case "volume" -> {
|
||||
rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2]));
|
||||
rig.manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]);
|
||||
}
|
||||
case "stopall" -> rig.manager.stop();
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
var current = (SoundInstance) VanillaSoundRig.get(manager, MusicManager.class, "currentMusic");
|
||||
out.printf(" current=%s delay=%d gain=%08x toastShown=%s musicGain=%08x%n", current == null ? "-" : current.getIdentifier(),
|
||||
(int) VanillaSoundRig.get(manager, MusicManager.class, "nextSongDelay"),
|
||||
Float.floatToRawIntBits((float) VanillaSoundRig.get(manager, MusicManager.class, "currentGain")),
|
||||
VanillaSoundRig.get(manager, MusicManager.class, "toastShown"),
|
||||
Float.floatToRawIntBits(((it.unimi.dsi.fastutil.objects.Object2FloatMap<SoundSource>) gains.get(rig.engine)).getFloat(SoundSource.MUSIC)));
|
||||
for (String call : toasts.calls) out.println(" toast " + call);
|
||||
toasts.calls.clear();
|
||||
if (current != null) out.println(rig.describe("music", current));
|
||||
rig.flush(out);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,550 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
|
||||
import it.unimi.dsi.fastutil.longs.LongSet;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.level.ChunkMap;
|
||||
import net.minecraft.server.level.ServerChunkCache;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.Difficulty;
|
||||
import net.minecraft.world.DifficultyInstance;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.level.*;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeManager;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.border.WorldBorder;
|
||||
import net.minecraft.world.level.chunk.ChunkGenerator;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.entity.EntityTypeTest;
|
||||
import net.minecraft.world.level.gamerules.GameRules;
|
||||
import net.minecraft.world.level.levelgen.Heightmap;
|
||||
import net.minecraft.world.level.levelgen.FlatLevelSource;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.level.levelgen.structure.BoundingBox;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructurePiece;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureStart;
|
||||
import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer;
|
||||
import net.minecraft.world.level.levelgen.structure.pieces.StructurePieceSerializationContext;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.level.storage.LevelData;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Original oracle: natural spawning as NaturalSpawner decides it, on a
|
||||
* stand-in ServerLevel built from boxes of blocks, light and biomes, with
|
||||
* structure starts (pieces), existing entities, players, the world spawn
|
||||
* point and unloaded chunks. Three modes:
|
||||
*
|
||||
* - chunk: createState over the entities, getFilteredSpawningCategories, then
|
||||
* spawnForChunk's loop (canSpawnForCategoryLocal, getRandomPosWithin) and
|
||||
* vanilla's spawnCategoryForPosition with the state's canSpawn and
|
||||
* afterSpawn;
|
||||
* - pos: spawnCategoryForPosition from a given start;
|
||||
* - gen: spawnMobsForChunkGeneration.
|
||||
*
|
||||
* The log records each attempt (the nearest player lookup), each type that
|
||||
* passed isValidSpawnPostitionForType with the potential test's answer, each
|
||||
* spawn (position and yaw bits), and the next draw of the level random, which
|
||||
* pins every draw in between. finalizeSpawn reads level.getRandom(), which
|
||||
* here is a fixed "neutral" source (nextInt 0, nextFloat and nextDouble 0.75),
|
||||
* so finalizeSpawn's own outcomes stay out of scope while its effect on later
|
||||
* attempts (the finalized mob's box obstructs them) is deterministic.
|
||||
*/
|
||||
public final class VanillaNaturalSpawnOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate, putObject, objectFieldOffset;
|
||||
|
||||
static Object alloc(Class<?> c) throws Exception { return allocate.invoke(unsafe, c); }
|
||||
|
||||
static void put(Object target, Class<?> owner, String field, Object value) throws Exception {
|
||||
Field f = owner.getDeclaredField(field);
|
||||
putObject.invoke(unsafe, target, (long) objectFieldOffset.invoke(unsafe, f), value);
|
||||
}
|
||||
|
||||
record Box(int x0, int y0, int z0, int x1, int y1, int z1) {
|
||||
boolean has(int x, int y, int z) { return x >= x0 && x <= x1 && y >= y0 && y <= y1 && z >= z0 && z <= z1; }
|
||||
static Box parse(String s) {
|
||||
String[] p = s.split(",");
|
||||
return new Box(Integer.parseInt(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]),
|
||||
Integer.parseInt(p[3]), Integer.parseInt(p[4]), Integer.parseInt(p[5]));
|
||||
}
|
||||
}
|
||||
record Start(Structure structure, StructureStart start) {}
|
||||
|
||||
/** finalizeSpawn's random: the same answer every time. */
|
||||
static final class Neutral implements RandomSource {
|
||||
@Override public RandomSource fork() { return this; }
|
||||
@Override public net.minecraft.world.level.levelgen.PositionalRandomFactory forkPositional() { throw new UnsupportedOperationException(); }
|
||||
@Override public void setSeed(long seed) {}
|
||||
@Override public int nextInt() { return 0; }
|
||||
@Override public int nextInt(int bound) { return 0; }
|
||||
@Override public long nextLong() { return 0L; }
|
||||
@Override public boolean nextBoolean() { return false; }
|
||||
@Override public float nextFloat() { return 0.75F; }
|
||||
@Override public double nextDouble() { return 0.75; }
|
||||
@Override public double nextGaussian() { return 0.0; }
|
||||
}
|
||||
|
||||
static final class Lvl extends ServerLevel {
|
||||
Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); }
|
||||
RegistryAccess registries;
|
||||
net.minecraft.server.MinecraftServer fake;
|
||||
@Override public net.minecraft.server.MinecraftServer getServer() { return fake; }
|
||||
List<Map.Entry<Box, BlockState>> blocks = new ArrayList<>();
|
||||
List<Map.Entry<Box, int[]>> lights = new ArrayList<>();
|
||||
List<Map.Entry<Box, Holder<Biome>>> biomes = new ArrayList<>();
|
||||
Holder<Biome> biome;
|
||||
int sky, block, darken, sea;
|
||||
boolean thunder;
|
||||
long seed;
|
||||
Difficulty difficulty;
|
||||
DimensionType dimensionType;
|
||||
ResourceKey<Level> dimensionKey;
|
||||
LevelData.RespawnData respawn;
|
||||
Set<Long> unloaded = new HashSet<>();
|
||||
List<Start> starts = new ArrayList<>();
|
||||
List<Entity> entities = new ArrayList<>();
|
||||
List<ServerPlayer> playerList = new ArrayList<>();
|
||||
net.minecraft.world.attribute.EnvironmentAttributeSystem attributes;
|
||||
BiomeManager biomeManager;
|
||||
WorldBorder border = new WorldBorder();
|
||||
GameRules rules;
|
||||
ServerChunkCache chunkSource;
|
||||
StructureManager structures;
|
||||
RandomSource neutral = new Neutral();
|
||||
List<String> log;
|
||||
boolean logColumns;
|
||||
int next = 1;
|
||||
@Override public RegistryAccess registryAccess() { return registries; }
|
||||
@Override public Difficulty getDifficulty() { return difficulty; }
|
||||
@Override public long getGameTime() { return 0L; }
|
||||
@Override public int getNextEntityId() { return next++; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
|
||||
@Override public BlockState getBlockState(BlockPos pos) {
|
||||
for (int i = blocks.size() - 1; i >= 0; i--)
|
||||
if (blocks.get(i).getKey().has(pos.getX(), pos.getY(), pos.getZ())) return blocks.get(i).getValue();
|
||||
return Blocks.AIR.defaultBlockState();
|
||||
}
|
||||
@Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); }
|
||||
int[] light(BlockPos pos) {
|
||||
for (int i = lights.size() - 1; i >= 0; i--)
|
||||
if (lights.get(i).getKey().has(pos.getX(), pos.getY(), pos.getZ())) return lights.get(i).getValue();
|
||||
return new int[] {sky, block};
|
||||
}
|
||||
@Override public int getBrightness(LightLayer layer, BlockPos pos) { int[] l = light(pos); return layer == LightLayer.SKY ? l[0] : l[1]; }
|
||||
@Override public int getRawBrightness(BlockPos pos, int darkening) { int[] l = light(pos); return Math.max(l[1], l[0] - darkening); }
|
||||
@Override public int getSkyDarken() { return darken; }
|
||||
@Override public boolean isThundering() { return thunder; }
|
||||
@Override public int getSeaLevel() { return sea; }
|
||||
@Override public int getHeight(Heightmap.Types type, int x, int z) {
|
||||
if (logColumns) log.add("col " + x + " " + z);
|
||||
for (int y = getMaxY(); y >= getMinY(); y--)
|
||||
if (type.isOpaque().test(getBlockState(new BlockPos(x, y, z)))) return y + 1;
|
||||
return getMinY();
|
||||
}
|
||||
@Override public long getSeed() { return seed; }
|
||||
@Override public DimensionType dimensionType() { return dimensionType; }
|
||||
@Override public ResourceKey<Level> dimension() { return dimensionKey; }
|
||||
Holder<Biome> biomeAt(int x, int y, int z) {
|
||||
for (int i = biomes.size() - 1; i >= 0; i--)
|
||||
if (biomes.get(i).getKey().has(x, y, z)) return biomes.get(i).getValue();
|
||||
return biome;
|
||||
}
|
||||
@Override public Holder<Biome> getBiome(BlockPos pos) { return biomeAt(pos.getX(), pos.getY(), pos.getZ()); }
|
||||
@Override public BiomeManager getBiomeManager() { return biomeManager; }
|
||||
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; }
|
||||
@Override public WorldBorder getWorldBorder() { return border; }
|
||||
@Override public GameRules getGameRules() { return rules; }
|
||||
@Override public RandomSource getRandom() { return neutral; }
|
||||
@Override public ServerChunkCache getChunkSource() { return chunkSource; }
|
||||
@Override public StructureManager structureManager() { return structures; }
|
||||
@Override public LevelData.RespawnData getRespawnData() { return respawn; }
|
||||
@Override public boolean canSpawnEntitiesInChunk(ChunkPos pos) { return !unloaded.contains(pos.pack()); }
|
||||
@Override public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { return new DifficultyInstance(difficulty, 0L, 0L, 0.0F); }
|
||||
@Override public BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return this; }
|
||||
@Override public boolean containsAnyLiquid(AABB box) {
|
||||
BlockPos lo = BlockPos.containing(box.minX, box.minY, box.minZ), hi = BlockPos.containing(box.maxX, box.maxY, box.maxZ);
|
||||
for (BlockPos p : BlockPos.betweenClosed(lo, hi)) if (!getBlockState(p).getFluidState().isEmpty()) return true;
|
||||
return false;
|
||||
}
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@Override public List players() { return playerList; }
|
||||
@Override public Iterable<Entity> getAllEntities() { return entities; }
|
||||
@Override public List<Entity> getEntities(Entity except, AABB bb, Predicate<? super Entity> selector) {
|
||||
List<Entity> out = new ArrayList<>();
|
||||
for (Entity e : entities) if (e != except && e.getBoundingBox().intersects(bb) && selector.test(e)) out.add(e);
|
||||
return out;
|
||||
}
|
||||
@Override public <T extends Entity> List<T> getEntities(EntityTypeTest<Entity, T> type, AABB bb, Predicate<? super T> selector) {
|
||||
List<T> out = new ArrayList<>();
|
||||
for (Entity e : entities) {
|
||||
T t = type.tryCast(e);
|
||||
if (t != null && e.getBoundingBox().intersects(bb) && selector.test(t)) out.add(t);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@Override public boolean addFreshEntity(Entity entity) { entities.add(entity); return true; }
|
||||
@Override public void addFreshEntityWithPassengers(Entity entity) { entity.getSelfAndPassengers().forEach(this::addFreshEntity); }
|
||||
@Override public Player getNearestPlayer(double x, double y, double z, double maxDist, boolean filter) {
|
||||
if (maxDist == -1.0 && !filter) log.add("try " + (int) Math.floor(x) + " " + (int) Math.floor(z));
|
||||
return super.getNearestPlayer(x, y, z, maxDist, filter);
|
||||
}
|
||||
}
|
||||
|
||||
static final class Chunk extends LevelChunk {
|
||||
Chunk() { super((Level) null, (ChunkPos) null); }
|
||||
Lvl level;
|
||||
ChunkPos at;
|
||||
@Override public ChunkPos getPos() { return at; }
|
||||
@Override public BlockState getBlockState(BlockPos pos) { return level.getBlockState(pos); }
|
||||
@Override public FluidState getFluidState(BlockPos pos) { return level.getFluidState(pos); }
|
||||
@Override public int getHeight(Heightmap.Types type, int x, int z) { return level.getHeight(type, x, z); }
|
||||
}
|
||||
|
||||
static final class Source extends ServerChunkCache {
|
||||
Source() { super(null, null, null, null, null, null, 0, 0, false, null); }
|
||||
ChunkGenerator generator;
|
||||
@Override public ChunkGenerator getGenerator() { return generator; }
|
||||
}
|
||||
|
||||
/** getPlayersCloseForSpawning: none past the natural spawn chunk tracker's 8 chunks, else non-spectators within 128 blocks of the chunk centre. */
|
||||
static final class Map2 extends ChunkMap {
|
||||
Map2() { super(null, null, null, null, null, null, null, null, null, null, 0, false); }
|
||||
Lvl level;
|
||||
@Override public List<ServerPlayer> getPlayersCloseForSpawning(ChunkPos pos) {
|
||||
boolean tracked = false;
|
||||
for (ServerPlayer p : level.playerList) {
|
||||
int px = Mth.floor(p.getX()) >> 4, pz = Mth.floor(p.getZ()) >> 4;
|
||||
if (Math.max(Math.abs(px - pos.x()), Math.abs(pz - pos.z())) <= 8) tracked = true;
|
||||
}
|
||||
if (!tracked) return List.of();
|
||||
List<ServerPlayer> out = new ArrayList<>();
|
||||
for (ServerPlayer p : level.playerList) {
|
||||
double xd = pos.x() * 16 + 8 - p.getX(), zd = pos.z() * 16 + 8 - p.getZ();
|
||||
if (!p.isSpectator() && xd * xd + zd * zd < 16384.0) out.add(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
static final class Structures extends StructureManager {
|
||||
Structures() { super(null, null, null); }
|
||||
Lvl level;
|
||||
List<Start> referenced(int x, int z) {
|
||||
int cx = x >> 4, cz = z >> 4;
|
||||
List<Start> out = new ArrayList<>();
|
||||
for (Start s : level.starts) {
|
||||
BoundingBox b = s.start().getBoundingBox();
|
||||
if (b.intersects(cx * 16, cz * 16, cx * 16 + 15, cz * 16 + 15)) out.add(s);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@Override public Map<Structure, LongSet> getAllStructuresAt(int x, int y, int z) {
|
||||
Map<Structure, LongSet> out = new LinkedHashMap<>();
|
||||
for (Start s : referenced(x, z)) out.computeIfAbsent(s.structure(), k -> new LongOpenHashSet()).add(level.starts.indexOf(s));
|
||||
return out;
|
||||
}
|
||||
@Override public void fillStartsForStructure(Structure structure, LongSet references, Consumer<StructureStart> consumer) {
|
||||
for (long i : references) {
|
||||
StructureStart start = level.starts.get((int) i).start();
|
||||
if (start.isValid()) consumer.accept(start);
|
||||
}
|
||||
}
|
||||
@Override public List<StructureStart> startsForStructure(int sectionX, int sectionZ, Structure structure) {
|
||||
List<StructureStart> out = new ArrayList<>();
|
||||
for (Start s : referenced(sectionX << 4, sectionZ << 4)) if (s.structure() == structure) out.add(s.start());
|
||||
return out;
|
||||
}
|
||||
@Override public RegistryAccess registryAccess() { return level.registries; }
|
||||
}
|
||||
|
||||
static final class Piece extends StructurePiece {
|
||||
Piece(BoundingBox box) { super(null, 0, box); }
|
||||
@Override protected void addAdditionalSaveData(StructurePieceSerializationContext context, CompoundTag tag) {}
|
||||
@Override public void postProcess(WorldGenLevel level, StructureManager structureManager, ChunkGenerator generator, RandomSource random,
|
||||
BoundingBox chunkBB, ChunkPos chunkPos, BlockPos referencePos) {}
|
||||
}
|
||||
|
||||
static final class OraclePlayer extends ServerPlayer {
|
||||
OraclePlayer() { super(null, null, null, null); }
|
||||
GameType mode;
|
||||
@Override public boolean isSpectator() { return mode == GameType.SPECTATOR; }
|
||||
@Override public boolean isCreative() { return mode == GameType.CREATIVE; }
|
||||
@Override public GameType gameMode() { return mode; }
|
||||
}
|
||||
|
||||
static String bits(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); }
|
||||
/**
|
||||
* A spawned mob's yaw. A cube mob whose size finalizeSpawn changed took its
|
||||
* constructor's head rotation (AbstractCubeMob.onSyncedDataUpdated), drawn
|
||||
* from the entity's own unseeded random: not reproducible, so not compared.
|
||||
*/
|
||||
static String yaw(Entity e) {
|
||||
if (e instanceof net.minecraft.world.entity.monster.cubemob.AbstractCubeMob cube && cube.getSize() != 1) return "head";
|
||||
return bits(e.getYRot());
|
||||
}
|
||||
static String bits(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class);
|
||||
objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class);
|
||||
var repo = ServerPacksSource.createVanillaTrustedRepository();
|
||||
repo.reload();
|
||||
repo.setSelected(List.of("vanilla"));
|
||||
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
|
||||
var layers = RegistryLayer.createRegistryAccess();
|
||||
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
|
||||
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
|
||||
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
|
||||
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world);
|
||||
var loaded = net.minecraft.server.ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
|
||||
HolderLookup.Provider lookup = loaded.lookupWithUpdatedTags();
|
||||
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply);
|
||||
RegistryAccess access = loaded.layers().compositeAccess();
|
||||
var biomes = access.lookupOrThrow(Registries.BIOME);
|
||||
var dimensions = access.lookupOrThrow(Registries.DIMENSION_TYPE);
|
||||
var blockLookup = access.lookupOrThrow(Registries.BLOCK);
|
||||
var structureLookup = access.lookupOrThrow(Registries.STRUCTURE);
|
||||
|
||||
// A server that only answers debug subscribers (path navigation asks).
|
||||
var server = (net.minecraft.server.MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class);
|
||||
put(server, net.minecraft.server.MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class));
|
||||
Lvl level = (Lvl) alloc(Lvl.class);
|
||||
level.fake = server;
|
||||
put(level, ServerLevel.class, "server", server);
|
||||
level.registries = access;
|
||||
level.blocks = new ArrayList<>();
|
||||
level.lights = new ArrayList<>();
|
||||
level.biomes = new ArrayList<>();
|
||||
level.unloaded = new HashSet<>();
|
||||
level.starts = new ArrayList<>();
|
||||
level.entities = new ArrayList<>();
|
||||
level.playerList = new ArrayList<>();
|
||||
level.border = new WorldBorder();
|
||||
level.neutral = new Neutral();
|
||||
level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags());
|
||||
level.biomeManager = new BiomeManager((x, y, z) -> level.biome, 0L) {
|
||||
@Override public Holder<Biome> getBiome(BlockPos pos) { return level.biomeAt(pos.getX(), pos.getY(), pos.getZ()); }
|
||||
@Override public Holder<Biome> getBiome(int x, int y, int z) { return level.biomeAt(x, y, z); }
|
||||
};
|
||||
Source source = (Source) alloc(Source.class);
|
||||
source.generator = (ChunkGenerator) alloc(FlatLevelSource.class);
|
||||
level.chunkSource = source;
|
||||
Structures structures = (Structures) alloc(Structures.class);
|
||||
structures.level = level;
|
||||
level.structures = structures;
|
||||
Map2 chunkMap = (Map2) alloc(Map2.class);
|
||||
chunkMap.level = level;
|
||||
|
||||
Method createState = NaturalSpawner.class.getMethod("createState", int.class, ServerLevel.class, NaturalSpawner.ChunkGetter.class, LocalMobCapCalculator.class);
|
||||
Method canSpawn = NaturalSpawner.SpawnState.class.getDeclaredMethod("canSpawn", EntityType.class, Level.class, BlockPos.class, net.minecraft.world.level.chunk.ChunkAccess.class);
|
||||
canSpawn.setAccessible(true);
|
||||
Method afterSpawn = NaturalSpawner.SpawnState.class.getDeclaredMethod("afterSpawn", Mob.class, net.minecraft.world.level.chunk.ChunkAccess.class);
|
||||
afterSpawn.setAccessible(true);
|
||||
Method local = NaturalSpawner.SpawnState.class.getDeclaredMethod("canSpawnForCategoryLocal", MobCategory.class, ChunkPos.class);
|
||||
local.setAccessible(true);
|
||||
Method randomPos = NaturalSpawner.class.getDeclaredMethod("getRandomPosWithin", Level.class, LevelChunk.class);
|
||||
randomPos.setAccessible(true);
|
||||
Field entityId = Entity.class.getDeclaredField("id");
|
||||
entityId.setAccessible(true);
|
||||
|
||||
List<String> lines = Files.readAllLines(Path.of(args[0]));
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (String raw : lines) {
|
||||
if (raw.isBlank()) continue;
|
||||
Map<String, String> c = new LinkedHashMap<>();
|
||||
for (String token : raw.trim().split("\\s+")) {
|
||||
int eq = token.indexOf('=');
|
||||
if (eq < 0) c.put("name", token); else c.put(token.substring(0, eq), token.substring(eq + 1));
|
||||
}
|
||||
List<String> log = new ArrayList<>();
|
||||
level.log = log;
|
||||
level.logColumns = false;
|
||||
try {
|
||||
level.dimensionKey = ResourceKey.create(Registries.DIMENSION, Identifier.parse(c.getOrDefault("dim", "minecraft:overworld")));
|
||||
level.dimensionType = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, level.dimensionKey.identifier())).value();
|
||||
level.blocks.clear();
|
||||
for (int i = 0; c.containsKey("k" + i); i++) {
|
||||
String[] p = c.get("k" + i).split("/", 2);
|
||||
level.blocks.add(Map.entry(Box.parse(p[0]), net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blockLookup, p[1], false).blockState()));
|
||||
}
|
||||
level.lights.clear();
|
||||
for (int i = 0; c.containsKey("l" + i); i++) {
|
||||
String[] p = c.get("l" + i).split("/", 2);
|
||||
String[] v = p[1].split(",");
|
||||
level.lights.add(Map.entry(Box.parse(p[0]), new int[] {Integer.parseInt(v[0]), Integer.parseInt(v[1])}));
|
||||
}
|
||||
level.biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(c.getOrDefault("biome", "minecraft:plains"))));
|
||||
level.biomes.clear();
|
||||
for (int i = 0; c.containsKey("b" + i); i++) {
|
||||
String[] p = c.get("b" + i).split("/", 2);
|
||||
level.biomes.add(Map.entry(Box.parse(p[0]), biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(p[1])))));
|
||||
}
|
||||
level.sky = Integer.parseInt(c.getOrDefault("sky", "15"));
|
||||
level.block = Integer.parseInt(c.getOrDefault("light", "0"));
|
||||
level.darken = Integer.parseInt(c.getOrDefault("darken", "0"));
|
||||
level.thunder = c.getOrDefault("thunder", "0").equals("1");
|
||||
level.sea = Integer.parseInt(c.getOrDefault("sea", "63"));
|
||||
level.seed = Long.parseLong(c.getOrDefault("wseed", "0"));
|
||||
level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal"));
|
||||
level.rules.set(net.minecraft.world.level.gamerules.GameRules.SPAWN_MOBS, !c.getOrDefault("rules", "1").equals("0"), null);
|
||||
// The dimension and biome layers; the moon timeline's surface slime chance as a constant.
|
||||
level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addStaticLayers(level)
|
||||
.addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder()
|
||||
.set(net.minecraft.world.attribute.EnvironmentAttributes.SURFACE_SLIME_SPAWN_CHANCE, Float.parseFloat(c.getOrDefault("slime", "0.0"))).build())
|
||||
.build();
|
||||
level.unloaded.clear();
|
||||
if (c.containsKey("unloaded")) for (String u : c.get("unloaded").split(";")) {
|
||||
String[] p = u.split(",");
|
||||
level.unloaded.add(ChunkPos.pack(Integer.parseInt(p[0]), Integer.parseInt(p[1])));
|
||||
}
|
||||
level.starts.clear();
|
||||
for (int i = 0; c.containsKey("s" + i); i++) {
|
||||
String[] p = c.get("s" + i).split("/", 2);
|
||||
Structure structure = structureLookup.getValue(Identifier.parse(p[0]));
|
||||
List<StructurePiece> pieces = new ArrayList<>();
|
||||
for (String b : p[1].split(";")) {
|
||||
Box bx = Box.parse(b);
|
||||
pieces.add(new Piece(new BoundingBox(bx.x0(), bx.y0(), bx.z0(), bx.x1(), bx.y1(), bx.z1())));
|
||||
}
|
||||
level.starts.add(new Start(structure, new StructureStart(structure, new ChunkPos(0, 0), 0, new PiecesContainer(pieces))));
|
||||
}
|
||||
String[] r = c.getOrDefault("respawn", "0,-1000,0/minecraft:overworld").split("/");
|
||||
String[] rp = r[0].split(",");
|
||||
level.respawn = new LevelData.RespawnData(GlobalPos.of(ResourceKey.create(Registries.DIMENSION, Identifier.parse(r[1])),
|
||||
new BlockPos(Integer.parseInt(rp[0]), Integer.parseInt(rp[1]), Integer.parseInt(rp[2]))), 0.0F, 0.0F);
|
||||
level.playerList.clear();
|
||||
for (int i = 0; c.containsKey("p" + i); i++) {
|
||||
String[] p = c.get("p" + i).split("/");
|
||||
String[] v = p[0].split(",");
|
||||
OraclePlayer player = (OraclePlayer) alloc(OraclePlayer.class);
|
||||
player.mode = GameType.byName(p.length > 1 ? p[1] : "survival");
|
||||
entityId.setInt(player, 100000 + i);
|
||||
put(player, Entity.class, "position", new Vec3(Double.parseDouble(v[0]), Double.parseDouble(v[1]), Double.parseDouble(v[2])));
|
||||
level.playerList.add(player);
|
||||
}
|
||||
level.entities.clear();
|
||||
for (int i = 0; c.containsKey("e" + i); i++) {
|
||||
String[] p = c.get("e" + i).split("/");
|
||||
String[] v = p[1].split(",");
|
||||
Entity e = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(p[0])).create(level, EntitySpawnReason.LOAD);
|
||||
if (e == null) continue; // monsters do not exist in peaceful
|
||||
e.setPos(Double.parseDouble(v[0]), Double.parseDouble(v[1]), Double.parseDouble(v[2]));
|
||||
if (p.length > 2 && p[2].equals("p") && e instanceof Mob mob) mob.setPersistenceRequired();
|
||||
level.entities.add(e);
|
||||
}
|
||||
RandomSource mainRandom = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0")));
|
||||
put(level, Level.class, "random", mainRandom);
|
||||
String mode = c.getOrDefault("mode", "chunk");
|
||||
String[] cp = c.getOrDefault("chunk", "0,0").split(",");
|
||||
Chunk chunk = (Chunk) alloc(Chunk.class);
|
||||
chunk.level = level;
|
||||
chunk.at = new ChunkPos(Integer.parseInt(cp[0]), Integer.parseInt(cp[1]));
|
||||
if (mode.equals("gen")) {
|
||||
level.logColumns = true;
|
||||
int n = level.entities.size();
|
||||
RandomSource random = RandomSource.create(Long.parseLong(c.getOrDefault("gseed", "0")));
|
||||
BlockPos sourcePos = new BlockPos(chunk.at.getMinBlockX(), level.getMaxY(), chunk.at.getMinBlockZ());
|
||||
NaturalSpawner.spawnMobsForChunkGeneration(level, sourcePos, chunk.at, random);
|
||||
level.logColumns = false;
|
||||
for (Entity e : level.entities.subList(n, level.entities.size()))
|
||||
if (e.getVehicle() == null)
|
||||
log.add("spawn " + BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()) + " " + bits(e.getX()) + " " + bits(e.getY()) + " " + bits(e.getZ()) + " " + yaw(e));
|
||||
log.add("next " + random.nextInt(1000));
|
||||
} else {
|
||||
Map<Long, Chunk> chunks = new HashMap<>();
|
||||
NaturalSpawner.ChunkGetter getter = (key, consumer) -> {
|
||||
if (level.unloaded.contains(key)) return;
|
||||
Chunk k = chunks.computeIfAbsent(key, kk -> {
|
||||
try {
|
||||
Chunk made = (Chunk) alloc(Chunk.class);
|
||||
made.level = level;
|
||||
made.at = ChunkPos.unpack(kk);
|
||||
return made;
|
||||
} catch (Exception ex) { throw new RuntimeException(ex); }
|
||||
});
|
||||
consumer.accept(k);
|
||||
};
|
||||
var state = (NaturalSpawner.SpawnState) createState.invoke(null, Integer.parseInt(c.getOrDefault("chunkcount", "289")), level, getter, new LocalMobCapCalculator(chunkMap));
|
||||
NaturalSpawner.SpawnPredicate extra = (type, lvl, pos, ch) -> {
|
||||
try {
|
||||
boolean ok = (boolean) canSpawn.invoke(state, type, lvl, pos, ch);
|
||||
log.add("test " + BuiltInRegistries.ENTITY_TYPE.getKey(type) + " " + pos.getX() + " " + pos.getY() + " " + pos.getZ() + " " + ok);
|
||||
return ok;
|
||||
} catch (Exception ex) { throw new RuntimeException(ex); }
|
||||
};
|
||||
NaturalSpawner.AfterSpawnCallback after = (mob, ch) -> {
|
||||
log.add("spawn " + BuiltInRegistries.ENTITY_TYPE.getKey(mob.getType()) + " " + bits(mob.getX()) + " " + bits(mob.getY()) + " " + bits(mob.getZ()) + " " + yaw(mob));
|
||||
try { afterSpawn.invoke(state, mob, ch); } catch (Exception ex) { throw new RuntimeException(ex); }
|
||||
};
|
||||
if (mode.equals("pos")) {
|
||||
MobCategory category = MobCategory.valueOf(c.get("cat").toUpperCase(Locale.ROOT));
|
||||
String[] sp = c.get("start").split(",");
|
||||
BlockPos start = new BlockPos(Integer.parseInt(sp[0]), Integer.parseInt(sp[1]), Integer.parseInt(sp[2]));
|
||||
NaturalSpawner.spawnCategoryForPosition(category, level, chunk, start, extra, after);
|
||||
} else {
|
||||
List<MobCategory> categories = NaturalSpawner.getFilteredSpawningCategories(state, c.getOrDefault("enemies", "1").equals("1"), c.getOrDefault("persistent", "1").equals("1"));
|
||||
StringBuilder names = new StringBuilder();
|
||||
for (MobCategory m : categories) names.append(names.isEmpty() ? "" : ",").append(m.getSerializedName());
|
||||
log.add("cats " + names);
|
||||
// spawnForChunk, then spawnCategoryForChunk with its start logged.
|
||||
for (MobCategory category : categories) {
|
||||
boolean ok = (boolean) local.invoke(state, category, chunk.at);
|
||||
log.add("local " + category.getSerializedName() + " " + ok);
|
||||
if (!ok) continue;
|
||||
BlockPos start = (BlockPos) randomPos.invoke(null, level, chunk);
|
||||
log.add("start " + category.getSerializedName() + " " + start.getX() + " " + start.getY() + " " + start.getZ());
|
||||
if (start.getY() >= level.getMinY() + 1) NaturalSpawner.spawnCategoryForPosition(category, level, chunk, start, extra, after);
|
||||
}
|
||||
}
|
||||
log.add("next " + mainRandom.nextInt(1000));
|
||||
}
|
||||
w.println(c.get("name") + " " + String.join(" ; ", log));
|
||||
} catch (Throwable t) {
|
||||
Throwable cause = t;
|
||||
while ((cause instanceof InvocationTargetException || cause instanceof RuntimeException && cause.getCause() != null) && cause.getCause() != null) cause = cause.getCause();
|
||||
StringBuilder line = new StringBuilder(c.get("name") + " error " + cause);
|
||||
if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) line.append("\n at ").append(frame);
|
||||
w.println(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.ProtocolInfo;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.configuration.ConfigurationProtocols;
|
||||
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
|
||||
import net.minecraft.network.protocol.game.GameProtocols;
|
||||
import net.minecraft.network.protocol.login.LoginProtocols;
|
||||
import net.minecraft.network.protocol.status.StatusProtocols;
|
||||
import net.minecraft.world.level.chunk.LevelChunkSection;
|
||||
import net.minecraft.world.level.chunk.PalettedContainerFactory;
|
||||
|
||||
/**
|
||||
* Checks a capture written by tools/net_capture.py against vanilla's own
|
||||
* packet codecs: every clientbound packet a server sent (login,
|
||||
* configuration and play) must decode with vanilla's StreamCodec, consume
|
||||
* its whole payload, and encode back to the same bytes, so the bytes are
|
||||
* exactly what vanilla would have written for that packet. Chunk data is
|
||||
* decoded section by section and the stored block counts are checked
|
||||
* against a recount. Prints one line per packet:
|
||||
* conn dir state name ok|ERROR|REENCODE|SECTIONS detail
|
||||
* and a summary per packet type at the end.
|
||||
*/
|
||||
public final class VanillaPacketCodecOracle {
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
Path capture = Path.of(args[0]);
|
||||
boolean verbose = args.length > 2 && args[2].equals("--verbose");
|
||||
var play = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access));
|
||||
var factory = PalettedContainerFactory.create(ParityData.access);
|
||||
Field nonEmpty = LevelChunkSection.class.getDeclaredField("nonEmptyBlockCount");
|
||||
Field fluids = LevelChunkSection.class.getDeclaredField("fluidCount");
|
||||
nonEmpty.setAccessible(true);
|
||||
fluids.setAccessible(true);
|
||||
Map<String, int[]> totals = new TreeMap<>();
|
||||
int failures = 0;
|
||||
try (BufferedReader in = Files.newBufferedReader(capture);
|
||||
PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])))) {
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
if (line.isBlank()) continue;
|
||||
JsonObject e = JsonParser.parseString(line).getAsJsonObject();
|
||||
if (!e.has("name") || !e.get("dir").getAsString().equals("s2c")) continue;
|
||||
String state = e.get("state").getAsString();
|
||||
String name = e.get("name").getAsString();
|
||||
String key = state + "/" + name;
|
||||
int[] t = totals.computeIfAbsent(key, k -> new int[2]);
|
||||
t[0]++;
|
||||
if (!e.has("data")) {
|
||||
out.println(e.get("conn") + " s2c " + key + " SKIPPED payload not captured");
|
||||
t[1]++;
|
||||
failures++;
|
||||
continue;
|
||||
}
|
||||
byte[] payload = HexFormat.of().parseHex(e.get("data").getAsString());
|
||||
ProtocolInfo<?> protocol = switch (state) {
|
||||
case "status" -> StatusProtocols.CLIENTBOUND;
|
||||
case "login" -> LoginProtocols.CLIENTBOUND;
|
||||
case "configuration" -> ConfigurationProtocols.CLIENTBOUND;
|
||||
case "play" -> play;
|
||||
default -> null;
|
||||
};
|
||||
if (protocol == null) continue;
|
||||
ByteBuf original = Unpooled.buffer();
|
||||
new FriendlyByteBuf(original).writeVarInt(e.get("id").getAsInt());
|
||||
original.writeBytes(payload);
|
||||
byte[] framed = new byte[original.readableBytes()];
|
||||
original.getBytes(0, framed);
|
||||
String verdict;
|
||||
String detail = "";
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
var codec = (net.minecraft.network.codec.StreamCodec<ByteBuf, Packet<?>>) (Object) protocol.codec();
|
||||
Packet<?> packet = codec.decode(original);
|
||||
if (original.readableBytes() != 0) {
|
||||
verdict = "ERROR";
|
||||
detail = original.readableBytes() + " bytes left after decoding " + packet;
|
||||
} else {
|
||||
ByteBuf again = Unpooled.buffer();
|
||||
codec.encode(again, packet);
|
||||
byte[] encoded = new byte[again.readableBytes()];
|
||||
again.getBytes(0, encoded);
|
||||
if (!java.util.Arrays.equals(encoded, framed)) {
|
||||
verdict = "REENCODE";
|
||||
detail = firstDifference(framed, encoded) + " " + abbreviate(packet.toString());
|
||||
} else if (packet instanceof ClientboundLevelChunkWithLightPacket chunk) {
|
||||
String problem = checkSections(chunk, factory, nonEmpty, fluids);
|
||||
verdict = problem == null ? "ok" : "SECTIONS";
|
||||
detail = problem == null ? "" : problem;
|
||||
} else {
|
||||
verdict = "ok";
|
||||
if (verbose) detail = abbreviate(packet.toString());
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
verdict = "ERROR";
|
||||
detail = ex.toString();
|
||||
}
|
||||
if (!verdict.equals("ok")) {
|
||||
t[1]++;
|
||||
failures++;
|
||||
}
|
||||
if (!verdict.equals("ok") || verbose) {
|
||||
out.println(e.get("conn") + " s2c " + key + " " + verdict + " " + detail);
|
||||
}
|
||||
}
|
||||
out.println("# packet type, count, failures");
|
||||
for (var entry : totals.entrySet()) {
|
||||
out.println("# " + entry.getKey() + " " + entry.getValue()[0] + " " + entry.getValue()[1]);
|
||||
}
|
||||
out.println("# failures " + failures);
|
||||
}
|
||||
System.exit(failures == 0 ? 0 : 1);
|
||||
}
|
||||
|
||||
static String checkSections(ClientboundLevelChunkWithLightPacket chunk, PalettedContainerFactory factory,
|
||||
Field nonEmpty, Field fluids) throws Exception {
|
||||
FriendlyByteBuf buf = chunk.chunkData().getReadBuffer();
|
||||
int index = 0;
|
||||
while (buf.isReadable()) {
|
||||
int start = buf.readerIndex();
|
||||
short storedBlocks = buf.getShort(start);
|
||||
short storedFluids = buf.getShort(start + 2);
|
||||
LevelChunkSection section = new LevelChunkSection(factory);
|
||||
section.read(buf);
|
||||
section.recalcBlockCounts();
|
||||
int blocks = (short) (int) nonEmpty.get(section);
|
||||
int fluidCount = (short) (int) fluids.get(section);
|
||||
if (blocks != storedBlocks || fluidCount != storedFluids) {
|
||||
return "section " + index + " of " + chunk.x() + "," + chunk.z() + " stores " + storedBlocks + " blocks/"
|
||||
+ storedFluids + " fluids, recount " + blocks + "/" + fluidCount;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
if (index != 24 && index != 16) return index + " sections in " + chunk.x() + "," + chunk.z();
|
||||
return null;
|
||||
}
|
||||
|
||||
static String firstDifference(byte[] a, byte[] b) {
|
||||
int n = Math.min(a.length, b.length);
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (a[i] != b[i]) return "differs at byte " + i + " of " + a.length + " (vanilla writes " + b.length + ")";
|
||||
}
|
||||
return "lengths " + a.length + " vs vanilla " + b.length;
|
||||
}
|
||||
|
||||
static String abbreviate(String s) {
|
||||
s = s.replace('\n', ' ');
|
||||
return s.length() > 400 ? s.substring(0, 400) + "..." : s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.client.Camera;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.Gui;
|
||||
import net.minecraft.client.gui.Hud;
|
||||
import net.minecraft.client.gui.components.BossHealthOverlay;
|
||||
import net.minecraft.client.gui.components.LerpingBossEvent;
|
||||
import net.minecraft.client.gui.screens.WinScreen;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.sounds.Music;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.world.BossEvent;
|
||||
import net.minecraft.world.attribute.*;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.player.Abilities;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Calls the real Minecraft.getSituationalMusic and getMusicVolume on shells
|
||||
* holding the open screen (none or the credits' WinScreen), the boss overlay's
|
||||
* events, the player (its level's dimension, abilities and underwater state)
|
||||
* and a real camera EnvironmentAttributeProbe over the dimension and biome's
|
||||
* attribute layers from the vanilla data pack. Lines: "screen player
|
||||
* dimension biome boss instabuild mayfly underwater".
|
||||
*/
|
||||
public final class VanillaSituationalMusicOracle {
|
||||
static String music(Music m) {
|
||||
return m == null ? "-" : m.sound().value().location() + "," + m.minDelay() + "," + m.maxDelay() + "," + m.replaceCurrentMusic();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private static void addBiome(EnvironmentAttributeSystem.Builder b, EnvironmentAttribute attr, Biome biome) {
|
||||
b.addPositionalLayer(attr, (base, pos, w) -> biome.getAttributes().applyModifier(attr, base));
|
||||
}
|
||||
|
||||
static LerpingBossEvent bar(boolean darken, boolean music) {
|
||||
return new LerpingBossEvent(UUID.randomUUID(), Component.empty(), 1.0F, BossEvent.BossBarColor.PINK, BossEvent.BossBarOverlay.PROGRESS,
|
||||
darken, music, false);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
var repo = ServerPacksSource.createVanillaTrustedRepository();
|
||||
repo.reload();
|
||||
repo.setSelected(List.of("vanilla"));
|
||||
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
|
||||
var layers = RegistryLayer.createRegistryAccess();
|
||||
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
|
||||
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
|
||||
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
var dimensions = world.lookupOrThrow(Registries.DIMENSION_TYPE);
|
||||
var biomes = world.lookupOrThrow(Registries.BIOME);
|
||||
|
||||
Minecraft mc = VanillaSoundRig.make(Minecraft.class);
|
||||
Gui gui = VanillaSoundRig.make(Gui.class);
|
||||
Hud hud = VanillaSoundRig.make(Hud.class);
|
||||
BossHealthOverlay overlay = VanillaSoundRig.make(BossHealthOverlay.class);
|
||||
Map<UUID, LerpingBossEvent> events = new LinkedHashMap<>();
|
||||
VanillaSoundRig.set(overlay, BossHealthOverlay.class, "events", events);
|
||||
VanillaSoundRig.set(hud, Hud.class, "bossOverlay", overlay);
|
||||
VanillaSoundRig.set(gui, Gui.class, "hud", hud);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "gui", gui);
|
||||
GameRenderer renderer = VanillaSoundRig.make(GameRenderer.class);
|
||||
Camera camera = VanillaSoundRig.make(Camera.class);
|
||||
VanillaSoundRig.set(renderer, GameRenderer.class, "mainCamera", camera);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "gameRenderer", renderer);
|
||||
WinScreen credits = VanillaSoundRig.make(WinScreen.class);
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (String line : Files.readAllLines(Path.of(args[0]), StandardCharsets.UTF_8)) {
|
||||
String[] f = line.split(" ");
|
||||
VanillaSoundRig.set(gui, Gui.class, "screen", f[0].equals("win") ? credits : null);
|
||||
events.clear();
|
||||
if (f[4].contains("dark")) events.put(UUID.randomUUID(), bar(true, false));
|
||||
if (f[4].contains("music")) events.put(UUID.randomUUID(), bar(false, true));
|
||||
var probe = new EnvironmentAttributeProbe();
|
||||
VanillaSoundRig.set(camera, Camera.class, "attributeProbe", probe);
|
||||
if (f[1].equals("1")) {
|
||||
DimensionType dim = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(f[2]))).value();
|
||||
Biome biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(f[3]))).value();
|
||||
var b = EnvironmentAttributeSystem.builder();
|
||||
b.addConstantLayer(dim.attributes());
|
||||
for (EnvironmentAttribute<?> attr : biome.getAttributes().keySet()) addBiome(b, attr, biome);
|
||||
ClientLevel level = VanillaSoundRig.make(ClientLevel.class);
|
||||
VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", b.build());
|
||||
VanillaSoundRig.set(level, Level.class, "dimension", f[2].equals("minecraft:the_end") ? Level.END
|
||||
: f[2].equals("minecraft:the_nether") ? Level.NETHER : Level.OVERWORLD);
|
||||
VanillaSoundRig.set(probe, EnvironmentAttributeProbe.class, "level", level);
|
||||
VanillaSoundRig.set(probe, EnvironmentAttributeProbe.class, "position", new Vec3(0.5, 64.0, 0.5));
|
||||
LocalPlayer player = VanillaSoundRig.make(LocalPlayer.class);
|
||||
VanillaSoundRig.set(player, Entity.class, "level", level);
|
||||
var abilities = new Abilities();
|
||||
abilities.instabuild = f[5].equals("1");
|
||||
abilities.mayfly = f[6].equals("1");
|
||||
VanillaSoundRig.set(player, Player.class, "abilities", abilities);
|
||||
VanillaSoundRig.set(player, Player.class, "wasUnderwater", f[7].equals("1"));
|
||||
mc.player = player;
|
||||
} else {
|
||||
mc.player = null;
|
||||
}
|
||||
w.printf("%s music=%s volume=%08x%n", line, music(mc.getSituationalMusic()), Float.floatToRawIntBits(mc.getMusicVolume()));
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.resources.sounds.*;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
|
||||
/**
|
||||
* Drives the real SoundEngine (see VanillaSoundRig) with a script of plays,
|
||||
* stops, category gains, option volumes, channel ends, pauses and ticks, and
|
||||
* prints after every step each instance's activity and AL source parameters,
|
||||
* the subtitle notifications and the channel pool counts.
|
||||
*/
|
||||
public final class VanillaSoundEngineOracle {
|
||||
/** The local player the underwater instances look at. */
|
||||
public static final class Actor extends LocalPlayer {
|
||||
boolean underwater;
|
||||
|
||||
Actor() {
|
||||
super(null, null, null, null, null, null, false, null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnderWater() {
|
||||
return underwater;
|
||||
}
|
||||
}
|
||||
|
||||
static float f(String hex) {
|
||||
return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16));
|
||||
}
|
||||
|
||||
static double d(String hex) {
|
||||
return Double.longBitsToDouble(Long.parseUnsignedLong(hex, 16));
|
||||
}
|
||||
|
||||
static void seed(SoundInstance instance, long seed) throws Exception {
|
||||
VanillaSoundRig.set(instance, AbstractSoundInstance.class, "random", RandomSource.create(seed));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var rig = new VanillaSoundRig(Path.of(args[0]));
|
||||
var actor = VanillaSoundRig.make(Actor.class);
|
||||
Constructor<UnderLiquidSubSound> sub = UnderLiquidSubSound.class.getDeclaredConstructor(LocalPlayer.class, SoundEvent.class);
|
||||
sub.setAccessible(true);
|
||||
var instances = new TreeMap<String, SoundInstance>();
|
||||
var manager = rig.manager;
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) {
|
||||
for (String line : Files.readAllLines(Path.of(args[1]))) {
|
||||
out.println(line);
|
||||
String[] a = line.split(" ");
|
||||
switch (a[0]) {
|
||||
case "play" -> {
|
||||
// play name kind event source volume pitch x y z looping delay attenuation relative seed
|
||||
Identifier id = Identifier.parse(a[3]);
|
||||
SoundEvent event = SoundEvent.createVariableRangeEvent(id);
|
||||
long seed = Long.parseLong(a[14]);
|
||||
SoundInstance instance = switch (a[2]) {
|
||||
case "simple" -> new SimpleSoundInstance(id, SoundSource.values()[Integer.parseInt(a[4])], f(a[5]), f(a[6]),
|
||||
RandomSource.create(seed), a[10].equals("1"), Integer.parseInt(a[11]),
|
||||
a[12].equals("linear") ? SoundInstance.Attenuation.LINEAR : SoundInstance.Attenuation.NONE, d(a[7]), d(a[8]), d(a[9]),
|
||||
a[13].equals("1"));
|
||||
case "loop" -> new BiomeAmbientSoundsHandler.LoopSoundInstance(event);
|
||||
case "uloop" -> new UnderLiquidAmbientSoundInstance(event, actor, LocalPlayer::isUnderWater);
|
||||
case "usub" -> sub.newInstance(actor, event);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
};
|
||||
if (!a[2].equals("simple")) seed(instance, seed);
|
||||
instances.put(a[1], instance);
|
||||
out.println(" result " + manager.play(instance));
|
||||
}
|
||||
case "replay" -> out.println(" result " + manager.play(instances.get(a[1])));
|
||||
case "queue" -> manager.queueTickingSound((TickableSoundInstance) instances.get(a[1]));
|
||||
case "delayed" -> manager.playDelayed(instances.get(a[1]), Integer.parseInt(a[2]));
|
||||
case "fade" -> {
|
||||
if (instances.get(a[1]) instanceof BiomeAmbientSoundsHandler.LoopSoundInstance loop) {
|
||||
if (a[2].equals("in")) loop.fadeIn(); else loop.fadeOut();
|
||||
}
|
||||
}
|
||||
case "stop" -> manager.stop(instances.get(a[1]));
|
||||
case "stopmatch" -> manager.stop(a[1].equals("-") ? null : Identifier.parse(a[1]),
|
||||
a[2].equals("-") ? null : SoundSource.values()[Integer.parseInt(a[2])]);
|
||||
case "finish" -> rig.finish(instances.get(a[1]));
|
||||
case "gain" -> manager.updateCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2]));
|
||||
case "volume" -> rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2]));
|
||||
case "refresh" -> manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]);
|
||||
case "pause" -> manager.pauseAllExcept(SoundSource.MUSIC, SoundSource.UI);
|
||||
case "resume" -> manager.resume();
|
||||
case "player" -> {
|
||||
actor.underwater = a[1].equals("1");
|
||||
VanillaSoundRig.set(actor, Entity.class, "removalReason", a[2].equals("1") ? Entity.RemovalReason.DISCARDED : null);
|
||||
}
|
||||
case "tick" -> manager.tick(a[1].equals("1"));
|
||||
case "forget" -> instances.remove(a[1]);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
for (var e : instances.entrySet()) out.println(rig.describe(e.getKey(), e.getValue()));
|
||||
rig.flush(out);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.Options;
|
||||
import net.minecraft.client.resources.sounds.*;
|
||||
import net.minecraft.client.sounds.*;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.contents.TranslatableContents;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.packs.*;
|
||||
import net.minecraft.server.packs.repository.PackSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.server.packs.resources.ResourceManager;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.util.profiling.InactiveProfiler;
|
||||
|
||||
/**
|
||||
* Builds vanilla's sound event registry with the real SoundManager.prepare
|
||||
* (sounds.json read through a resource manager over the client asset root,
|
||||
* files validated against the listed .ogg resources) and Preparations.apply,
|
||||
* then resolves SimpleSoundInstances: getOrResolve with a seeded random,
|
||||
* getVolume/getPitch, and the instance random's next draw (to fix the number
|
||||
* of draws). Lines: "event seed volume pitch".
|
||||
*/
|
||||
public final class VanillaSoundEventOracle {
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
var f = type.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
static String bits(float v) {
|
||||
return String.format("%08x", Float.floatToRawIntBits(v));
|
||||
}
|
||||
|
||||
static String sentinel(Sound sound) {
|
||||
if (sound == SoundManager.EMPTY_SOUND) return "empty";
|
||||
if (sound == SoundManager.INTENTIONALLY_EMPTY_SOUND) return "intentionally_empty";
|
||||
return "-";
|
||||
}
|
||||
|
||||
/** The real registry, prepared from an asset root. */
|
||||
@SuppressWarnings("unchecked")
|
||||
static SoundManager load(Path root) throws Exception {
|
||||
var info = new PackLocationInfo("horizon", Component.literal("horizon"), PackSource.BUILT_IN, Optional.empty());
|
||||
ResourceManager resources = new MultiPackResourceManager(PackType.CLIENT_RESOURCES, List.of(new PathPackResources(info, root)));
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
Object unsafe = field(u, "theUnsafe").get(null);
|
||||
Options options = (Options) u.getMethod("allocateInstance", Class.class).invoke(unsafe, Options.class);
|
||||
var manager = new SoundManager(options);
|
||||
Method prepare = SoundManager.class.getDeclaredMethod("prepare", ResourceManager.class, net.minecraft.util.profiling.ProfilerFiller.class);
|
||||
prepare.setAccessible(true);
|
||||
Object preparations = prepare.invoke(manager, resources, InactiveProfiler.INSTANCE);
|
||||
Method apply = preparations.getClass().getDeclaredMethod("apply", Map.class, Map.class, SoundEngine.class);
|
||||
apply.setAccessible(true);
|
||||
apply.invoke(preparations, field(SoundManager.class, "registry").get(manager), field(SoundManager.class, "soundCache").get(manager),
|
||||
field(SoundManager.class, "soundEngine").get(manager));
|
||||
return manager;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var manager = load(Path.of(args[0]));
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) {
|
||||
var names = new ArrayList<String>();
|
||||
for (var id : manager.getAvailableSounds()) names.add(id.toString());
|
||||
Collections.sort(names);
|
||||
for (String name : names) out.println("registered " + name);
|
||||
for (String line : Files.readAllLines(Path.of(args[1]))) {
|
||||
String[] f = line.split(" ");
|
||||
long seed = Long.parseLong(f[1]);
|
||||
float volume = Float.intBitsToFloat(Integer.parseUnsignedInt(f[2], 16));
|
||||
float pitch = Float.intBitsToFloat(Integer.parseUnsignedInt(f[3], 16));
|
||||
RandomSource random = RandomSource.create(seed);
|
||||
var instance = new SimpleSoundInstance(Identifier.parse(f[0]), SoundSource.MASTER, volume, pitch, random, false, 0,
|
||||
SoundInstance.Attenuation.LINEAR, 0.0, 0.0, 0.0, false);
|
||||
WeighedSoundEvents event = instance.getOrResolve(manager);
|
||||
Sound sound = instance.getSound();
|
||||
StringBuilder sb = new StringBuilder(line);
|
||||
if (event == null) {
|
||||
sb.append(" event=none");
|
||||
} else {
|
||||
String subtitle = "-";
|
||||
if (event.getSubtitle() != null && event.getSubtitle().getContents() instanceof TranslatableContents t) subtitle = t.getKey();
|
||||
sb.append(" event weight=").append(event.getWeight()).append(" subtitle=").append(subtitle);
|
||||
}
|
||||
float v = instance.getVolume();
|
||||
float p = instance.getPitch();
|
||||
sb.append(" sound=").append(sound.getLocation()).append(" path=").append(sound.getPath())
|
||||
.append(" sentinel=").append(sentinel(sound))
|
||||
.append(" weight=").append(sound.getWeight())
|
||||
.append(" type=").append(sound.getType().name())
|
||||
.append(" stream=").append(sound.shouldStream())
|
||||
.append(" preload=").append(sound.shouldPreload())
|
||||
.append(" attenuation=").append(sound.getAttenuationDistance())
|
||||
.append(" volume=").append(bits(v))
|
||||
.append(" pitch=").append(bits(p))
|
||||
.append(" range=").append(bits(sound.getAttenuationDistance(v)))
|
||||
.append(" next=").append(random.nextLong());
|
||||
out.println(sb);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.mojang.blaze3d.audio.*;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import javax.sound.sampled.AudioFormat;
|
||||
import net.minecraft.client.OptionInstance;
|
||||
import net.minecraft.client.Options;
|
||||
import net.minecraft.client.resources.sounds.SoundInstance;
|
||||
import net.minecraft.client.sounds.*;
|
||||
import net.minecraft.network.chat.contents.TranslatableContents;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import org.lwjgl.openal.AL10;
|
||||
|
||||
/**
|
||||
* A real vanilla SoundManager/SoundEngine running on OpenAL Soft's "No Output"
|
||||
* device (ALSOFT_DRIVERS=null), shared by the audio oracles.
|
||||
*
|
||||
* Determinism: the sound executor runs each task inline (the model where the
|
||||
* sound thread keeps up between client ticks); static sounds get one silent
|
||||
* hour-long buffer (they play until stopped or "finished" by the script) and
|
||||
* streams play endless silence. Everything else, the
|
||||
* channel pools, AL source parameters, lifetimes and bookkeeping, is the real
|
||||
* code and the real OpenAL implementation.
|
||||
*/
|
||||
public final class VanillaSoundRig {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
|
||||
static <T> T make(Class<T> type) throws Exception {
|
||||
if (unsafe == null) {
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
unsafe = field(u, "theUnsafe").get(null);
|
||||
allocate = u.getMethod("allocateInstance", Class.class);
|
||||
}
|
||||
return type.cast(allocate.invoke(unsafe, type));
|
||||
}
|
||||
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
var f = type.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
static Object get(Object target, Class<?> type, String name) throws Exception {
|
||||
return field(type, name).get(target);
|
||||
}
|
||||
|
||||
static void set(Object target, Class<?> type, String name, Object value) throws Exception {
|
||||
field(type, name).set(target, value);
|
||||
}
|
||||
|
||||
/** Runs every task on the calling thread. */
|
||||
public static final class Inline extends SoundEngineExecutor {
|
||||
@Override
|
||||
public void execute(final Runnable command) {
|
||||
command.run();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutDown() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startUp() {
|
||||
}
|
||||
}
|
||||
|
||||
static SoundBuffer silence;
|
||||
|
||||
/** Static sounds: a silent hour; streams: endless silence. */
|
||||
public static final class Buffers extends SoundBufferLibrary {
|
||||
Buffers() {
|
||||
super(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SoundBuffer> getCompleteBuffer(final Identifier location) {
|
||||
return CompletableFuture.completedFuture(silence);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<AudioStream> getStream(final Identifier location, final boolean looping) {
|
||||
return CompletableFuture.completedFuture(new Silence());
|
||||
}
|
||||
}
|
||||
|
||||
/** An endless silent stream, a minute per read (it never runs dry between ticks). */
|
||||
public static final class Silence implements AudioStream {
|
||||
static final AudioFormat FORMAT = new AudioFormat(8000.0F, 8, 1, false, false);
|
||||
|
||||
@Override
|
||||
public AudioFormat getFormat() {
|
||||
return FORMAT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ByteBuffer read(final int expectedSize) {
|
||||
ByteBuffer data = ByteBuffer.allocateDirect(8000 * 60);
|
||||
for (int i = 0; i < data.capacity(); i++) data.put(i, (byte) 0x80);
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
}
|
||||
|
||||
public final SoundManager manager;
|
||||
public final SoundEngine engine;
|
||||
public final Options options;
|
||||
public final List<String> heard = new ArrayList<>();
|
||||
|
||||
public VanillaSoundRig(Path root) throws Exception {
|
||||
manager = VanillaSoundEventOracle.load(root);
|
||||
engine = (SoundEngine) get(manager, SoundManager.class, "soundEngine");
|
||||
options = (Options) get(engine, SoundEngine.class, "options");
|
||||
var inline = make(Inline.class);
|
||||
set(engine, SoundEngine.class, "executor", inline);
|
||||
set(get(engine, SoundEngine.class, "channelAccess"), ChannelAccess.class, "executor", inline);
|
||||
set(engine, SoundEngine.class, "soundBuffers", make(Buffers.class));
|
||||
Library library = (Library) get(engine, SoundEngine.class, "library");
|
||||
library.init(null, DeviceList.query(), false);
|
||||
ByteBuffer data = ByteBuffer.allocateDirect(8000 * 3600);
|
||||
for (int i = 0; i < data.capacity(); i++) data.put(i, (byte) 0x80);
|
||||
silence = new SoundBuffer(data, new AudioFormat(8000.0F, 8, 1, false, false));
|
||||
set(engine, SoundEngine.class, "loaded", true);
|
||||
Method slider = Options.class.getDeclaredMethod("createSoundSliderOptionInstance", String.class, SoundSource.class);
|
||||
slider.setAccessible(true);
|
||||
var volumes = new EnumMap<SoundSource, OptionInstance<Double>>(SoundSource.class);
|
||||
for (SoundSource source : SoundSource.values()) {
|
||||
volumes.put(source, (OptionInstance<Double>) slider.invoke(options, "soundCategory." + source.getName(), source));
|
||||
}
|
||||
set(options, Options.class, "soundSourceVolumes", volumes);
|
||||
manager.addListener((sound, event, range) -> {
|
||||
String subtitle = "-";
|
||||
if (event.getSubtitle() != null && event.getSubtitle().getContents() instanceof TranslatableContents t) subtitle = t.getKey();
|
||||
heard.add(String.format("notify %s %s %08x %s %016x %016x %016x", sound.getIdentifier(), subtitle, Float.floatToRawIntBits(range),
|
||||
sound.isLooping(), Double.doubleToRawLongBits(sound.getX()), Double.doubleToRawLongBits(sound.getY()),
|
||||
Double.doubleToRawLongBits(sound.getZ())));
|
||||
});
|
||||
}
|
||||
|
||||
/** Set a sound source volume option without its change callback. */
|
||||
public void volume(SoundSource source, double value) throws Exception {
|
||||
set(options.getSoundSourceOptionInstance(source), OptionInstance.class, "value", value);
|
||||
}
|
||||
|
||||
/** The channel of an instance, or null. */
|
||||
@SuppressWarnings("unchecked")
|
||||
public Channel channel(SoundInstance instance) throws Exception {
|
||||
var map = (Map<SoundInstance, ChannelAccess.ChannelHandle>) get(engine, SoundEngine.class, "instanceToChannel");
|
||||
var handle = map.get(instance);
|
||||
return handle == null ? null : (Channel) get(handle, ChannelAccess.ChannelHandle.class, "channel");
|
||||
}
|
||||
|
||||
/** The channel's end: what OpenAL does when a non-looping buffer runs out. */
|
||||
public void finish(SoundInstance instance) throws Exception {
|
||||
var channel = channel(instance);
|
||||
if (channel != null) channel.stop();
|
||||
}
|
||||
|
||||
static String fbits(float v) {
|
||||
return String.format("%08x", Float.floatToRawIntBits(v));
|
||||
}
|
||||
|
||||
/** One line describing an instance: activity and its AL source. */
|
||||
public String describe(String name, SoundInstance instance) throws Exception {
|
||||
StringBuilder sb = new StringBuilder(" ").append(name).append(" active=").append(manager.isActive(instance));
|
||||
var channel = channel(instance);
|
||||
if (channel == null) {
|
||||
sb.append(" channel=-");
|
||||
} else {
|
||||
int source = (int) get(channel, Channel.class, "source");
|
||||
boolean initialized = ((java.util.concurrent.atomic.AtomicBoolean) get(channel, Channel.class, "initialized")).get();
|
||||
if (!initialized) {
|
||||
sb.append(" channel=released");
|
||||
} else {
|
||||
float[] pos = new float[3];
|
||||
AL10.alGetSourcefv(source, AL10.AL_POSITION, pos);
|
||||
sb.append(String.format(" state=%x gain=%s pitch=%s pos=%s,%s,%s rel=%d loop=%d model=%x max=%s rolloff=%s ref=%s",
|
||||
AL10.alGetSourcei(source, AL10.AL_SOURCE_STATE), fbits(AL10.alGetSourcef(source, AL10.AL_GAIN)),
|
||||
fbits(AL10.alGetSourcef(source, AL10.AL_PITCH)), fbits(pos[0]), fbits(pos[1]), fbits(pos[2]),
|
||||
AL10.alGetSourcei(source, AL10.AL_SOURCE_RELATIVE), AL10.alGetSourcei(source, AL10.AL_LOOPING),
|
||||
AL10.alGetSourcei(source, 0xD000), fbits(AL10.alGetSourcef(source, AL10.AL_MAX_DISTANCE)),
|
||||
fbits(AL10.alGetSourcef(source, AL10.AL_ROLLOFF_FACTOR)), fbits(AL10.alGetSourcef(source, AL10.AL_REFERENCE_DISTANCE))));
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** Print and clear the notifications, then the channel counts. */
|
||||
public void flush(PrintWriter out) {
|
||||
for (String h : heard) out.println(h);
|
||||
heard.clear();
|
||||
out.println(" " + manager.getChannelDebugString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.Difficulty;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.LightLayer;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.border.WorldBorder;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.levelgen.Heightmap;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
|
||||
/**
|
||||
* Original oracle: SpawnPlacements.isSpawnPositionOk and checkSpawnRules for an
|
||||
* entity type at a position of a controlled column world. The stand-in
|
||||
* ServerLevel answers block states from the case (air elsewhere), uniform sky
|
||||
* and block light, the sky darkening, thunder, difficulty, dimension type,
|
||||
* biome, sea level, WORLD_SURFACE height, world seed, the surface slime spawn
|
||||
* chance and an optional nearby player. Each case prints the two answers and
|
||||
* the next nextInt(1000) of its random, which pins the number of draws.
|
||||
*/
|
||||
public final class VanillaSpawnRulesOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate, putObject, objectFieldOffset;
|
||||
|
||||
static Object alloc(Class<?> c) throws Exception { return allocate.invoke(unsafe, c); }
|
||||
|
||||
static void put(Object target, Class<?> owner, String field, Object value) throws Exception {
|
||||
Field f = owner.getDeclaredField(field);
|
||||
putObject.invoke(unsafe, target, (long) objectFieldOffset.invoke(unsafe, f), value);
|
||||
}
|
||||
|
||||
static final class Lvl extends ServerLevel {
|
||||
Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); }
|
||||
RegistryAccess registries;
|
||||
Map<Integer, BlockState> column = new HashMap<>();
|
||||
int x0, z0, sky, block, darken, sea, surface;
|
||||
boolean thunder;
|
||||
long seed;
|
||||
Difficulty difficulty;
|
||||
DimensionType dimension;
|
||||
Holder<Biome> biome;
|
||||
net.minecraft.world.attribute.EnvironmentAttributeSystem attributes;
|
||||
List<Player> playerList = new ArrayList<>();
|
||||
WorldBorder border = new WorldBorder();
|
||||
int next = 1;
|
||||
@Override public RegistryAccess registryAccess() { return registries; }
|
||||
@Override public Difficulty getDifficulty() { return difficulty; }
|
||||
@Override public long getGameTime() { return 0L; }
|
||||
@Override public int getNextEntityId() { return next++; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
|
||||
@Override public BlockState getBlockState(BlockPos pos) {
|
||||
if (pos.getX() != x0 || pos.getZ() != z0) return Blocks.AIR.defaultBlockState();
|
||||
return column.getOrDefault(pos.getY(), Blocks.AIR.defaultBlockState());
|
||||
}
|
||||
@Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); }
|
||||
@Override public int getBrightness(LightLayer layer, BlockPos pos) { return layer == LightLayer.SKY ? sky : block; }
|
||||
@Override public int getRawBrightness(BlockPos pos, int darkening) { return Math.max(block, sky - darkening); }
|
||||
@Override public int getSkyDarken() { return darken; }
|
||||
@Override public boolean isThundering() { return thunder; }
|
||||
@Override public int getSeaLevel() { return sea; }
|
||||
@Override public int getHeight(Heightmap.Types type, int x, int z) { return surface; }
|
||||
@Override public long getSeed() { return seed; }
|
||||
@Override public DimensionType dimensionType() { return dimension; }
|
||||
@Override public Holder<Biome> getBiome(BlockPos pos) { return biome; }
|
||||
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; }
|
||||
@Override public WorldBorder getWorldBorder() { return border; }
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@Override public List players() { return playerList; }
|
||||
}
|
||||
|
||||
static final class OraclePlayer extends Player {
|
||||
final GameType mode;
|
||||
OraclePlayer(Level level, GameType mode) { super(level, new GameProfile(new UUID(1L, 2L), "oracle")); this.mode = mode; }
|
||||
@Override public GameType gameMode() { return mode; }
|
||||
@Override public boolean isCreative() { return mode == GameType.CREATIVE; }
|
||||
@Override public boolean isSpectator() { return mode == GameType.SPECTATOR; }
|
||||
@Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return net.minecraft.world.item.component.ResolvableProfile.createResolved(this.getGameProfile()); }
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class);
|
||||
objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class);
|
||||
var repo = ServerPacksSource.createVanillaTrustedRepository();
|
||||
repo.reload();
|
||||
repo.setSelected(List.of("vanilla"));
|
||||
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
|
||||
var layers = RegistryLayer.createRegistryAccess();
|
||||
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
|
||||
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
|
||||
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
var access = layers.replaceFrom(RegistryLayer.WORLD, world).compositeAccess();
|
||||
|
||||
Lvl level = (Lvl) alloc(Lvl.class);
|
||||
level.registries = access;
|
||||
level.column = new HashMap<>();
|
||||
level.playerList = new ArrayList<>();
|
||||
level.border = new WorldBorder();
|
||||
put(level, Level.class, "random", RandomSource.create(0L));
|
||||
var biomes = access.lookupOrThrow(Registries.BIOME);
|
||||
var dimensions = access.lookupOrThrow(Registries.DIMENSION_TYPE);
|
||||
var blocks = access.lookupOrThrow(Registries.BLOCK);
|
||||
|
||||
if (args.length > 2 && args[2].equals("facts")) {
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (var type : BuiltInRegistries.ENTITY_TYPE)
|
||||
w.println(BuiltInRegistries.ENTITY_TYPE.getKey(type) + " peaceful=" + type.isAllowedInPeaceful() + " fire_immune=" + type.fireImmune()
|
||||
+ " placement=" + SpawnPlacements.getPlacementType(type) + " heightmap=" + SpawnPlacements.getHeightmapType(type));
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
List<String> lines = Files.readAllLines(Path.of(args[0]));
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (String raw : lines) {
|
||||
if (raw.isBlank()) continue;
|
||||
Map<String, String> c = new LinkedHashMap<>();
|
||||
for (String token : raw.trim().split("\\s+")) {
|
||||
int eq = token.indexOf('=');
|
||||
if (eq < 0) c.put("name", token); else c.put(token.substring(0, eq), token.substring(eq + 1));
|
||||
}
|
||||
try {
|
||||
int y = Integer.parseInt(c.getOrDefault("y", "64"));
|
||||
level.x0 = Integer.parseInt(c.getOrDefault("x", "8"));
|
||||
level.z0 = Integer.parseInt(c.getOrDefault("z", "8"));
|
||||
level.column.clear();
|
||||
for (var e : c.entrySet()) {
|
||||
if (e.getKey().startsWith("at")) {
|
||||
int offset = Integer.parseInt(e.getKey().substring(2));
|
||||
level.column.put(y + offset, net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blocks, e.getValue(), false).blockState());
|
||||
}
|
||||
}
|
||||
level.sky = Integer.parseInt(c.getOrDefault("sky", "15"));
|
||||
level.block = Integer.parseInt(c.getOrDefault("light", "0"));
|
||||
level.darken = Integer.parseInt(c.getOrDefault("darken", "0"));
|
||||
level.thunder = c.getOrDefault("thunder", "0").equals("1");
|
||||
level.sea = Integer.parseInt(c.getOrDefault("sea", "63"));
|
||||
level.surface = Integer.parseInt(c.getOrDefault("surface", "0"));
|
||||
level.seed = Long.parseLong(c.getOrDefault("wseed", "0"));
|
||||
level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal"));
|
||||
level.dimension = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(c.getOrDefault("dim", "minecraft:overworld")))).value();
|
||||
level.biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(c.getOrDefault("biome", "minecraft:plains"))));
|
||||
level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder()
|
||||
.addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder()
|
||||
.set(net.minecraft.world.attribute.EnvironmentAttributes.SURFACE_SLIME_SPAWN_CHANCE, Float.parseFloat(c.getOrDefault("slime", "0.0")))
|
||||
.build())
|
||||
.build();
|
||||
level.playerList.clear();
|
||||
if (c.containsKey("player")) {
|
||||
String[] p = c.get("player").split(",");
|
||||
Player player = new OraclePlayer(level, GameType.byName(p.length > 3 ? p[3] : "survival"));
|
||||
player.setPos(level.x0 + Double.parseDouble(p[0]), y + Double.parseDouble(p[1]), level.z0 + Double.parseDouble(p[2]));
|
||||
level.playerList.add(player);
|
||||
}
|
||||
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(c.get("type")));
|
||||
EntitySpawnReason reason = EntitySpawnReason.valueOf(c.getOrDefault("reason", "natural").toUpperCase(Locale.ROOT));
|
||||
BlockPos pos = new BlockPos(level.x0, y, level.z0);
|
||||
RandomSource random = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0")));
|
||||
boolean ok = SpawnPlacements.isSpawnPositionOk(type, level, pos);
|
||||
boolean rules = SpawnPlacements.checkSpawnRules(type, level, reason, pos, random);
|
||||
w.println(c.get("name") + " " + ok + " " + rules + " " + random.nextInt(1000));
|
||||
} catch (Throwable t) {
|
||||
Throwable cause = t instanceof InvocationTargetException ite ? ite.getCause() : t;
|
||||
StringBuilder line = new StringBuilder(c.get("name") + " error " + cause);
|
||||
if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) line.append("\n at ").append(frame);
|
||||
w.println(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.blaze3d.platform.InputConstants;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.*;
|
||||
|
||||
/**
|
||||
* Drives the real Options key mappings (keyShift, keySprint, keyAttack and
|
||||
* keyUse are ToggleKeyMappings reading toggleCrouch/toggleSprint/toggleAttack/
|
||||
* toggleUse) through the real static KeyMapping.set/click, releaseAll,
|
||||
* restoreToggleStatesOnScreenClosed and resetToggleKeys, dispatched as
|
||||
* KeyboardHandler.keyPress, MouseHandler.onButton, Gui.setScreen and
|
||||
* LocalPlayer.respawn call them, and prints each mapping's down state and
|
||||
* pending clicks after every event.
|
||||
*/
|
||||
public final class VanillaToggleKeysOracle {
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
Field f = type.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
var unsafe = field(u, "theUnsafe").get(null);
|
||||
Minecraft shell = (Minecraft) u.getMethod("allocateInstance", Class.class).invoke(unsafe, Minecraft.class);
|
||||
field(Minecraft.class, "fixerUpper").set(shell, net.minecraft.util.datafix.DataFixers.getDataFixer());
|
||||
field(Minecraft.class, "instance").set(null, shell);
|
||||
Options options = new Options(shell, Files.createTempDirectory("opts").toFile());
|
||||
KeyMapping[] mappings = {options.keyShift, options.keySprint, options.keyAttack, options.keyUse};
|
||||
List<OptionInstance<Boolean>> toggles = List.of(options.toggleCrouch(), options.toggleSprint(), options.toggleAttack(), options.toggleUse());
|
||||
Field keyField = field(KeyMapping.class, "key");
|
||||
Field clicks = field(KeyMapping.class, "clickCount");
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
int n = 0;
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
out.println("== " + n++);
|
||||
// A fresh session: everything up, no pending clicks or remembered releases.
|
||||
for (int i = 0; i < 4; i++) {
|
||||
toggles.get(i).set(false);
|
||||
}
|
||||
KeyMapping.resetToggleKeys();
|
||||
KeyMapping.releaseAll();
|
||||
KeyMapping.restoreToggleStatesOnScreenClosed();
|
||||
for (var m : mappings) {
|
||||
while (m.consumeClick()) {
|
||||
}
|
||||
}
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
String name = op.get(0).getAsString();
|
||||
switch (name) {
|
||||
case "option" -> toggles.get(op.get(1).getAsInt()).set(op.get(2).getAsBoolean());
|
||||
case "key" -> {
|
||||
// KeyboardHandler.keyPress: action 0 releases; a press (1) or an SDL
|
||||
// repeat (-1) sets and clicks only with no screen open.
|
||||
var key = (InputConstants.Key) keyField.get(mappings[op.get(1).getAsInt()]);
|
||||
int action = op.get(2).getAsInt();
|
||||
boolean screen = op.get(3).getAsBoolean();
|
||||
if (action == 0) {
|
||||
KeyMapping.set(key, false);
|
||||
} else if (!screen) {
|
||||
KeyMapping.set(key, true);
|
||||
KeyMapping.click(key);
|
||||
}
|
||||
}
|
||||
case "button" -> {
|
||||
// MouseHandler.onButton: only with no screen or overlay.
|
||||
var key = (InputConstants.Key) keyField.get(mappings[op.get(1).getAsInt()]);
|
||||
boolean pressed = op.get(2).getAsBoolean();
|
||||
if (!op.get(3).getAsBoolean()) {
|
||||
KeyMapping.set(key, pressed);
|
||||
if (pressed) {
|
||||
KeyMapping.click(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
case "open" -> KeyMapping.releaseAll();
|
||||
case "close" -> KeyMapping.restoreToggleStatesOnScreenClosed();
|
||||
case "respawn" -> KeyMapping.resetToggleKeys();
|
||||
default -> throw new IllegalArgumentException(name);
|
||||
}
|
||||
var sb = new StringBuilder(name);
|
||||
for (var m : mappings) {
|
||||
sb.append(' ').append(m.isDown()).append(' ').append(clicks.getInt(m));
|
||||
}
|
||||
out.println(sb);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user