Merge remote-tracking branch 'origin/t3/achieve-full-parity' into parity/warden-sculk

# Conflicts:
#	crates/horizon-client/src/game.rs
#	crates/horizon-client/src/game/creatures.rs
This commit is contained in:
Ludovic Marie
2026-10-12 17:18:11 +02:00
133 changed files with 19187 additions and 2931 deletions
@@ -0,0 +1,362 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.io.*;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import java.util.function.Predicate;
import net.minecraft.client.model.object.book.BookModel;
import net.minecraft.client.model.object.chest.ChestModel;
import net.minecraft.client.renderer.blockentity.*;
import net.minecraft.client.renderer.blockentity.state.*;
import net.minecraft.commands.arguments.blocks.BlockStateParser;
import net.minecraft.core.*;
import net.minecraft.core.particles.ColorParticleOption;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.*;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.entity.*;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.*;
/**
* Original oracle for the client-ticked animation state of chests and ender
* chests (ChestLidController), enchanting table books, shulker boxes, bells,
* conduits, skulls and decorated pots. Each case builds the real
* vanilla block entity on a stand-in client level (scripted blocks, entities,
* game time and a seeded LegacyRandomSource), then per step applies the
* scripted block event (triggerEvent), runs the block entity's own client
* ticker (lidAnimateTick, bookAnimationTick with the class's static RANDOM
* reseeded, ShulkerBoxBlockEntity.tick, BellBlockEntity.clientTick,
* ConduitBlockEntity.clientTick, SkullBlockEntity.animation; pots have none)
* and runs the real renderer's extractRenderState at the step's partial tick.
* It prints the block entity's fields, the level calls the tick made
* (neighbour updates, entity queries, sounds, particles) and the render state.
*
* Usage: VanillaBlockEntityAnimOracle inputs.jsonl output.txt
*/
public final class VanillaBlockEntityAnimOracle {
static Object unsafe;
static Method allocate, putObject, objectFieldOffset;
@SuppressWarnings("unchecked")
static <T> T make(Class<T> type) throws Exception { return (T) allocate.invoke(unsafe, type); }
static void put(Object target, Class<?> owner, String name, Object value) throws Exception {
Field f = owner.getDeclaredField(name);
long offset = (long) objectFieldOffset.invoke(unsafe, f);
putObject.invoke(unsafe, target, offset, value);
}
static Field field(Class<?> owner, String name) throws Exception {
Field f = owner.getDeclaredField(name);
f.setAccessible(true);
return f;
}
static String f(float v) { return String.format("%08x", Float.floatToRawIntBits(v)); }
static String d(double v) { return String.format("%016x", Double.doubleToRawLongBits(v)); }
static String box(AABB b) { return d(b.minX) + " " + d(b.minY) + " " + d(b.minZ) + " " + d(b.maxX) + " " + d(b.maxY) + " " + d(b.maxZ); }
static BlockState parse(String s) throws Exception {
return BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, s, false).blockState();
}
/** A living entity the case places: a Pillager whose type field says raider or not. */
static final class Mob extends net.minecraft.world.entity.monster.illager.Pillager {
boolean living;
Mob() { super(null, null); }
@Override public boolean isAlive() { return !this.isRemoved() && this.living; }
}
/** A player the case places: position and game mode (spectators are skipped). */
static final class Gamer extends Player {
GameType mode;
Gamer() { super(null, null); }
@Override public GameType gameMode() { return mode; }
@Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return null; }
}
static Gamer gamer(JsonObject e) throws Exception {
Gamer g = make(Gamer.class);
g.mode = e.has("spectator") && e.get("spectator").getAsBoolean() ? GameType.SPECTATOR : GameType.SURVIVAL;
var p = e.getAsJsonArray("pos");
put(g, Entity.class, "position", new Vec3(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble()));
return g;
}
/** The stand-in client level. */
static final class World extends Level {
World() { super(null, null, null, null, false, false, 0L, 0); }
long time;
Map<BlockPos, BlockState> blocks = new HashMap<>();
List<Mob> mobs = new ArrayList<>();
List<Player> gamers = new ArrayList<>();
Map<BlockPos, BlockEntity> entities = new HashMap<>();
RandomSource random;
StringBuilder log = new StringBuilder();
@Override public long getGameTime() { return time; }
@Override public boolean isClientSide() { return true; }
@Override public BlockState getBlockState(BlockPos p) { return blocks.getOrDefault(p.immutable(), Blocks.AIR.defaultBlockState()); }
@Override public FluidState getFluidState(BlockPos p) { return getBlockState(p).getFluidState(); }
@Override public int getBrightness(LightLayer layer, BlockPos p) { return 0; }
@Override public RandomSource getRandom() { return random; }
@Override public BlockEntity getBlockEntity(BlockPos p) { return entities.get(p.immutable()); }
@Override public void updateNeighborsAt(BlockPos p, Block block) { log.append(" neighbors"); }
@Override public void neighborShapeChanged(Direction dir, BlockPos p, BlockPos from, BlockState state, int flags, int limit) {}
@Override public List<Entity> getEntities(Entity except, AABB bb) { log.append(" push ").append(box(bb)); return List.of(); }
@SuppressWarnings("unchecked")
@Override public <T extends Entity> List<T> getEntitiesOfClass(Class<T> type, AABB bb, Predicate<? super T> selector) {
log.append(" gather ").append(box(bb));
List<T> out = new ArrayList<>();
for (Mob m : mobs) if (type.isInstance(m) && bb.contains(m.position())) out.add((T) m);
return out;
}
@Override public void playSound(Entity except, BlockPos p, SoundEvent s, SoundSource source, float volume, float pitch) {
log.append(" sound ").append(BuiltInRegistries.SOUND_EVENT.getKey(s));
}
@Override public void addParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) {
log.append(" particle ").append(BuiltInRegistries.PARTICLE_TYPE.getKey(o.getType()));
if (o instanceof ColorParticleOption c) {
try { log.append(" ").append(field(ColorParticleOption.class, "color").getInt(c)); } catch (Exception e) { throw new RuntimeException(e); }
}
log.append(" ").append(d(x)).append(" ").append(d(y)).append(" ").append(d(z))
.append(" ").append(d(xd)).append(" ").append(d(yd)).append(" ").append(d(zd));
}
@Override public net.minecraft.world.clock.ClockManager clockManager(){throw new UnsupportedOperationException();}
@Override public void destroyBlockProgress(int p0,net.minecraft.core.BlockPos p1,int p2){throw new UnsupportedOperationException();}
@Override public java.util.Collection dragonParts(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes(){throw new UnsupportedOperationException();}
@Override public void explode(net.minecraft.world.entity.Entity p0,net.minecraft.world.damagesource.DamageSource p1,net.minecraft.world.level.ExplosionDamageCalculator p2,double p3,double p4,double p5,float p6,boolean p7,net.minecraft.world.level.Level.ExplosionInteraction p8,net.minecraft.core.particles.ParticleOptions p9,net.minecraft.core.particles.ParticleOptions p10,net.minecraft.util.random.WeightedList p11,net.minecraft.core.Holder p12){throw new UnsupportedOperationException();}
@Override public void gameEvent(net.minecraft.core.Holder p0,net.minecraft.world.phys.Vec3 p1,net.minecraft.world.level.gameevent.GameEvent.Context p2){throw new UnsupportedOperationException();}
@Override public java.lang.String gatherChunkSourceStats(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.ticks.LevelTickAccess getBlockTicks(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.level.chunk.ChunkSource getChunkSource(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.level.entity.LevelEntityGetter getEntities(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.entity.Entity getEntity(int p0){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.ticks.LevelTickAccess getFluidTicks(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.level.saveddata.maps.MapItemSavedData getMapData(net.minecraft.world.level.saveddata.maps.MapId p0){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.level.storage.LevelData.RespawnData getRespawnData(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.scores.Scoreboard getScoreboard(){throw new UnsupportedOperationException();}
@Override public int getSeaLevel(){throw new UnsupportedOperationException();}
@Override public net.minecraft.core.Holder getUncachedNoiseBiome(int p0,int p1,int p2){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.level.border.WorldBorder getWorldBorder(){throw new UnsupportedOperationException();}
@Override public void levelEvent(net.minecraft.world.entity.Entity p0,int p1,net.minecraft.core.BlockPos p2,int p3){throw new UnsupportedOperationException();}
@Override public void playSeededSound(net.minecraft.world.entity.Entity p0,net.minecraft.world.entity.Entity p1,net.minecraft.core.Holder p2,net.minecraft.sounds.SoundSource p3,float p4,float p5,long p6){throw new UnsupportedOperationException();}
@Override public void playSeededSound(net.minecraft.world.entity.Entity p0,double p1,double p2,double p3,net.minecraft.core.Holder p4,net.minecraft.sounds.SoundSource p5,float p6,float p7,long p8){throw new UnsupportedOperationException();}
@Override public java.util.List players(){return gamers;}
@Override public net.minecraft.world.item.crafting.RecipeAccess recipeAccess(){throw new UnsupportedOperationException();}
@Override public void sendBlockUpdated(net.minecraft.core.BlockPos p0,net.minecraft.world.level.block.state.BlockState p1,net.minecraft.world.level.block.state.BlockState p2,int p3){throw new UnsupportedOperationException();}
@Override public void setRespawnData(net.minecraft.world.level.storage.LevelData.RespawnData p0){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.TickRateManager tickRateManager(){throw new UnsupportedOperationException();}
}
static Mob mob(JsonObject e, World world) throws Exception {
Mob m = make(Mob.class);
m.living = !e.has("alive") || e.get("alive").getAsBoolean();
put(m, Entity.class, "type", e.has("raider") && e.get("raider").getAsBoolean() ? EntityTypes.PILLAGER : EntityTypes.COW);
var p = e.getAsJsonArray("pos");
put(m, Entity.class, "position", new Vec3(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble()));
if (e.has("removed") && e.get("removed").getAsBoolean()) put(m, Entity.class, "removalReason", Entity.RemovalReason.KILLED);
if (e.has("width")) {
put(m, Entity.class, "dimensions", EntityDimensions.scalable(e.get("width").getAsFloat(), e.get("height").getAsFloat()));
Field eye = field(Entity.class, "eyeHeight");
eye.setFloat(m, e.get("eye").getAsFloat());
}
return m;
}
static ChestModel CHEST_MODEL;
static void tickLid(World world, BlockEntity e) {
if (e instanceof ChestBlockEntity c) ChestBlockEntity.lidAnimateTick(world, c.getBlockPos(), c.getBlockState(), c);
else if (e instanceof EnderChestBlockEntity c) EnderChestBlockEntity.lidAnimateTick(world, c.getBlockPos(), c.getBlockState(), c);
}
static String lid(BlockEntity e) throws Exception {
if (!(e instanceof ChestBlockEntity) && !(e instanceof EnderChestBlockEntity)) return "-";
Class<?> owner = e instanceof ChestBlockEntity ? ChestBlockEntity.class : EnderChestBlockEntity.class;
Object lid = field(owner, "chestLidController").get(e);
return field(ChestLidController.class, "shouldBeOpen").getBoolean(lid)
+ " " + f(field(ChestLidController.class, "openness").getFloat(lid))
+ " " + f(field(ChestLidController.class, "oOpenness").getFloat(lid));
}
static String run(JsonObject c) throws Exception {
World world = make(World.class);
world.blocks = new HashMap<>();
world.mobs = new ArrayList<>();
world.gamers = new ArrayList<>();
world.entities = new HashMap<>();
world.log = new StringBuilder();
world.random = RandomSource.create(c.has("seed") ? c.get("seed").getAsLong() : 0L);
var pa = c.getAsJsonArray("pos");
BlockPos pos = new BlockPos(pa.get(0).getAsInt(), pa.get(1).getAsInt(), pa.get(2).getAsInt());
BlockState state = parse(c.get("block").getAsString());
world.blocks.put(pos, state);
if (c.has("world")) {
for (var e : c.getAsJsonObject("world").entrySet()) {
String[] xyz = e.getKey().split(",");
world.blocks.put(pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2])), parse(e.getValue().getAsString()));
}
}
if (c.has("entities")) for (var e : c.getAsJsonArray("entities")) world.mobs.add(mob(e.getAsJsonObject(), world));
var be = ((EntityBlock) state.getBlock()).newBlockEntity(pos, state);
be.setLevel(world);
world.entities.put(pos, be);
// The other half of a double chest (or whatever block sits there).
BlockEntity partner = null;
if (c.has("partner")) {
String[] xyz = c.get("partner").getAsString().split(",");
BlockPos at = pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2]));
BlockState there = world.getBlockState(at);
if (there.getBlock() instanceof EntityBlock eb) {
partner = eb.newBlockEntity(at, there);
partner.setLevel(world);
world.entities.put(at, partner);
}
}
if (c.has("players")) for (var e : c.getAsJsonArray("players")) world.gamers.add(gamer(e.getAsJsonObject()));
if (be instanceof EnchantingTableBlockEntity) {
((RandomSource) field(EnchantingTableBlockEntity.class, "RANDOM").get(null)).setSeed(c.get("seed").getAsLong());
}
if (c.has("target") && be instanceof ConduitBlockEntity) {
put(be, ConduitBlockEntity.class, "destroyTarget", EntityReference.of(mob(c.getAsJsonObject("target"), world)));
}
StringBuilder out = new StringBuilder();
for (var stepElement : c.getAsJsonArray("steps")) {
var step = stepElement.getAsJsonObject();
world.time = step.get("time").getAsLong();
world.log.setLength(0);
if (step.has("set")) {
for (var e : step.getAsJsonObject("set").entrySet()) {
String[] xyz = e.getKey().split(",");
world.blocks.put(pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2])), parse(e.getValue().getAsString()));
}
}
if (step.has("players")) {
world.gamers.clear();
for (var e : step.getAsJsonArray("players")) world.gamers.add(gamer(e.getAsJsonObject()));
}
if (step.has("event")) {
var ev = step.getAsJsonArray("event");
boolean handled = be.triggerEvent(ev.get(0).getAsInt(), ev.get(1).getAsInt());
world.log.append(" event ").append(handled);
}
if (step.has("partnerEvent") && partner != null) {
var ev = step.getAsJsonArray("partnerEvent");
boolean handled = partner.triggerEvent(ev.get(0).getAsInt(), ev.get(1).getAsInt());
world.log.append(" partner event ").append(handled);
}
float partial = step.get("partial").getAsFloat();
String fields;
if (be instanceof ChestBlockEntity || be instanceof EnderChestBlockEntity) {
tickLid(world, be);
if (partner != null) tickLid(world, partner);
ChestRenderer<?> renderer = make(ChestRenderer.class);
var r = new net.minecraft.client.renderer.blockentity.state.ChestRenderState();
@SuppressWarnings({"unchecked", "rawtypes"})
ChestRenderer raw = renderer;
raw.extractRenderState(be, r, partial, Vec3.ZERO, null);
float open = r.open;
// ChestRenderer.submit, then ChestModel.setupAnim.
open = 1.0F - open;
open = 1.0F - open * open * open;
CHEST_MODEL.setupAnim(open);
fields = lid(be) + " partner " + (partner == null ? "none" : lid(partner))
+ " render " + f(r.open) + " " + f(((net.minecraft.client.model.geom.ModelPart) field(ChestModel.class, "lid").get(CHEST_MODEL)).xRot);
} else if (be instanceof EnchantingTableBlockEntity t) {
EnchantingTableBlockEntity.bookAnimationTick(world, pos, state, t);
var r = new net.minecraft.client.renderer.blockentity.state.EnchantTableRenderState();
make(EnchantTableRenderer.class).extractRenderState(t, r, partial, Vec3.ZERO, null);
// EnchantTableRenderer.submit's book state.
float ff1 = Mth.frac(r.flip + 0.25F) * 1.6F - 0.3F;
float ff2 = Mth.frac(r.flip + 0.75F) * 1.6F - 0.3F;
var book = BookModel.State.forAnimation(r.time, Mth.clamp(ff1, 0.0F, 1.0F), Mth.clamp(ff2, 0.0F, 1.0F), r.open);
fields = t.time + " " + f(t.flip) + " " + f(t.oFlip) + " " + f(t.flipT) + " " + f(t.flipA)
+ " " + f(t.open) + " " + f(t.oOpen) + " " + f(t.rot) + " " + f(t.oRot) + " " + f(t.tRot)
+ " render " + f(r.flip) + " " + f(r.open) + " " + f(r.time) + " " + f(r.yRot)
+ " book " + f(book.openness()) + " " + f(book.pageFlip1()) + " " + f(book.pageFlip2());
} else if (be instanceof ShulkerBoxBlockEntity s) {
ShulkerBoxBlockEntity.tick(world, pos, state, s);
var r = make(ShulkerBoxRenderer.class).createRenderState();
make(ShulkerBoxRenderer.class).extractRenderState(s, r, partial, Vec3.ZERO, null);
fields = s.getAnimationStatus() + " " + field(ShulkerBoxBlockEntity.class, "openCount").getInt(s)
+ " " + f(field(ShulkerBoxBlockEntity.class, "progress").getFloat(s))
+ " " + f(field(ShulkerBoxBlockEntity.class, "progressOld").getFloat(s))
+ " render " + f(r.progress);
} else if (be instanceof BellBlockEntity b) {
if (!step.has("noTick")) BellBlockEntity.clientTick(world, pos, state, b);
var r = make(BellRenderer.class).createRenderState();
make(BellRenderer.class).extractRenderState(b, r, partial, Vec3.ZERO, null);
fields = b.ticks + " " + b.shaking + " " + b.clickDirection
+ " " + field(BellBlockEntity.class, "resonating").getBoolean(b)
+ " " + field(BellBlockEntity.class, "resonationTicks").getInt(b)
+ " " + field(BellBlockEntity.class, "lastRingTimestamp").getLong(b)
+ " render " + f(r.ticks) + " " + r.shakeDirection;
} else if (be instanceof ConduitBlockEntity k) {
ConduitBlockEntity.clientTick(world, pos, state, k);
var r = make(ConduitRenderer.class).createRenderState();
make(ConduitRenderer.class).extractRenderState(k, r, partial, Vec3.ZERO, null);
@SuppressWarnings("unchecked")
var effect = (List<BlockPos>) field(ConduitBlockEntity.class, "effectBlocks").get(k);
fields = k.tickCount + " " + k.isActive() + " " + k.isHunting()
+ " " + f(field(ConduitBlockEntity.class, "activeRotation").getFloat(k)) + " " + effect.size()
+ " render " + r.isActive + " " + f(r.activeRotation) + " " + f(r.animTime) + " " + r.animationPhase + " " + r.isHunting;
} else if (be instanceof SkullBlockEntity k) {
BlockState now = step.has("state") ? parse(step.get("state").getAsString()) : state;
SkullBlockEntity.animation(world, pos, now, k);
fields = field(SkullBlockEntity.class, "isAnimating").getBoolean(k)
+ " " + field(SkullBlockEntity.class, "animationTickCount").getInt(k)
+ " render " + f(k.getAnimation(partial));
} else if (be instanceof DecoratedPotBlockEntity p) {
var r = make(DecoratedPotRenderer.class).createRenderState();
make(DecoratedPotRenderer.class).extractRenderState(p, r, partial, Vec3.ZERO, null);
fields = p.wobbleStartedAtTick + " " + p.lastWobbleStyle
+ " render " + f(r.wobbleProgress) + " " + r.wobbleStyle;
} else {
throw new IllegalArgumentException("no animation for " + be);
}
out.append(fields).append(" |").append(world.log).append('\n');
}
return out.toString();
}
public static void main(String[] args) throws Exception {
ParityData.init();
var allocator = Class.forName("sun.misc.Unsafe");
var theUnsafe = allocator.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = theUnsafe.get(null);
allocate = allocator.getMethod("allocateInstance", Class.class);
putObject = allocator.getMethod("putObject", Object.class, long.class, Object.class);
objectFieldOffset = allocator.getMethod("objectFieldOffset", Field.class);
CHEST_MODEL = new ChestModel(ChestModel.createSingleBodyLayer().bakeRoot());
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])));
var lines = Files.lines(Path.of(args[0]))) {
for (String line : (Iterable<String>) lines::iterator) {
var c = JsonParser.parseString(line).getAsJsonObject();
String result;
try {
result = run(c);
} catch (Throwable t) {
result = "error " + t + "\n";
}
out.print("case " + c.get("name").getAsString() + "\n" + result);
}
}
}
}
@@ -45,7 +45,8 @@ import org.joml.Quaternionf;
* renderer's extractRenderState and submit, and captures every submitted
* model (vertices after setupAnim and the pose stack, sprite-local UVs, tint,
* light), text call and item. Level-backed inputs (light, chest lid
* openness, pot wobble) come from the case because the entity has no level.
* openness, pot wobble) come from the case because the entity has no level;
* End gateways, which query theirs, get a stub level built from the case.
*
* Input lines: case JSON. Output lines: {case, submits:[...]} or {case, error}.
*/
@@ -206,6 +207,54 @@ public final class VanillaBlockEntityRenderOracle {
return (SubmitNodeCollector) Proxy.newProxyInstance(SubmitNodeCollector.class.getClassLoader(), new Class<?>[] {SubmitNodeCollector.class}, handler);
}
/**
* The level an End gateway reads: the gateway and the case's neighbour
* blocks (air elsewhere), its light, build height and game time. Allocated without running
* Level's constructor; everything else is unsupported.
*/
static final class CaseLevel extends net.minecraft.world.level.Level {
Map<BlockPos, BlockState> blocks;
int minY, height, sky, block;
long gameTime;
CaseLevel() { super(null, null, null, null, false, false, 0L, 0); }
@Override public BlockState getBlockState(BlockPos p) { return blocks.getOrDefault(p, net.minecraft.world.level.block.Blocks.AIR.defaultBlockState()); }
@Override public int getMinY() { return minY; }
@Override public int getHeight() { return height; }
@Override public long getGameTime() { return gameTime; }
@Override public int getBrightness(net.minecraft.world.level.LightLayer layer, BlockPos p) { return layer == net.minecraft.world.level.LightLayer.SKY ? sky : block; }
@Override public net.minecraft.world.clock.ClockManager clockManager() { throw new UnsupportedOperationException(); }
@Override public void destroyBlockProgress(int p0, BlockPos p1, int p2) { throw new UnsupportedOperationException(); }
@Override public java.util.Collection dragonParts() { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { throw new UnsupportedOperationException(); }
@Override public void explode(net.minecraft.world.entity.Entity p0, net.minecraft.world.damagesource.DamageSource p1, net.minecraft.world.level.ExplosionDamageCalculator p2, double p3, double p4, double p5, float p6, boolean p7, net.minecraft.world.level.Level.ExplosionInteraction p8, net.minecraft.core.particles.ParticleOptions p9, net.minecraft.core.particles.ParticleOptions p10, net.minecraft.util.random.WeightedList p11, net.minecraft.core.Holder p12) { throw new UnsupportedOperationException(); }
@Override public void gameEvent(net.minecraft.core.Holder p0, net.minecraft.world.phys.Vec3 p1, net.minecraft.world.level.gameevent.GameEvent.Context p2) { throw new UnsupportedOperationException(); }
@Override public String gatherChunkSourceStats() { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.ticks.LevelTickAccess getBlockTicks() { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.level.chunk.ChunkSource getChunkSource() { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.level.entity.LevelEntityGetter getEntities() { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.entity.Entity getEntity(int p0) { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.ticks.LevelTickAccess getFluidTicks() { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.level.saveddata.maps.MapItemSavedData getMapData(net.minecraft.world.level.saveddata.maps.MapId p0) { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.level.storage.LevelData.RespawnData getRespawnData() { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.scores.Scoreboard getScoreboard() { throw new UnsupportedOperationException(); }
@Override public int getSeaLevel() { throw new UnsupportedOperationException(); }
@Override public net.minecraft.core.Holder getUncachedNoiseBiome(int p0, int p1, int p2) { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { throw new UnsupportedOperationException(); }
@Override public void levelEvent(net.minecraft.world.entity.Entity p0, int p1, BlockPos p2, int p3) { throw new UnsupportedOperationException(); }
@Override public void playSeededSound(net.minecraft.world.entity.Entity p0, net.minecraft.world.entity.Entity p1, net.minecraft.core.Holder p2, net.minecraft.sounds.SoundSource p3, float p4, float p5, long p6) { throw new UnsupportedOperationException(); }
@Override public void playSeededSound(net.minecraft.world.entity.Entity p0, double p1, double p2, double p3, net.minecraft.core.Holder p4, net.minecraft.sounds.SoundSource p5, float p6, float p7, long p8) { throw new UnsupportedOperationException(); }
@Override public java.util.List players() { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.item.crafting.RecipeAccess recipeAccess() { throw new UnsupportedOperationException(); }
@Override public void sendBlockUpdated(BlockPos p0, BlockState p1, BlockState p2, int p3) { throw new UnsupportedOperationException(); }
@Override public void setRespawnData(net.minecraft.world.level.storage.LevelData.RespawnData p0) { throw new UnsupportedOperationException(); }
@Override public net.minecraft.world.TickRateManager tickRateManager() { throw new UnsupportedOperationException(); }
}
static BlockState parseState(String spec) throws Exception {
return BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, spec, false).blockState();
}
static Field field(Class<?> type, String name) throws NoSuchFieldException {
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
try {
@@ -263,6 +312,26 @@ public final class VanillaBlockEntityRenderOracle {
: Optional.of(new ItemStackTemplate(BuiltInRegistries.ITEM.getValue(Identifier.parse(id)))));
}
field(DecoratedPotBlockEntity.class, "decorations").set(be, new PotDecorations(items.get(0), items.get(1), items.get(2), items.get(3)));
} else if (be instanceof TheEndGatewayBlockEntity) {
// Age and teleportCooldown (synced and ticked by the client), and the level the renderer reads.
var g = c.has("gateway") ? c.getAsJsonObject("gateway") : new JsonObject();
field(TheEndGatewayBlockEntity.class, "age").setLong(be, g.has("age") ? g.get("age").getAsLong() : 0L);
field(TheEndGatewayBlockEntity.class, "teleportCooldown").setInt(be, g.has("cooldown") ? g.get("cooldown").getAsInt() : 0);
var level = (CaseLevel) allocate.invoke(unsafe, CaseLevel.class);
var height = c.has("level") ? c.getAsJsonArray("level") : null;
level.minY = height == null ? 0 : height.get(0).getAsInt();
level.height = height == null ? 256 : height.get(1).getAsInt();
level.gameTime = c.has("gameTime") ? c.get("gameTime").getAsLong() : 0L;
var light = c.getAsJsonArray("light");
level.sky = light.get(0).getAsInt();
level.block = light.get(1).getAsInt();
level.blocks = new HashMap<>();
level.blocks.put(be.getBlockPos(), be.getBlockState());
if (c.has("neighbours")) {
for (var e : c.getAsJsonObject("neighbours").entrySet())
level.blocks.put(be.getBlockPos().relative(Direction.byName(e.getKey())), parseState(e.getValue().getAsString()));
}
be.setLevel(level);
} else if (be instanceof BannerBlockEntity && c.has("patterns")) {
var builder = new net.minecraft.world.level.block.entity.BannerPatternLayers.Builder();
var registry = ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN);
@@ -307,7 +376,10 @@ public final class VanillaBlockEntityRenderOracle {
throw new RuntimeException(e);
}
};
var context = new BlockEntityRendererProvider.Context(null, null, null, null, models, font, sprites, null);
// Campfires and brushable blocks resolve their (here always empty) items: an empty
// stack only clears the render state and never reaches the model manager.
var items = new net.minecraft.client.renderer.item.ItemModelResolver(null);
var context = new BlockEntityRendererProvider.Context(null, null, items, null, models, font, sprites, null);
Map<Object, BlockEntityRenderer> renderers = (Map) BlockEntityRenderers.createEntityRenderers(context);
var gson = new Gson();
var out = new StringBuilder();
@@ -317,7 +389,7 @@ public final class VanillaBlockEntityRenderOracle {
var result = new JsonObject();
result.add("case", c);
try {
BlockState state = BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, c.get("block").getAsString(), false).blockState();
BlockState state = parseState(c.get("block").getAsString());
var p = c.getAsJsonArray("pos");
var pos = new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt());
var be = ((EntityBlock) state.getBlock()).newBlockEntity(pos, state);
@@ -0,0 +1,387 @@
package dev.horizonlab.parity;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.services.ServicesKeySet;
import com.mojang.serialization.Lifecycle;
import io.netty.channel.embedded.EmbeddedChannel;
import java.io.IOException;
import java.net.Proxy;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.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.core.MappedRegistry;
import net.minecraft.core.Registry;
import net.minecraft.core.UUIDUtil;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.Connection;
import net.minecraft.network.chat.ChatType;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.OutgoingChatMessage;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.protocol.PacketFlow;
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.ClientInformation;
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.server.players.ProfileResolver;
import net.minecraft.server.players.UserNameToIdResolver;
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.level.GameType;
import net.minecraft.world.level.LevelSettings;
import net.minecraft.world.level.WorldDataConfiguration;
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;
/**
* Runs command scripts through vanilla's real command implementations on a
* stand-in integrated server (a real MinecraftServer with a generated world
* and one single-player owner), recording every system and chat message the
* player receives as styled spans together with the results reported to the
* player's CommandResultCallback. Shared by tools/test_command_exec_parity.py.
*
* VanillaCommandExecOracle <universe> <script.jsonl> <out.jsonl> <seed>
*/
public final class VanillaCommandExecOracle {
static final List<JsonArray> messages = new ArrayList<>();
static final class Resolver implements ProfileResolver, UserNameToIdResolver {
@Override public Optional<GameProfile> fetchByName(String name) { return Optional.empty(); }
@Override public Optional<GameProfile> fetchById(UUID id) { return Optional.empty(); }
@Override public void add(NameAndId nameAndId) {}
@Override public Optional<NameAndId> get(String name) { return Optional.empty(); }
@Override public Optional<NameAndId> get(UUID id) { return Optional.empty(); }
@Override public void resolveOfflineUsers(boolean value) {}
@Override public void save() {}
}
static final class Server extends MinecraftServer {
final Path script;
final Path output;
final LocalSampleLogger sampleLogger = new LocalSampleLogger(4);
boolean ran;
static Server create(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs, long seed, Path script, Path output) throws Exception {
packs.reload();
WorldDataConfiguration config = WorldDataConfiguration.DEFAULT;
LevelSettings settings = new LevelSettings("Harness", 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.INTEGRATED, LevelBasedPermissionSet.OWNER);
WorldOptions options = new WorldOptions(seed, true, false);
WorldStem stem = Util.<WorldStem>blockUntilDone(executor -> WorldLoader.load(init, context -> {
Registry<LevelStem> noDatapackDimensions = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze();
WorldDimensions dimensions = context.datapackWorldRegistries().lookupOrThrow(Registries.WORLD_PRESET)
.getOrThrow(WorldPresets.NORMAL).value().createWorldDimensions();
WorldDimensions.Complete complete = dimensions.bake(noDatapackDimensions);
PrimaryLevelData data = new PrimaryLevelData(settings, complete.specialWorldProperty(), complete.lifecycle());
return new WorldLoader.DataLoadOutput<>(
new LevelDataAndDimensions.WorldDataAndGenSettings(data, new WorldGenSettings(options, dimensions)),
complete.dimensionsRegistryAccess());
}, WorldStem::new, Util.backgroundExecutor(), executor)).get();
return new Server(thread, access, packs, stem, script, output);
}
Server(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs, WorldStem stem, Path script, Path output) {
super(thread, access, packs, stem, Optional.of(new GameRules(WorldDataConfiguration.DEFAULT.enabledFeatures())), Proxy.NO_PROXY,
DataFixers.getDataFixer(), new Services(null, ServicesKeySet.EMPTY, null, new Resolver(), new Resolver()),
LoggingLevelLoadListener.forDedicatedServer(), false, new NotificationManager());
this.script = script;
this.output = output;
}
@Override protected boolean initServer() {
this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, new EmptyNotificationService()) {});
this.loadLevel();
return true;
}
@Override protected void tickServer(BooleanSupplier haveTime) {
if (ran) {
return;
}
ran = true;
try {
runScript();
} catch (Throwable t) {
t.printStackTrace();
Runtime.getRuntime().halt(2);
}
System.out.flush();
Runtime.getRuntime().halt(0);
}
ServerPlayer player;
void runScript() throws IOException {
ServerLevel level = this.overworld();
GameProfile profile = new GameProfile(UUIDUtil.createOfflinePlayerUUID("Player"), "Player");
CommonListenerCookie cookie = CommonListenerCookie.createInitial(profile, false);
player = new ServerPlayer(this, level, profile, ClientInformation.createDefault()) {
@Override public void sendSystemMessage(Component message, boolean overlay) {
if (!overlay) {
messages.add(spans(message));
}
}
@Override public void sendChatMessage(OutgoingChatMessage message, boolean filtered, ChatType.Bound chatType) {
messages.add(spans(chatType.decorate(message.content())));
}
};
Connection connection = new Connection(PacketFlow.SERVERBOUND);
new EmbeddedChannel(connection);
this.getPlayerList().placeNewPlayer(connection, player, cookie);
settle();
StringBuilder out = new StringBuilder();
Gson gson = new Gson();
for (String line : Files.readAllLines(script, StandardCharsets.UTF_8)) {
if (line.isBlank()) {
continue;
}
JsonObject op = JsonParser.parseString(line).getAsJsonObject();
switch (op.get("op").getAsString()) {
case "cmd" -> {
String command = op.get("cmd").getAsString();
messages.clear();
List<JsonArray> results = new ArrayList<>();
var source = player.createCommandSourceStack().withCallback((success, value) -> {
JsonArray r = new JsonArray();
r.add(success);
r.add(value);
results.add(r);
});
this.getCommands().performPrefixedCommand(source, command);
if (!op.has("record") || op.get("record").getAsBoolean()) {
JsonObject record = new JsonObject();
record.addProperty("cmd", command);
JsonArray m = new JsonArray();
messages.forEach(m::add);
record.add("messages", m);
JsonArray r = new JsonArray();
results.forEach(r::add);
record.add("results", r);
out.append(gson.toJson(record)).append('\n');
}
}
case "tick" -> {
int n = op.has("n") ? op.get("n").getAsInt() : 1;
messages.clear();
// Answers computed off-thread (profile lookups) reach the
// server's task queue before the next tick.
// (Other queued tasks may be pending already, so give
// the stub resolvers a fixed moment rather than
// waiting for the queue to fill.)
if (op.has("record")) {
try { Thread.sleep(300); } catch (InterruptedException e) { throw new RuntimeException(e); }
}
for (int i = 0; i < n; i++) {
tick();
}
if (op.has("record") && op.get("record").getAsBoolean()) {
JsonObject record = new JsonObject();
record.addProperty("cmd", "#tick");
JsonArray m = new JsonArray();
messages.forEach(m::add);
record.add("messages", m);
record.add("results", new JsonArray());
out.append(gson.toJson(record)).append('\n');
}
}
case "settle" -> settle();
default -> throw new IllegalArgumentException(line);
}
}
Files.writeString(output, out.toString(), StandardCharsets.UTF_8);
}
/** One iteration of MinecraftServer.runServer: the delayed tick profiler start, then the tick. */
void tick() {
try {
var delay = MinecraftServer.class.getDeclaredField("debugCommandProfilerDelayStart");
delay.setAccessible(true);
if (delay.getBoolean(this)) {
delay.setBoolean(this, false);
Class<?> profilerClass = Class.forName("net.minecraft.server.MinecraftServer$TimeProfiler");
var ctor = profilerClass.getDeclaredConstructor(long.class, int.class);
ctor.setAccessible(true);
var field = MinecraftServer.class.getDeclaredField("debugCommandProfiler");
field.setAccessible(true);
field.set(this, ctor.newInstance(Util.getNanos(), this.getTickCount()));
}
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
drain();
super.tickServer(() -> false);
// The player's network listener ticks it each server tick
// (ServerGamePacketListenerImpl.tickPlayer); this one has no
// listening connection. Its movement is the client's, so of
// that tick only apply changed attributes (waypoint range...).
if (player != null) {
try {
var refresh = net.minecraft.world.entity.LivingEntity.class.getDeclaredMethod("refreshDirtyAttributes");
refresh.setAccessible(true);
refresh.invoke(player);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
drain();
}
/** The server's and every level's chunk task queues (runServer's waits run them). */
void drain() {
boolean more = true;
while (more) {
more = false;
this.runAllTasks();
for (ServerLevel level : this.getAllLevels()) {
while (level.getChunkSource().pollTask()) {
more = true;
}
}
}
}
/** Force-load the chunks around the player (Horizon waits for its streamed terrain). */
void settle() {
ServerLevel level = player.level();
int cx = player.chunkPosition().x(), cz = player.chunkPosition().z();
for (int dz = -2; dz <= 2; dz++) {
for (int dx = -2; dx <= 2; dx++) {
// An entity-ticking ticket that, unlike setChunkForced,
// is not a force-load /forceload would report.
level.getChunkSource().addTicket(
new net.minecraft.server.level.Ticket(net.minecraft.server.level.TicketType.DRAGON, net.minecraft.server.level.ChunkMap.FORCED_TICKET_LEVEL),
new net.minecraft.world.level.ChunkPos(cx + dx, cz + dz));
level.getChunk(cx + dx, cz + dz);
}
}
// Entity sections become visible once their (asynchronous) load
// finished and the chunk entity-ticks.
for (int i = 0; i < 400; i++) {
tick();
boolean ready = true;
for (int dz = -2; dz <= 2 && ready; dz++) {
for (int dx = -2; dx <= 2 && ready; dx++) {
ready = level.areEntitiesActuallyLoadedAndTicking(new net.minecraft.world.level.ChunkPos(cx + dx, cz + dz));
}
}
if (ready && i >= 5) {
return;
}
try { Thread.sleep(5); } catch (InterruptedException e) { throw new RuntimeException(e); }
}
throw new IllegalStateException("entities around the player did not load");
}
static JsonArray spans(Component message) {
JsonArray out = new JsonArray();
message.visit((style, text) -> {
if (text.isEmpty()) {
return Optional.empty();
}
JsonArray key = styleKey(style);
if (!out.isEmpty()) {
JsonArray last = out.get(out.size() - 1).getAsJsonArray();
if (last.get(1).equals(key)) {
last.set(0, new com.google.gson.JsonPrimitive(last.get(0).getAsString() + text));
return Optional.empty();
}
}
JsonArray span = new JsonArray();
span.add(text);
span.add(key);
out.add(span);
return Optional.empty();
}, Style.EMPTY);
return out;
}
static JsonArray styleKey(Style style) {
JsonArray key = new JsonArray();
if (style.getColor() == null) {
key.add(com.google.gson.JsonNull.INSTANCE);
} else {
key.add(style.getColor().getValue() & 0xFFFFFF);
}
key.add(style.isBold());
key.add(style.isItalic());
key.add(style.isUnderlined());
key.add(style.isStrikethrough());
key.add(style.isObfuscated());
return key;
}
@Override public LevelBasedPermissionSet getProfilePermissions(NameAndId nameAndId) { return LevelBasedPermissionSet.OWNER; }
@Override protected SampleLogger getTickTimeLogger() { return sampleLogger; }
@Override public boolean isTickTimeLoggingEnabled() { return false; }
@Override public SystemReport fillServerSystemReport(SystemReport report) { return report; }
@Override public boolean isHardcore() { return false; }
@Override public LevelBasedPermissionSet operatorUserPermissions() { return LevelBasedPermissionSet.GAMEMASTER; }
@Override public PermissionSet getFunctionCompilationPermissions() { return LevelBasedPermissionSet.GAMEMASTER; }
@Override public boolean shouldRconBroadcast() { return true; }
@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 true; }
@Override public boolean isSingleplayerOwner(NameAndId nameAndId) { return nameAndId.name().equalsIgnoreCase("Player"); }
@Override public int getMaxPlayers() { return 8; }
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
Path universe = Path.of(args[0]);
Path script = Path.of(args[1]).toAbsolutePath();
Path output = Path.of(args[2]).toAbsolutePath();
long seed = Long.parseLong(args[3]);
Files.createDirectories(universe);
LevelStorageSource.LevelStorageAccess access = LevelStorageSource.createDefault(universe).createAccess("harness");
PackRepository packs = ServerPacksSource.createPackRepository(access);
MinecraftServer.spin(thread -> {
try {
return Server.create(thread, access, packs, seed, script, output);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
}
@@ -40,6 +40,10 @@ import net.minecraft.world.level.storage.LevelStorageSource;
*
* Files the game rewrites after loading get the current DataVersion so that the
* output compares with what the game would save. Nothing is answered by hand.
*
* OUT_WORLD is replaced. The oracle exits as soon as everything is written:
* the level storage starts the game's IO worker pool, whose idle threads would
* otherwise keep the JVM alive for a minute.
*/
public final class VanillaDataFixOracle {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
@@ -49,6 +53,7 @@ public final class VanillaDataFixOracle {
Bootstrap.bootStrap();
Path in = Path.of(args[0]);
Path out = Path.of(args[1]);
delete(out);
copy(in, out);
int current = SharedConstants.getCurrentVersion().dataVersion().version();
var fixer = DataFixers.getDataFixer();
@@ -104,6 +109,7 @@ public final class VanillaDataFixOracle {
fixed = fixed.set("DataVersion", fixed.createInt(current));
Files.writeString(file, GSON.toJson(fixed.getValue()), StandardCharsets.UTF_8);
}
System.exit(0);
}
/** Chunk generator type per dimension, from the saved world generation settings. */
@@ -231,6 +237,17 @@ public final class VanillaDataFixOracle {
}
}
private static void delete(Path path) throws Exception {
if (!Files.exists(path)) {
return;
}
try (Stream<Path> s = Files.walk(path)) {
for (Path p : s.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(p);
}
}
}
private static void copy(Path from, Path to) throws Exception {
try (Stream<Path> s = Files.walk(from)) {
for (Path p : s.sorted().toList()) {
@@ -43,19 +43,22 @@ import org.joml.Matrix3x2f;
import org.joml.Matrix3x2fStack;
/**
* Original oracle for the in-game HUD decorations: runs vanilla's own Hud
* methods (extractItemHotbar, extractPlayerHealth, extractVehicleHealth,
* extractCrosshair) and ExperienceBar / ContextualBar on a stand-in client
* (Unsafe-allocated Minecraft, options, game mode, window and level) and a
* player whose state getters answer from the case, and records every
* GuiGraphicsExtractor blit, text and item call.
* Oracle for the in-game HUD: runs vanilla's own Hud methods (hotbar,
* crosshair, health, mount, experience, effects, titles and the action bar,
* the selected item name, the sidebar, camera and sleep overlays and
* Hud.tick), BossHealthOverlay, JumpableVehicleBar, ChatComponent and
* GuiGraphicsExtractor.itemDecorations on a stand-in client (Unsafe-allocated
* Minecraft, options, game mode, window and level) and a player whose state
* getters answer from the case, and records every GuiGraphicsExtractor blit,
* fill, text and item call. See tools/test_hud_parity.py for the case kinds.
*
* Input lines: case JSON. Output lines: {case, draws:[...]} or {case, error}.
* Input lines: case JSON. Output lines: {case, draws:[...], state...} or {case, error}.
*/
public final class VanillaHudOracle {
static Object unsafe;
static Method allocate;
static JsonObject c;
static Font FONT;
static IdentityHashMap<ItemStack, Integer> slots = new IdentityHashMap<>();
@SuppressWarnings("unchecked")
@@ -84,9 +87,41 @@ public final class VanillaHudOracle {
unsafe.getClass().getMethod(setter, Object.class, long.class, param).invoke(unsafe, target, offset, value);
}
static void putStatic(Class<?> owner, String name, Object value) throws Exception {
Field f = field(owner, name);
var u = unsafe.getClass();
Object base = u.getMethod("staticFieldBase", Field.class).invoke(unsafe, f);
long offset = (long) u.getMethod("staticFieldOffset", Field.class).invoke(unsafe, f);
u.getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, base, offset, value);
}
static float f(String k, float d) { return c.has(k) && !c.get(k).isJsonNull() ? c.get(k).getAsFloat() : d; }
static int i(String k, int d) { return c.has(k) && !c.get(k).isJsonNull() ? c.get(k).getAsInt() : d; }
static boolean b(String k) { return c.has(k) && c.get(k).getAsBoolean(); }
static net.minecraft.network.chat.Component comp(JsonElement e) {
return net.minecraft.network.chat.ComponentSerialization.CODEC.parse(com.mojang.serialization.JsonOps.INSTANCE, e).getOrThrow();
}
static <T> OptionInstance<T> option(T value) throws Exception {
@SuppressWarnings("unchecked") OptionInstance<T> o = alloc(OptionInstance.class);
put(o, OptionInstance.class, "value", value);
return o;
}
static net.minecraft.network.chat.numbers.NumberFormat numberFormat(JsonElement e) {
if (e == null || e.isJsonNull()) return null;
var o = e.getAsJsonObject();
return switch (o.get("type").getAsString()) {
case "blank" -> net.minecraft.network.chat.numbers.BlankFormat.INSTANCE;
case "fixed" -> new net.minecraft.network.chat.numbers.FixedFormat(comp(o.get("value")));
case "styled" -> new net.minecraft.network.chat.numbers.StyledFormat(
net.minecraft.network.chat.Style.Serializer.MAP_CODEC.codec().parse(com.mojang.serialization.JsonOps.INSTANCE, o.get("style")).getOrThrow());
default -> throw new IllegalArgumentException(o.toString());
};
}
static Method hudMethod(String name, Class<?>... params) throws Exception {
Method m = Hud.class.getDeclaredMethod(name, params);
m.setAccessible(true);
return m;
}
/** A player whose HUD-facing getters answer from the case. */
public static final class Actor extends LocalPlayer {
@@ -94,6 +129,7 @@ public final class VanillaHudOracle {
Entity vehicle;
FoodData food;
ItemStack offhand = ItemStack.EMPTY;
List<net.minecraft.world.effect.MobEffectInstance> active = new ArrayList<>();
private Actor() { super(null, null, null, null, null, null, false, null, null); }
@Override public float getHealth() { return f("health", 20); }
@Override public double getAttributeValue(Holder<Attribute> a) { return a == Attributes.MAX_HEALTH ? f("maxHealth", 20) : 0.0; }
@@ -101,9 +137,10 @@ public final class VanillaHudOracle {
@Override public int getArmorValue() { return i("armor", 0); }
@Override public FoodData getFoodData() { return food; }
@Override public boolean hasEffect(Holder<MobEffect> effect) {
for (var e : c.getAsJsonArray("effects")) if (effect.is(Identifier.parse(e.getAsString()))) return true;
if (c.has("effects")) for (var e : c.getAsJsonArray("effects")) if (effect.is(Identifier.parse(e.getAsString()))) return true;
return false;
}
@Override public java.util.Collection<net.minecraft.world.effect.MobEffectInstance> getActiveEffects() { return active; }
@Override public boolean isFullyFrozen() { return b("frozen"); }
@Override public int getAirSupply() { return i("air", 300); }
@Override public int getMaxAirSupply() { return i("maxAir", 300); }
@@ -114,6 +151,23 @@ public final class VanillaHudOracle {
@Override public float getAttackStrengthScale(float a) { return f("attackScale", 1); }
@Override public Level level() { return level; }
@Override public boolean isSpectator() { return false; }
@Override public net.minecraft.world.entity.PlayerRideableJumping jumpableVehicle() {
return (net.minecraft.world.entity.PlayerRideableJumping) Proxy.newProxyInstance(Actor.class.getClassLoader(),
new Class<?>[] {net.minecraft.world.entity.PlayerRideableJumping.class},
(proxy, method, a) -> method.getName().equals("getJumpCooldown") ? i("cooldown", 0)
: method.getReturnType() == boolean.class ? false : method.getReturnType() == float.class ? 0.0F : null);
}
@Override public float getJumpRidingScale() { return f("jumpScale", 0); }
@Override public ItemStack getItemBySlot(net.minecraft.world.entity.EquipmentSlot slot) {
return slot == net.minecraft.world.entity.EquipmentSlot.HEAD && c.has("head") && !c.get("head").isJsonNull()
? new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.withDefaultNamespace(c.get("head").getAsString()))) : ItemStack.EMPTY;
}
@Override public int getTicksFrozen() { return i("ticksFrozen", 0); }
@Override public boolean isScoping() { return b("scoping"); }
@Override public float getEffectBlendFactor(Holder<MobEffect> effect, float partial) {
return effect.is(net.minecraft.world.effect.MobEffects.NAUSEA) ? f("nausea", 0) : 0.0F;
}
@Override public int getSleepTimer() { return i("sleepTimer", 0); }
@Override public void playSound(net.minecraft.sounds.SoundEvent sound, float volume, float pitch) { }
}
@@ -134,6 +188,16 @@ public final class VanillaHudOracle {
@Override public int guiHeight() { return i("height", 0); }
@Override public Matrix3x2fStack pose() { return stack; }
@Override public void nextStratum() { }
/** Adds the pose when it is not the identity. */
JsonObject posed(JsonObject o, org.joml.Matrix3x2fc m) {
if (!m.equals(new Matrix3x2f())) {
var a = new JsonArray();
for (float v : new float[] {m.m00(), m.m01(), m.m10(), m.m11(), m.m20(), m.m21()}) a.add(v);
o.add("matrix", a);
}
draws.add(o);
return o;
}
void sprite(Identifier id, int x, int y, int w, int h, int[] region, int color) {
var o = new JsonObject();
o.addProperty("type", "sprite");
@@ -145,20 +209,86 @@ public final class VanillaHudOracle {
o.add("region", r);
}
o.addProperty("color", color);
draws.add(o);
posed(o, stack);
}
@Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) { sprite(id, x, y, w, h, null, color); }
@Override public void blitSprite(RenderPipeline p, Identifier id, int sw, int sh, int u, int v, int x, int y, int w, int h, int color) {
sprite(id, x, y, w, h, new int[] {sw, sh, u, v}, color);
}
@Override public void text(Font font, FormattedCharSequence str, int x, int y, int color, boolean shadow) {
@Override public void blitSprite(RenderPipeline p, net.minecraft.client.renderer.texture.TextureAtlasSprite s, int x, int y, int w, int h, int color) {
var o = new JsonObject();
o.addProperty("type", "atlas");
o.addProperty("sprite", s.contents().name().getPath());
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
o.addProperty("color", color);
posed(o, stack);
}
@Override public void blit(RenderPipeline p, Identifier texture, int x, int y, float u, float v, int w, int h, int srcW, int srcH, int texW, int texH, int color) {
var o = new JsonObject();
o.addProperty("type", "blit");
o.addProperty("texture", texture.getPath());
o.addProperty("pipeline", p.getLocation().getPath());
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
var uv = new JsonArray(); uv.add(u); uv.add(v); o.add("uv", uv);
var src = new JsonArray(); src.add(srcW); src.add(srcH); o.add("src", src);
var tex = new JsonArray(); tex.add(texW); tex.add(texH); o.add("tex", tex);
o.addProperty("color", color);
posed(o, stack);
}
@Override public void fill(RenderPipeline p, int x0, int y0, int x1, int y1, int color) {
var o = new JsonObject();
o.addProperty("type", "fill");
o.addProperty("x0", Math.min(x0, x1)); o.addProperty("y0", Math.min(y0, y1));
o.addProperty("x1", Math.max(x0, x1)); o.addProperty("y1", Math.max(y0, y1));
o.addProperty("color", color);
posed(o, stack);
}
void text(FormattedCharSequence str, int x, int y, int color, boolean shadow, org.joml.Matrix3x2fc pose) {
var o = new JsonObject();
o.addProperty("type", "text");
var sb = new StringBuilder();
str.accept((index, style, cp) -> { sb.appendCodePoint(cp); return true; });
var runs = new JsonArray();
boolean[] styled = {false};
str.accept((index, style, cp) -> {
sb.appendCodePoint(cp);
Integer rgb = style.getColor() == null ? null : style.getColor().getValue();
boolean bold = style.isBold(), italic = style.isItalic();
styled[0] |= rgb != null || bold || italic;
JsonArray last = runs.isEmpty() ? null : runs.get(runs.size() - 1).getAsJsonArray();
if (last != null && java.util.Objects.equals(last.get(1).isJsonNull() ? null : last.get(1).getAsInt(), rgb)
&& last.get(2).getAsBoolean() == bold && last.get(3).getAsBoolean() == italic) {
last.set(0, new JsonPrimitive(last.get(0).getAsString() + new String(Character.toChars(cp))));
} else {
var run = new JsonArray();
run.add(new String(Character.toChars(cp)));
if (rgb == null) run.add(JsonNull.INSTANCE); else run.add(rgb);
run.add(bold); run.add(italic);
runs.add(run);
}
return true;
});
o.addProperty("text", sb.toString());
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("color", color); o.addProperty("shadow", shadow);
draws.add(o);
if (styled[0]) o.add("runs", runs);
posed(o, pose);
}
@Override public void text(Font font, FormattedCharSequence str, int x, int y, int color, boolean shadow) {
if (net.minecraft.util.ARGB.alpha(color) != 0) text(str, x, y, color, shadow, stack);
}
/** The chat's text collector: text at the parameters' pose and opacity. */
@Override public net.minecraft.client.gui.ActiveTextCollector textRenderer(GuiGraphicsExtractor.HoveredTextEffects effects, java.util.function.Consumer<net.minecraft.network.chat.Style> consumer) {
var self = this;
return new net.minecraft.client.gui.ActiveTextCollector() {
Parameters parameters = new Parameters(new Matrix3x2f(stack), 1.0F, null);
@Override public Parameters defaultParameters() { return parameters; }
@Override public void defaultParameters(Parameters p) { parameters = p; }
@Override public void accept(net.minecraft.client.gui.TextAlignment alignment, int anchorX, int y, Parameters p, FormattedCharSequence text) {
int left = alignment.calculateLeft(anchorX, FONT, text);
if (net.minecraft.util.ARGB.as8BitChannel(p.opacity()) != 0)
self.text(text, left, y, net.minecraft.util.ARGB.white(p.opacity()), true, p.pose());
}
@Override public void acceptScrolling(net.minecraft.network.chat.Component m, int cx, int l, int r, int t, int b, Parameters p) { }
};
}
@Override public void item(LivingEntity owner, ItemStack stack, int x, int y, int seed) {
var o = new JsonObject();
@@ -171,7 +301,11 @@ public final class VanillaHudOracle {
o.add("matrix", a);
draws.add(o);
}
@Override public void itemDecorations(Font font, ItemStack stack, int x, int y, String count) { }
/** Off for the hotbar cases (Horizon draws the decorations with the item). */
boolean realDecorations;
@Override public void itemDecorations(Font font, ItemStack stack, int x, int y, String count) {
if (realDecorations) super.itemDecorations(font, stack, x, y, count);
}
}
public static void main(String[] args) throws Exception {
@@ -180,13 +314,21 @@ public final class VanillaHudOracle {
unsafeField.setAccessible(true);
unsafe = unsafeField.get(null);
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
Font font = ParityFont.create(ParityFont.resources());
Font font = FONT = ParityFont.create(ParityFont.resources());
Method hotbar = Hud.class.getDeclaredMethod("extractItemHotbar", GuiGraphicsExtractor.class, DeltaTracker.class);
Method health = Hud.class.getDeclaredMethod("extractPlayerHealth", GuiGraphicsExtractor.class);
Method vehicle = Hud.class.getDeclaredMethod("extractVehicleHealth", GuiGraphicsExtractor.class);
Method crosshair = Hud.class.getDeclaredMethod("extractCrosshair", GuiGraphicsExtractor.class, DeltaTracker.class);
crosshair.setAccessible(true);
for (Method m : new Method[] {hotbar, health, vehicle}) m.setAccessible(true);
Method effects = hudMethod("extractEffects", GuiGraphicsExtractor.class, DeltaTracker.class);
Method title = hudMethod("extractTitle", GuiGraphicsExtractor.class, DeltaTracker.class);
Method overlayMessage = hudMethod("extractOverlayMessage", GuiGraphicsExtractor.class, DeltaTracker.class);
Method selectedName = hudMethod("extractSelectedItemName", GuiGraphicsExtractor.class);
Method tick = hudMethod("tick");
Method cameraOverlays = hudMethod("extractCameraOverlays", GuiGraphicsExtractor.class, DeltaTracker.class);
Method sleep = hudMethod("extractSleepOverlay", GuiGraphicsExtractor.class, DeltaTracker.class);
Method sidebar = hudMethod("displayScoreboardSidebar", GuiGraphicsExtractor.class, net.minecraft.world.scores.Objective.class);
Method level = Class.forName("net.minecraft.client.gui.contextualbar.ContextualBar")
.getDeclaredMethod("extractExperienceLevel", GuiGraphicsExtractor.class, Font.class, int.class);
level.setAccessible(true);
@@ -207,6 +349,7 @@ public final class VanillaHudOracle {
put(clientLevel, ClientLevel.class, "clientLevelData", levelData);
actor.level = clientLevel;
actor.offhand = ItemStack.EMPTY;
actor.active = new ArrayList<>();
actor.food = new FoodData();
actor.food.setFoodLevel(i("food", 20));
actor.food.setSaturation(f("saturation", 5));
@@ -219,7 +362,7 @@ public final class VanillaHudOracle {
var stacks = c.getAsJsonArray("slots");
var items = new net.minecraft.world.item.Item[] {Items.STONE, Items.DIAMOND_SWORD, Items.APPLE, Items.TORCH, Items.BOW,
Items.OAK_LOG, Items.BREAD, Items.SHIELD, Items.COMPASS};
for (int n = 0; n < 9; n++) {
for (int n = 0; stacks != null && n < 9; n++) {
if (stacks.get(n).isJsonNull()) continue;
var stack = new ItemStack(items[n]);
stack.setPopTime(stacks.get(n).getAsInt());
@@ -240,17 +383,21 @@ public final class VanillaHudOracle {
put(mc, Minecraft.class, "gameRenderer", renderer);
put(mc, Minecraft.class, "font", font);
var gameMode = alloc(MultiPlayerGameMode.class);
put(gameMode, MultiPlayerGameMode.class, "localPlayerMode", GameType.byName(c.get("gameMode").getAsString()));
put(gameMode, MultiPlayerGameMode.class, "localPlayerMode", GameType.byName(c.has("gameMode") ? c.get("gameMode").getAsString() : "survival"));
put(mc, Minecraft.class, "gameMode", gameMode);
var options = alloc(Options.class);
var indicator = alloc(OptionInstance.class);
put(indicator, OptionInstance.class, "value", AttackIndicatorStatus.valueOf(c.get("attackIndicator").getAsString()));
put(options, Options.class, "attackIndicator", indicator);
put(options, Options.class, "attackIndicator", option(AttackIndicatorStatus.valueOf(c.has("attackIndicator") ? c.get("attackIndicator").getAsString() : "OFF")));
put(options, Options.class, "backgroundForChatOnly", option(c.has("chatOnly") ? b("chatOnly") : true));
put(options, Options.class, "textBackgroundOpacity", option((double) f("textOpacity", 0.5F)));
put(options, Options.class, "notificationDisplayTime", option(c.has("displayTime") ? c.get("displayTime").getAsDouble() : 1.0));
put(mc, Minecraft.class, "options", options);
var window = alloc(com.mojang.blaze3d.platform.Window.class);
put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledWidth", i("width", 0));
put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledHeight", i("height", 0));
put(mc, Minecraft.class, "window", window);
var gui = alloc(net.minecraft.client.gui.Gui.class);
put(mc, Minecraft.class, "gui", gui);
put(mc, Minecraft.class, "demo", b("demo"));
var hud = alloc(Hud.class);
put(hud, Hud.class, "minecraft", mc);
put(hud, Hud.class, "random", net.minecraft.util.RandomSource.create());
@@ -259,25 +406,197 @@ public final class VanillaHudOracle {
put(hud, Hud.class, "displayHealth", i("displayHealth", 0));
put(hud, Hud.class, "lastHealthTime", Util.getMillis() - (long) i("lastHealthAgo", 0));
put(hud, Hud.class, "healthBlinkTime", (long) i("healthBlinkTime", 0));
put(hud, Hud.class, "lastToolHighlight", ItemStack.EMPTY);
var chat = alloc(net.minecraft.client.gui.components.ChatComponent.class);
put(chat, net.minecraft.client.gui.components.ChatComponent.class, "messageDeletionQueue", new ArrayList<>());
put(hud, Hud.class, "chat", chat);
hud.resetTitleTimes();
var capture = alloc(Capture.class);
capture.draws = new JsonArray();
capture.stack = new Matrix3x2fStack(16);
put(capture, GuiGraphicsExtractor.class, "minecraft", mc);
put(capture, GuiGraphicsExtractor.class, "pose", capture.stack);
float partial = f("partial", 0);
DeltaTracker delta = (DeltaTracker) Proxy.newProxyInstance(DeltaTracker.class.getClassLoader(), new Class<?>[] {DeltaTracker.class},
(proxy, method, a) -> method.getReturnType() == float.class ? partial : null);
var mode = GameType.byName(c.get("gameMode").getAsString());
if (c.has("crosshair") && c.get("crosshair").getAsBoolean()) {
put(options, Options.class, "cameraType", net.minecraft.client.CameraType.FIRST_PERSON);
var debug = alloc(net.minecraft.client.gui.components.debug.DebugScreenEntryList.class);
put(debug, net.minecraft.client.gui.components.debug.DebugScreenEntryList.class, "currentlyEnabled", new ArrayList<Identifier>());
put(mc, Minecraft.class, "debugEntries", debug);
crosshair.invoke(hud, capture, delta);
var mode = GameType.byName(c.has("gameMode") ? c.get("gameMode").getAsString() : "survival");
// Hud.tick's vignette brightness reads the camera entity's level: tick without one.
if (Set.of("title", "selected").contains(c.get("kind").getAsString()))
put(camera, net.minecraft.client.Camera.class, "entity", null);
switch (c.get("kind").getAsString()) {
case "decorations" -> {
if (c.has("crosshair") && c.get("crosshair").getAsBoolean()) {
put(options, Options.class, "cameraType", net.minecraft.client.CameraType.FIRST_PERSON);
var debug = alloc(net.minecraft.client.gui.components.debug.DebugScreenEntryList.class);
put(debug, net.minecraft.client.gui.components.debug.DebugScreenEntryList.class, "currentlyEnabled", new ArrayList<Identifier>());
put(mc, Minecraft.class, "debugEntries", debug);
crosshair.invoke(hud, capture, delta);
}
if (mode != GameType.SPECTATOR) hotbar.invoke(hud, capture, delta);
if (mode.isSurvival()) health.invoke(hud, capture);
vehicle.invoke(hud, capture);
if (c.has("experienceBar") && c.get("experienceBar").getAsBoolean()) new ExperienceBar(mc).extractBackground(capture, delta);
if (mode.isSurvival() && actor.experienceLevel > 0) level.invoke(null, capture, font, actor.experienceLevel);
}
case "effects" -> {
for (var e : c.getAsJsonArray("active")) {
var o = e.getAsJsonObject();
var effect = BuiltInRegistries.MOB_EFFECT.get(Identifier.parse(o.get("id").getAsString())).orElseThrow();
actor.active.add(new net.minecraft.world.effect.MobEffectInstance(effect, o.get("duration").getAsInt(), 0,
o.get("ambient").getAsBoolean(), true, o.get("icon").getAsBoolean()));
}
effects.invoke(hud, capture, delta);
}
case "title" -> {
for (var e : c.getAsJsonArray("ops")) {
var op = e.getAsJsonArray();
switch (op.get(0).getAsString()) {
case "title" -> hud.setTitle(comp(op.get(1)));
case "subtitle" -> hud.setSubtitle(comp(op.get(1)));
case "times" -> hud.setTimes(op.get(1).getAsInt(), op.get(2).getAsInt(), op.get(3).getAsInt());
case "clear" -> hud.clearTitles();
case "reset" -> hud.resetTitleTimes();
case "overlay" -> hud.setOverlayMessage(comp(op.get(1)), op.get(2).getAsBoolean());
case "tick" -> { for (int n = op.get(1).getAsInt(); n > 0; n--) tick.invoke(hud); }
default -> throw new IllegalArgumentException(op.toString());
}
}
overlayMessage.invoke(hud, capture, delta);
title.invoke(hud, capture, delta);
}
case "selected" -> {
int slot = i("selected", 0);
for (var e : c.getAsJsonArray("steps")) {
ItemStack stack = ItemStack.EMPTY;
if (!e.isJsonNull()) {
var o = e.getAsJsonObject();
stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.withDefaultNamespace(o.get("item").getAsString())));
if (!o.get("custom").isJsonNull()) stack.set(net.minecraft.core.component.DataComponents.CUSTOM_NAME, comp(o.get("custom")));
}
inventory.setItem(slot, stack);
tick.invoke(hud);
}
selectedName.invoke(hud, capture);
}
case "boss" -> {
var overlay = new net.minecraft.client.gui.components.BossHealthOverlay(mc);
@SuppressWarnings("unchecked") var events = (Map<UUID, net.minecraft.client.gui.components.LerpingBossEvent>)
field(net.minecraft.client.gui.components.BossHealthOverlay.class, "events").get(overlay);
for (var e : c.getAsJsonArray("bars")) {
var o = e.getAsJsonObject();
var id = UUID.randomUUID();
events.put(id, new net.minecraft.client.gui.components.LerpingBossEvent(id, comp(o.get("name")), o.get("progress").getAsFloat(),
net.minecraft.world.BossEvent.BossBarColor.values()[o.get("color").getAsInt()],
net.minecraft.world.BossEvent.BossBarOverlay.values()[o.get("overlay").getAsInt()], false, false, false));
}
overlay.extractRenderState(capture);
}
case "jump" -> new net.minecraft.client.gui.contextualbar.JumpableVehicleBar(mc).extractBackground(capture, delta);
case "sidebar" -> {
var board = new net.minecraft.world.scores.Scoreboard();
var o = c.getAsJsonObject("objective");
var objective = board.addObjective("sidebar", net.minecraft.world.scores.criteria.ObjectiveCriteria.DUMMY, comp(o.get("display")),
net.minecraft.world.scores.criteria.ObjectiveCriteria.RenderType.INTEGER, false, numberFormat(o.get("format")));
for (var e : c.getAsJsonArray("scores")) {
var sc = e.getAsJsonObject();
var access = board.getOrCreatePlayerScore(net.minecraft.world.scores.ScoreHolder.forNameOnly(sc.get("owner").getAsString()), objective);
access.set(sc.get("value").getAsInt());
if (!sc.get("display").isJsonNull()) access.display(comp(sc.get("display")));
access.numberFormatOverride(numberFormat(sc.get("format")));
}
for (var e : c.getAsJsonArray("teams")) {
var t = e.getAsJsonObject();
var team = board.addPlayerTeam(t.get("name").getAsString());
team.setPlayerPrefix(comp(t.get("prefix")));
team.setPlayerSuffix(comp(t.get("suffix")));
team.setColor(t.get("color").isJsonNull() ? Optional.empty()
: Optional.of(net.minecraft.world.scores.TeamColor.byName(t.get("color").getAsString())));
for (var m : t.getAsJsonArray("members")) board.addPlayerToTeam(m.getAsString(), team);
}
sidebar.invoke(hud, capture, objective);
}
case "decor" -> {
var stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.withDefaultNamespace(c.get("item").getAsString())));
stack.setCount(i("count", 1));
stack.setDamageValue(i("damage", 0));
if (b("unbreakable")) stack.set(net.minecraft.core.component.DataComponents.UNBREAKABLE, net.minecraft.util.Unit.INSTANCE);
var cooldowns = new net.minecraft.world.item.ItemCooldowns();
put(actor, net.minecraft.world.entity.player.Player.class, "cooldowns", cooldowns);
if (c.has("cooldown") && !c.get("cooldown").isJsonNull()) {
var cd = c.getAsJsonObject("cooldown");
cooldowns.addCooldown(stack, cd.get("duration").getAsInt());
for (int n = cd.get("elapsed").getAsInt(); n > 0; n--) cooldowns.tick();
}
var timer = alloc(DeltaTracker.Timer.class);
put(timer, DeltaTracker.Timer.class, "deltaTickResidual", partial);
put(mc, Minecraft.class, "deltaTracker", timer);
capture.realDecorations = true;
capture.itemDecorations(font, stack, i("x", 0), i("y", 0), c.has("countText") ? c.get("countText").getAsString() : null);
}
case "overlays" -> {
put(options, Options.class, "vignette", option(b("vignette")));
put(options, Options.class, "cameraType", b("firstPerson") ? net.minecraft.client.CameraType.FIRST_PERSON : net.minecraft.client.CameraType.THIRD_PERSON_BACK);
put(options, Options.class, "screenEffectScale", option((double) f("screenEffectScale", 1)));
var border = new net.minecraft.world.level.border.WorldBorder();
if (c.has("border") && !c.get("border").isJsonNull()) {
var bo = c.getAsJsonObject("border");
border.setCenter(bo.get("centerX").getAsDouble(), bo.get("centerZ").getAsDouble());
border.setSize(bo.get("size").getAsDouble());
border.setWarningBlocks(bo.get("warningBlocks").getAsInt());
border.setWarningTime(bo.get("warningTime").getAsInt());
}
put(clientLevel, ClientLevel.class, "worldBorder", border);
put(mc, Minecraft.class, "level", clientLevel);
put(actor, Entity.class, "position", new net.minecraft.world.phys.Vec3(f("camX", 0), 64, f("camZ", 0)));
actor.oPortalEffectIntensity = c.getAsJsonArray("portal").get(0).getAsFloat();
actor.portalEffectIntensity = c.getAsJsonArray("portal").get(1).getAsFloat();
put(hud, Hud.class, "vignetteBrightness", f("vignetteBrightness", 1));
put(hud, Hud.class, "scopeScale", f("scopeScale", 0.5F));
// The nether portal particle sprite, as the block model set would give it.
var contents = alloc(net.minecraft.client.renderer.texture.SpriteContents.class);
put(contents, net.minecraft.client.renderer.texture.SpriteContents.class, "name", Identifier.withDefaultNamespace("block/nether_portal"));
var sprite = alloc(net.minecraft.client.renderer.texture.TextureAtlasSprite.class);
put(sprite, net.minecraft.client.renderer.texture.TextureAtlasSprite.class, "contents", contents);
var material = new net.minecraft.client.resources.model.sprite.Material.Baked(sprite, false);
var model = (net.minecraft.client.renderer.block.dispatch.BlockStateModel) Proxy.newProxyInstance(Actor.class.getClassLoader(),
new Class<?>[] {net.minecraft.client.renderer.block.dispatch.BlockStateModel.class},
(proxy, method, a) -> method.getName().equals("particleMaterial") ? material : null);
var models = alloc(net.minecraft.client.resources.model.ModelManager.class);
put(models, net.minecraft.client.resources.model.ModelManager.class, "blockStateModelSet",
new net.minecraft.client.renderer.block.BlockStateModelSet(Map.of(), model));
put(mc, Minecraft.class, "modelManager", models);
cameraOverlays.invoke(hud, capture, delta);
sleep.invoke(hud, capture, delta);
result.addProperty("scopeScale", (float) field(Hud.class, "scopeScale").get(hud));
}
case "chat" -> {
for (String o : new String[] {"chatScale", "chatWidth", "chatOpacity", "chatLineSpacing", "chatHeightUnfocused", "chatHeightFocused"})
put(options, Options.class, o, option(c.get(o).getAsDouble()));
put(options, Options.class, "chatColors", option(true));
putStatic(Minecraft.class, "instance", mc);
put(gui, net.minecraft.client.gui.Gui.class, "hud", hud);
var listener = alloc(net.minecraft.client.multiplayer.chat.ChatListener.class);
put(listener, net.minecraft.client.multiplayer.chat.ChatListener.class, "delayedMessageQueue", new ArrayDeque<>());
put(gui, net.minecraft.client.gui.Gui.class, "chatListener", listener);
var C = net.minecraft.client.gui.components.ChatComponent.class;
put(chat, C, "minecraft", mc);
put(chat, C, "allMessages", new ArrayList<>());
put(chat, C, "trimmedMessages", new ArrayList<>());
put(chat, C, "visibleMessageFilter", (java.util.function.Predicate<?>) m -> true);
for (var e : c.getAsJsonArray("messages")) {
var m = e.getAsJsonObject();
put(hud, Hud.class, "tickCount", m.get("at").getAsInt());
var text = comp(m.get("text"));
switch (m.get("tag").isJsonNull() ? "" : m.get("tag").getAsString()) {
case "system" -> chat.addClientSystemMessage(text);
case "error" -> chat.addPlayerMessage(text, null, net.minecraft.client.multiplayer.chat.GuiMessageTag.chatError());
default -> chat.addPlayerMessage(text, null, null);
}
}
chat.extractRenderState(capture, font, i("now", 0), 0, 0, net.minecraft.client.gui.components.ChatComponent.DisplayMode.BACKGROUND, false);
}
default -> throw new IllegalArgumentException(c.get("kind").getAsString());
}
if (mode != GameType.SPECTATOR) hotbar.invoke(hud, capture, delta);
if (mode.isSurvival()) health.invoke(hud, capture);
vehicle.invoke(hud, capture);
if (c.has("experienceBar") && c.get("experienceBar").getAsBoolean()) new ExperienceBar(mc).extractBackground(capture, delta);
if (mode.isSurvival() && actor.experienceLevel > 0) level.invoke(null, capture, font, actor.experienceLevel);
result.add("draws", capture.draws);
} catch (Throwable error) {
var cause = error instanceof InvocationTargetException && error.getCause() != null ? error.getCause() : error;
@@ -14,6 +14,7 @@ import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.BooleanSupplier;
import net.minecraft.SharedConstants;
@@ -65,7 +66,10 @@ 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.BehaviorControl;
import net.minecraft.world.entity.ai.behavior.BlockPosTracker;
import net.minecraft.world.entity.ai.behavior.GateBehavior;
import net.minecraft.world.entity.ai.behavior.ShufflingList;
import net.minecraft.world.entity.ai.behavior.EntityTracker;
import net.minecraft.world.entity.ai.control.LookControl;
import net.minecraft.world.entity.ai.control.MoveControl;
@@ -105,6 +109,8 @@ import net.minecraft.world.phys.Vec3;
public final class VanillaMobAiOracle {
static final List<Scenario> SCENARIOS = new ArrayList<>();
static PrintWriter out;
/** The temporary world directory, deleted before the oracle halts. */
static Path UNIVERSE;
static final List<String> SOUNDS = new ArrayList<>();
/** Draws of a traced mob random: the caller frames of each draw (AI_TRACE=scenario:from-to). */
@@ -208,7 +214,10 @@ public final class VanillaMobAiOracle {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
Util.startTimerHackThread();
Path universe = Files.createTempDirectory("horizon-mob-ai");
// The harness passes an empty world directory under its build directory.
Path universe = args.length > 2 ? Path.of(args[2]) : Files.createTempDirectory("horizon-mob-ai");
Files.createDirectories(universe);
UNIVERSE = universe;
LevelStorageSource.LevelStorageAccess access = LevelStorageSource.createDefault(universe).createAccess("aiworld");
PackRepository packs = ServerPacksSource.createPackRepository(access);
MinecraftServer.spin(thread -> Server.create(thread, access, packs));
@@ -344,7 +353,12 @@ public final class VanillaMobAiOracle {
void step(BooleanSupplier haveTime) throws Exception {
if (scenario >= SCENARIOS.size()) {
out.close();
// Nothing to save: skip the shutdown.
// Nothing to save: skip the shutdown, but leave no world behind.
try (var paths = Files.walk(UNIVERSE)) {
paths.sorted(java.util.Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
} catch (Exception e) {
// best effort
}
Runtime.getRuntime().halt(0);
return;
}
@@ -420,14 +434,23 @@ public final class VanillaMobAiOracle {
Connection connection = new Connection(PacketFlow.SERVERBOUND);
new EmbeddedChannel(connection);
this.getPlayerList().placeNewPlayer(connection, player, cookie);
// A client that has finished loading: otherwise the player stays invulnerable
// until 60 of the server ticks between scenarios have passed, so whether mobs can
// hurt it would depend on the scenario order.
method(player.connection.getClass(), "markClientLoaded").invoke(player.connection);
}
player.setGameMode(s.creative ? GameType.CREATIVE : GameType.SURVIVAL);
player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F);
// The player is never ticked during a scenario: give it the water state of
// where it stands (isInWater), not the previous scenario's.
method(Entity.class, "updateFluidInteraction").invoke(player);
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<>();
List<Brain<?>> brains = new ArrayList<>();
List<Long> seeds = new ArrayList<>();
int id = 100000;
for (MobSpec spec : s.mobs) {
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(net.minecraft.resources.Identifier.parse(spec.type));
@@ -452,7 +475,10 @@ public final class VanillaMobAiOracle {
@SuppressWarnings("unchecked")
Map<Object, Sensor<?>> sensors = (Map<Object, Sensor<?>>) get(brain, "sensors");
for (Sensor<?> sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom());
seedGates(brain, spec.seed);
mobs.add(mob);
brains.add(brain);
seeds.add(spec.seed);
}
level.getRandom().setSeed(s.levelSeed);
SOUNDS.clear();
@@ -467,6 +493,8 @@ public final class VanillaMobAiOracle {
if (player != null && s.player != null) {
player.setHealth(player.getMaxHealth());
player.setInvulnerableTime(0);
// The hurt cooldown (only ServerPlayer.tick counts it down).
field(LivingEntity.class, "damageCooldownTime").setInt(player, 0);
player.hurtTime = 0;
player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F);
player.setDeltaMovement(Vec3.ZERO);
@@ -474,6 +502,13 @@ public final class VanillaMobAiOracle {
TracingRandom.tick = t;
TracingRandom.on = tracing(s) && t >= traceFrom() && t <= traceTo();
SOUNDS.clear();
for (int i = 0; i < mobs.size(); i++) {
// Villager.refreshBrain builds a new brain with new gates: seed those too.
if (mobs.get(i).getBrain() != brains.get(i)) {
brains.set(i, mobs.get(i).getBrain());
seedGates(brains.get(i), seeds.get(i));
}
}
for (Mob mob : mobs) {
if (mob.isRemoved()) continue;
mob.checkDespawn();
@@ -491,6 +526,26 @@ public final class VanillaMobAiOracle {
out.flush();
}
/**
* Every GateBehavior (RunOne and the gates of TradeWithVillager and VillagerMakeLove) shuffles
* its behaviours with its own ShufflingList random, which RandomSource.create() seeds from the
* clock: give each a LegacyRandomSource seeded with the mob's seed so runs are reproducible.
*/
static void seedGates(Brain<?> brain, long seed) throws Exception {
@SuppressWarnings("unchecked")
Map<Integer, Map<?, Set<BehaviorControl<?>>>> byPriority = (Map<Integer, Map<?, Set<BehaviorControl<?>>>>) get(brain, "availableBehaviorsByPriority");
for (Map<?, Set<BehaviorControl<?>>> byActivity : byPriority.values())
for (Set<BehaviorControl<?>> behaviors : byActivity.values())
for (BehaviorControl<?> behavior : behaviors) seedGate(behavior, seed);
}
static void seedGate(Object behavior, long seed) throws Exception {
if (!(behavior instanceof GateBehavior<?>)) return;
ShufflingList<?> list = (ShufflingList<?>) field(GateBehavior.class, "behaviors").get(behavior);
field(ShufflingList.class, "random").set(list, new net.minecraft.world.level.levelgen.LegacyRandomSource(seed));
for (Object child : list) seedGate(child, seed);
}
static String who(Entity e) {
if (e == null) return "none";
if (e instanceof ServerPlayer) return "player";