Run versioned transformers at chunk read and stamp chunks on save

This commit is contained in:
Ruling-0 committed 2026-08-27 19:49:25 -05:00
1 parent 99907e564c
commit 2e0b571550
10 files changed
+272 -86

No files matched your search

@@ -1,8 +1,167 @@
package com.gtnewhorizons.postea.api;
import static net.minecraftforge.common.util.Constants.NBT.TAG_COMPOUND;
import java.util.function.Consumer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import com.gtnewhorizons.postea.compat.Compat;
import com.gtnewhorizons.postea.compat.SubChunkAccess;
import com.gtnewhorizons.postea.utility.NbtItemStacks;
import com.gtnewhorizons.postea.utility.VersionStamps;
/**
* A chunk as handed to {@link IVersionedTransformer#transformChunk}: its block storage and the raw {@code Level}
* tag as read from disk, before tile entities and entities are parsed. Coordinates are chunk-local
* ({@code 0..15}, {@code y 0..255}); block ids and metadata are the world's numeric values at full EndlessIDs
* width. The world is not loaded yet: block access through {@link #world()} is not possible. Changing a block id
* does not recompute lighting or the height map; Postea flags the chunk for a relight when an id changed.
*/
public final class ChunkTransformContext {
public static final int UNSTAMPED = VersionStamps.UNSTAMPED;
private final Chunk chunk;
private final World world;
private final NBTTagCompound levelTag;
private final int storedVersion;
private final int currentVersion;
private final SubChunkAccess[] sections = new SubChunkAccess[16];
private boolean blockIdsChanged;
public ChunkTransformContext(Chunk chunk, World world, NBTTagCompound levelTag, int storedVersion,
int currentVersion) {
this.chunk = chunk;
this.world = world;
this.levelTag = levelTag;
this.storedVersion = storedVersion;
this.currentVersion = currentVersion;
}
public Chunk chunk() {
return chunk;
}
public World world() {
return world;
}
public int chunkX() {
return chunk.xPosition;
}
public int chunkZ() {
return chunk.zPosition;
}
/**
* The chunk's {@code Level} tag. Changes to its {@code TileEntities} and {@code Entities} lists are what the
* game loads.
*/
public NBTTagCompound levelTag() {
return levelTag;
}
public NBTTagList tileEntityTags() {
return levelTag.getTagList("TileEntities", TAG_COMPOUND);
}
public NBTTagList entityTags() {
return levelTag.getTagList("Entities", TAG_COMPOUND);
}
/**
* The version this transformer's key was stamped with when the chunk was saved, or {@link #UNSTAMPED}.
*/
public int storedVersion() {
return storedVersion;
}
public int currentVersion() {
return currentVersion;
}
/**
* The block id at a chunk-local position; 0 for a missing section.
*/
public int getBlockId(int x, int y, int z) {
SubChunkAccess access = section(y >> 4, false);
return access == null ? 0 : access.getBlockId(x, y & 15, z);
}
public int getMetadata(int x, int y, int z) {
SubChunkAccess access = section(y >> 4, false);
return access == null ? 0 : access.getMeta(x, y & 15, z);
}
/**
* Sets the block at a chunk-local position, creating the section when a non-air block goes into a missing one.
*/
public void setBlock(int x, int y, int z, int blockId, int metadata) {
SubChunkAccess access = section(y >> 4, blockId != 0);
if (access == null) return;
if (access.getBlockId(x, y & 15, z) != blockId) blockIdsChanged = true;
access.setBlockId(x, y & 15, z, blockId);
access.setMeta(x, y & 15, z, metadata);
}
/**
* Visits every non-air block of every present section.
*/
public void forEachBlock(BlockVisitor visitor) {
ExtendedBlockStorage[] storage = chunk.getBlockStorageArray();
for (int index = 0; index < storage.length; index++) {
if (storage[index] == null) continue;
SubChunkAccess access = section(index, false);
int base = index << 4;
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
int id = access.getBlockId(x, y, z);
if (id != 0) visitor.visit(x, base + y, z, id, access.getMeta(x, y, z));
}
}
}
}
}
/**
* Visits every serialized item stack held by the chunk's tile entities and entities; see
* {@link NbtItemStacks#forEach}.
*/
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(tileEntityTags(), visitor);
NbtItemStacks.forEach(entityTags(), visitor);
}
/**
* Whether a block id (not only metadata) was rewritten.
*/
public boolean blockIdsChanged() {
return blockIdsChanged;
}
private SubChunkAccess section(int index, boolean create) {
if (index < 0 || index >= sections.length) return null;
if (sections[index] == null) {
ExtendedBlockStorage[] storage = chunk.getBlockStorageArray();
if (storage[index] == null) {
if (!create) return null;
storage[index] = new ExtendedBlockStorage(index << 4, !world.provider.hasNoSky);
}
sections[index] = Compat.getSubChunkAccess(storage[index]);
}
return sections[index];
}
@FunctionalInterface
public interface BlockVisitor {
void visit(int x, int y, int z, int blockId, int metadata);
}
}
@@ -14,23 +14,10 @@ import codechicken.nei.api.API;
public class Compat {
private static Boolean chunkapi = null;
private static Boolean endlessids = null;
private static Boolean neid = null;
private static Boolean nei = null;
public static boolean chunkapiPresent() {
if (chunkapi == null) {
boolean present = false;
try {
present = Launch.classLoader.getClassBytes("com.falsepattern.chunk.internal.core.CoreLoadingPlugin")
!= null;
} catch (Throwable ignored) {}
chunkapi = present;
}
return chunkapi;
}
public static boolean endlessidsPresent() {
if (endlessids == null) {
boolean present = false;
@@ -1,26 +0,0 @@
package com.gtnewhorizons.postea.mixins;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.gtnewhorizon.gtnhmixins.ILateMixinLoader;
import com.gtnewhorizon.gtnhmixins.LateMixin;
@LateMixin
public final class PosteaLateLoadingPlugin implements ILateMixinLoader {
@Override
public String getMixinConfig() {
return "mixins.postea.late.json";
}
@Override
public List<String> getMixins(Set<String> loadedMods) {
final List<String> mixins = new ArrayList<>();
if (loadedMods.contains("chunkapi")) {
mixins.add("MixinDataRegistryImpl");
}
return mixins;
}
}
@@ -12,16 +12,18 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import com.gtnewhorizons.postea.utility.ChunkFixerUtility;
import com.llamalad7.mixinextras.sugar.Local;
@Mixin(value = AnvilChunkLoader.class, priority = 1100)
public abstract class MixinAnvilChunkLoader {
// This hook is compatible with Vanilla/NEID/EIDs
@Inject(method = "readChunkFromNBT", at = @At("RETURN"), require = 1)
private void postea$chunkHook(CallbackInfoReturnable<Chunk> cir, @Local Chunk chunk,
@Local(argsOnly = true) World world, @Local(ordinal = 0, argsOnly = true) NBTTagCompound tag) {
ChunkFixerUtility.onChunkRead(chunk, world, tag);
// Forge-added funnel for sync and async loads; runs after relocation fix-ups and after ChunkAPI's own
// readChunkFromNBT replacement, so one hook covers vanilla, NEID, EndlessIDs, and ChunkAPI.
@Inject(method = "checkedReadChunkFromNBT__Async", at = @At("RETURN"), remap = false, require = 1)
private void postea$chunkHook(CallbackInfoReturnable<Object[]> cir) {
Object[] data = cir.getReturnValue();
if (data == null) return;
Chunk chunk = (Chunk) data[0];
ChunkFixerUtility.onChunkRead(chunk, chunk.worldObj, ((NBTTagCompound) data[1]).getCompoundTag("Level"));
}
@Inject(method = "loadChunk", at = @At("RETURN"))
@@ -1,5 +1,6 @@
package com.gtnewhorizons.postea.mixins.early;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Mixin;
@@ -15,6 +16,13 @@ public class MixinChunk implements IChunkMixin {
@Unique
private long postea_GTNH$posteaID;
// The stamps the chunk was read with; null for a chunk generated this session.
@Unique
private NBTTagCompound postea$versionStamps;
@Unique
private boolean postea$versionedDirty;
@Unique
public long Postea$getPosteaCode() {
return postea_GTNH$posteaID;
@@ -24,4 +32,24 @@ public class MixinChunk implements IChunkMixin {
public void Postea$setPosteaCode(long POSTEA_ID) {
this.postea_GTNH$posteaID = POSTEA_ID;
}
@Unique
public NBTTagCompound Postea$getVersionStamps() {
return postea$versionStamps;
}
@Unique
public void Postea$setVersionStamps(NBTTagCompound stamps) {
this.postea$versionStamps = stamps;
}
@Unique
public boolean Postea$isVersionedDirty() {
return postea$versionedDirty;
}
@Unique
public void Postea$setVersionedDirty(boolean dirty) {
this.postea$versionedDirty = dirty;
}
}
@@ -1,8 +1,18 @@
package com.gtnewhorizons.postea.mixins.interfaces;
import net.minecraft.nbt.NBTTagCompound;
public interface IChunkMixin {
long Postea$getPosteaCode();
void Postea$setPosteaCode(long posteaID);
NBTTagCompound Postea$getVersionStamps();
void Postea$setVersionStamps(NBTTagCompound stamps);
boolean Postea$isVersionedDirty();
void Postea$setVersionedDirty(boolean dirty);
}
@@ -1,24 +0,0 @@
package com.gtnewhorizons.postea.mixins.late;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.falsepattern.chunk.internal.DataRegistryImpl;
import com.gtnewhorizons.postea.utility.ChunkFixerUtility;
@Mixin(value = DataRegistryImpl.class, remap = false)
public abstract class MixinDataRegistryImpl {
@Inject(
method = "readChunkFromNBT(Lnet/minecraft/world/chunk/Chunk;Lnet/minecraft/nbt/NBTTagCompound;)V",
at = @At("RETURN"),
require = 1)
private static void Postea$chunkReadHook(Chunk chunk, NBTTagCompound chunkNBT, CallbackInfo ci) {
ChunkFixerUtility.onChunkRead(chunk, chunk.worldObj, chunkNBT);
}
}
@@ -6,13 +6,20 @@ import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.ReportedException;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import com.gtnewhorizons.postea.Postea;
import com.gtnewhorizons.postea.api.ChunkTransformContext;
import com.gtnewhorizons.postea.api.IVersionedTransformer;
import com.gtnewhorizons.postea.api.TriFunction;
import com.gtnewhorizons.postea.api.VersionedReplacementManager;
import com.gtnewhorizons.postea.compat.Compat;
import com.gtnewhorizons.postea.compat.SubChunkAccess;
import com.gtnewhorizons.postea.mixins.interfaces.IChunkMixin;
@@ -33,10 +40,8 @@ public class ChunkFixerUtility {
public static void onChunkRead(Chunk chunk, World world, NBTTagCompound tag) {
IChunkMixin chunkMixin = (IChunkMixin) chunk;
chunkMixin.Postea$setPosteaCode(-1);
if (tag.hasKey("POSTEA", 4)) {
chunkMixin.Postea$setPosteaCode(tag.getLong("POSTEA"));
}
runVersionedTransformers(chunk, world, tag);
chunkMixin.Postea$setPosteaCode(tag.hasKey("POSTEA", 4) ? tag.getLong("POSTEA") : -1);
// This checks if the chunk has been run with the current POSTEA_UPDATE_CODE and skips it if so.
if (hasChunkBeenUpdated(chunkMixin.Postea$getPosteaCode())) return;
List<ConversionInfo> conversionInfoList = adjustTileEntities(tag.getTagList("TileEntities", 10), world, chunk);
@@ -62,18 +67,72 @@ public class ChunkFixerUtility {
chunkMixin.Postea$setPosteaCode(ChunkFixerUtility.POSTEA_UPDATE_CODE);
}
private static void runVersionedTransformers(Chunk chunk, World world, NBTTagCompound tag) {
IChunkMixin chunkMixin = (IChunkMixin) chunk;
NBTTagCompound stamps = VersionStamps.read(tag);
chunkMixin.Postea$setVersionStamps(stamps == null ? null : (NBTTagCompound) stamps.copy());
boolean blockIdsChanged = false;
for (IVersionedTransformer transformer : VersionedReplacementManager.transformers()) {
int current = transformer.currentVersion();
int stored = VersionStamps.stored(stamps, transformer.key());
if (stored == current) continue;
ChunkTransformContext ctx = new ChunkTransformContext(chunk, world, tag, stored, current);
Postea.LOG.debug(
"{}: chunk {},{} in dimension {} from version {} to {}",
transformer.key(),
chunk.xPosition,
chunk.zPosition,
world.provider.dimensionId,
stored,
current);
try {
transformer.transformChunk(ctx);
} catch (Throwable t) {
throw new ReportedException(
describe(
t,
transformer,
stored,
current,
"Chunk",
chunk.xPosition + "," + chunk.zPosition + " in dimension " + world.provider.dimensionId));
}
chunkMixin.Postea$setVersionedDirty(true);
blockIdsChanged |= ctx.blockIdsChanged();
}
if (!blockIdsChanged) return;
chunk.isLightPopulated = false;
// A section's block count is what decides whether it is saved at all, and writing through SubChunkAccess
// bypasses the bookkeeping ExtendedBlockStorage does in its own setters.
for (ExtendedBlockStorage section : chunk.getBlockStorageArray()) {
if (section != null) section.removeInvalidBlocks();
}
}
static CrashReport describe(Throwable cause, IVersionedTransformer transformer, int stored, int current,
String subjectName, String subject) {
CrashReport report = CrashReport.makeCrashReport(cause, "Running versioned transformer " + transformer.key());
CrashReportCategory category = report.makeCategory("Postea versioned transformer");
category.addCrashSection("Key", transformer.key());
category.addCrashSection("Stored version", stored);
category.addCrashSection("Current version", current);
category.addCrashSection(subjectName, subject);
return report;
}
public static void onChunkLoaded(Chunk chunk) {
if (chunk instanceof IChunkMixin iChunkMixin) {
if (!hasChunkBeenUpdated(iChunkMixin.Postea$getPosteaCode())) {
iChunkMixin.Postea$setPosteaCode(ChunkFixerUtility.POSTEA_UPDATE_CODE);
chunk.setChunkModified();
}
boolean stale = !hasChunkBeenUpdated(iChunkMixin.Postea$getPosteaCode());
if (stale) iChunkMixin.Postea$setPosteaCode(ChunkFixerUtility.POSTEA_UPDATE_CODE);
if (stale || iChunkMixin.Postea$isVersionedDirty()) chunk.setChunkModified();
}
}
public static void onChunkWrite(Chunk chunk, NBTTagCompound tag) {
if (chunk instanceof IChunkMixin iChunkMixin) {
tag.setLong("POSTEA", iChunkMixin.Postea$getPosteaCode());
VersionStamps.write(tag, iChunkMixin.Postea$getVersionStamps(), VersionedReplacementManager.transformers());
iChunkMixin.Postea$setVersionedDirty(false);
}
}