| 1 | package net.minecraft.world.level.chunk.storage;
|
| 2 |
|
| 3 | import com.google.common.collect.Maps;
|
| 4 | import com.mojang.logging.LogUtils;
|
| 5 | import com.mojang.serialization.Codec;
|
| 6 | import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
|
| 7 | import it.unimi.dsi.fastutil.longs.LongSet;
|
| 8 | import it.unimi.dsi.fastutil.shorts.ShortArrayList;
|
| 9 | import it.unimi.dsi.fastutil.shorts.ShortList;
|
| 10 | import java.util.ArrayList;
|
| 11 | import java.util.Arrays;
|
| 12 | import java.util.EnumMap;
|
| 13 | import java.util.EnumSet;
|
| 14 | import java.util.List;
|
| 15 | import java.util.Map;
|
| 16 | import java.util.Objects;
|
| 17 | import java.util.Optional;
|
| 18 | import java.util.Set;
|
| 19 | import java.util.Map.Entry;
|
| 20 | import net.minecraft.Optionull;
|
| 21 | import net.minecraft.core.BlockPos;
|
| 22 | import net.minecraft.core.Holder;
|
| 23 | import net.minecraft.core.Registry;
|
| 24 | import net.minecraft.core.RegistryAccess;
|
| 25 | import net.minecraft.core.SectionPos;
|
| 26 | import net.minecraft.core.registries.BuiltInRegistries;
|
| 27 | import net.minecraft.core.registries.Registries;
|
| 28 | import net.minecraft.nbt.CompoundTag;
|
| 29 | import net.minecraft.nbt.ListTag;
|
| 30 | import net.minecraft.nbt.LongArrayTag;
|
| 31 | import net.minecraft.nbt.NbtException;
|
| 32 | import net.minecraft.nbt.NbtOps;
|
| 33 | import net.minecraft.nbt.NbtUtils;
|
| 34 | import net.minecraft.nbt.ShortTag;
|
| 35 | import net.minecraft.resources.Identifier;
|
| 36 | import net.minecraft.server.level.ServerLevel;
|
| 37 | import net.minecraft.util.ProblemReporter;
|
| 38 | import net.minecraft.world.entity.EntitySpawnReason;
|
| 39 | import net.minecraft.world.entity.EntityType;
|
| 40 | import net.minecraft.world.entity.ai.village.poi.PoiManager;
|
| 41 | import net.minecraft.world.level.ChunkPos;
|
| 42 | import net.minecraft.world.level.LevelHeightAccessor;
|
| 43 | import net.minecraft.world.level.LightLayer;
|
| 44 | import net.minecraft.world.level.biome.Biome;
|
| 45 | import net.minecraft.world.level.block.Block;
|
| 46 | import net.minecraft.world.level.block.entity.BlockEntity;
|
| 47 | import net.minecraft.world.level.block.state.BlockState;
|
| 48 | import net.minecraft.world.level.chunk.ChunkAccess;
|
| 49 | import net.minecraft.world.level.chunk.ChunkSource;
|
| 50 | import net.minecraft.world.level.chunk.DataLayer;
|
| 51 | import net.minecraft.world.level.chunk.ImposterProtoChunk;
|
| 52 | import net.minecraft.world.level.chunk.LevelChunk;
|
| 53 | import net.minecraft.world.level.chunk.LevelChunkSection;
|
| 54 | import net.minecraft.world.level.chunk.PalettedContainer;
|
| 55 | import net.minecraft.world.level.chunk.PalettedContainerFactory;
|
| 56 | import net.minecraft.world.level.chunk.PalettedContainerRO;
|
| 57 | import net.minecraft.world.level.chunk.ProtoChunk;
|
| 58 | import net.minecraft.world.level.chunk.UpgradeData;
|
| 59 | import net.minecraft.world.level.chunk.status.ChunkStatus;
|
| 60 | import net.minecraft.world.level.chunk.status.ChunkType;
|
| 61 | import net.minecraft.world.level.levelgen.BelowZeroRetrogen;
|
| 62 | import net.minecraft.world.level.levelgen.Heightmap;
|
| 63 | import net.minecraft.world.level.levelgen.blending.BlendingData;
|
| 64 | import net.minecraft.world.level.levelgen.structure.Structure;
|
| 65 | import net.minecraft.world.level.levelgen.structure.StructureStart;
|
| 66 | import net.minecraft.world.level.levelgen.structure.pieces.StructurePieceSerializationContext;
|
| 67 | import net.minecraft.world.level.lighting.LevelLightEngine;
|
| 68 | import net.minecraft.world.level.material.Fluid;
|
| 69 | import net.minecraft.world.level.storage.TagValueInput;
|
| 70 | import net.minecraft.world.ticks.LevelChunkTicks;
|
| 71 | import net.minecraft.world.ticks.ProtoChunkTicks;
|
| 72 | import net.minecraft.world.ticks.SavedTick;
|
| 73 | import org.jspecify.annotations.Nullable;
|
| 74 | import org.slf4j.Logger;
|
| 75 |
|
| 76 | public record SerializableChunkData(
|
| 77 | PalettedContainerFactory containerFactory,
|
| 78 | ChunkPos chunkPos,
|
| 79 | int minSectionY,
|
| 80 | long lastUpdateTime,
|
| 81 | long inhabitedTime,
|
| 82 | ChunkStatus chunkStatus,
|
| 83 | BlendingData.@Nullable Packed blendingData,
|
| 84 | @Nullable BelowZeroRetrogen belowZeroRetrogen,
|
| 85 | UpgradeData upgradeData,
|
| 86 | Map<Heightmap.Types, long[]> heightmaps,
|
| 87 | ChunkAccess.PackedTicks packedTicks,
|
| 88 | @Nullable ShortList[] postProcessingSections,
|
| 89 | boolean lightCorrect,
|
| 90 | List<SerializableChunkData.SectionData> sectionData,
|
| 91 | List<CompoundTag> entities,
|
| 92 | List<CompoundTag> blockEntities,
|
| 93 | CompoundTag structureData
|
| 94 | ) {
|
| 95 | private static final Codec<List<SavedTick<Block>>> BLOCK_TICKS_CODEC = SavedTick.codec(BuiltInRegistries.BLOCK.byNameCodec()).listOf();
|
| 96 | private static final Codec<List<SavedTick<Fluid>>> FLUID_TICKS_CODEC = SavedTick.codec(BuiltInRegistries.FLUID.byNameCodec()).listOf();
|
| 97 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 98 | private static final String TAG_UPGRADE_DATA = "UpgradeData";
|
| 99 | private static final String BLOCK_TICKS_TAG = "block_ticks";
|
| 100 | private static final String FLUID_TICKS_TAG = "fluid_ticks";
|
| 101 | public static final String X_POS_TAG = "xPos";
|
| 102 | public static final String Z_POS_TAG = "zPos";
|
| 103 | public static final String HEIGHTMAPS_TAG = "Heightmaps";
|
| 104 | public static final String IS_LIGHT_ON_TAG = "isLightOn";
|
| 105 | public static final String SECTIONS_TAG = "sections";
|
| 106 | public static final String BLOCK_LIGHT_TAG = "BlockLight";
|
| 107 | public static final String SKY_LIGHT_TAG = "SkyLight";
|
| 108 |
|
| 109 | public static SerializableChunkData parse(final LevelHeightAccessor levelHeight, final PalettedContainerFactory containerFactory, final CompoundTag chunkData) {
|
| 110 | if (chunkData.getString("Status").isEmpty()) {
|
| 111 | return null;
|
| 112 | }
|
| 113 |
|
| 114 | ChunkPos chunkPos = new ChunkPos(chunkData.getIntOr("xPos", 0), chunkData.getIntOr("zPos", 0));
|
| 115 | long lastUpdateTime = chunkData.getLongOr("LastUpdate", 0L);
|
| 116 | long inhabitedTime = chunkData.getLongOr("InhabitedTime", 0L);
|
| 117 | ChunkStatus status = chunkData.read("Status", ChunkStatus.CODEC).orElse(ChunkStatus.EMPTY);
|
| 118 | UpgradeData upgradeData = chunkData.getCompound("UpgradeData").map(tag -> new UpgradeData(tag, levelHeight)).orElse(UpgradeData.EMPTY);
|
| 119 | boolean lightCorrect = chunkData.getBooleanOr("isLightOn", false);
|
| 120 | BlendingData.Packed blendingData = chunkData.read("blending_data", BlendingData.Packed.CODEC).orElse(null);
|
| 121 | BelowZeroRetrogen belowZeroRetrogen = chunkData.read("below_zero_retrogen", BelowZeroRetrogen.CODEC).orElse(null);
|
| 122 | Map<Heightmap.Types, long[]> heightmaps = new EnumMap<>(Heightmap.Types.class);
|
| 123 | chunkData.getCompound("Heightmaps").ifPresent(heightmapsTag -> {
|
| 124 | for (Heightmap.Types type : Heightmap.Types.values()) {
|
| 125 | heightmapsTag.getLongArray(type.getSerializationKey()).ifPresent(longs -> heightmaps.put(type, longs));
|
| 126 | }
|
| 127 | });
|
| 128 | List<SavedTick<Block>> blockTicks = SavedTick.filterTickListForChunk(chunkData.read("block_ticks", BLOCK_TICKS_CODEC).orElse(List.of()), chunkPos);
|
| 129 | List<SavedTick<Fluid>> fluidTicks = SavedTick.filterTickListForChunk(chunkData.read("fluid_ticks", FLUID_TICKS_CODEC).orElse(List.of()), chunkPos);
|
| 130 | ChunkAccess.PackedTicks packedTicks = new ChunkAccess.PackedTicks(blockTicks, fluidTicks);
|
| 131 | ListTag postProcessTags = chunkData.getListOrEmpty("PostProcessing");
|
| 132 | ShortList[] postProcessingSections = new ShortList[postProcessTags.size()];
|
| 133 |
|
| 134 | for (int sectionIndex = 0; sectionIndex < postProcessTags.size(); sectionIndex++) {
|
| 135 | ListTag offsetsTag = postProcessTags.getList(sectionIndex).orElse(null);
|
| 136 | if (offsetsTag != null && !offsetsTag.isEmpty()) {
|
| 137 | ShortList packedOffsets = new ShortArrayList(offsetsTag.size());
|
| 138 |
|
| 139 | for (int i = 0; i < offsetsTag.size(); i++) {
|
| 140 | packedOffsets.add(offsetsTag.getShortOr(i, (short)0));
|
| 141 | }
|
| 142 |
|
| 143 | postProcessingSections[sectionIndex] = packedOffsets;
|
| 144 | }
|
| 145 | }
|
| 146 |
|
| 147 | List<CompoundTag> entities = chunkData.getList("entities").stream().flatMap(ListTag::compoundStream).toList();
|
| 148 | List<CompoundTag> blockEntities = chunkData.getList("block_entities").stream().flatMap(ListTag::compoundStream).toList();
|
| 149 | CompoundTag structureData = chunkData.getCompoundOrEmpty("structures");
|
| 150 | ListTag sectionTags = chunkData.getListOrEmpty("sections");
|
| 151 | List<SerializableChunkData.SectionData> sectionData = new ArrayList<>(sectionTags.size());
|
| 152 | Codec<PalettedContainerRO<Holder<Biome>>> biomesCodec = containerFactory.biomeContainerCodec();
|
| 153 | Codec<PalettedContainer<BlockState>> blockStatesCodec = containerFactory.blockStatesContainerCodec();
|
| 154 |
|
| 155 | for (int i = 0; i < sectionTags.size(); i++) {
|
| 156 | Optional<CompoundTag> maybeSectionTag = sectionTags.getCompound(i);
|
| 157 | if (!maybeSectionTag.isEmpty()) {
|
| 158 | CompoundTag sectionTag = maybeSectionTag.get();
|
| 159 | int y = sectionTag.getByteOr("Y", (byte)0);
|
| 160 | LevelChunkSection section;
|
| 161 | if (y >= levelHeight.getMinSectionY() && y <= levelHeight.getMaxSectionY()) {
|
| 162 | PalettedContainer<BlockState> blocks = sectionTag.getCompound("block_states")
|
| 163 | .map(
|
| 164 | container -> blockStatesCodec.parse(NbtOps.INSTANCE, container)
|
| 165 | .promotePartial(msg -> logErrors(chunkPos, y, msg))
|
| 166 | .getOrThrow(SerializableChunkData.ChunkReadException::new)
|
| 167 | )
|
| 168 | .orElseGet(containerFactory::createForBlockStates);
|
| 169 | PalettedContainerRO<Holder<Biome>> biomes = sectionTag.getCompound("biomes")
|
| 170 | .map(
|
| 171 | container -> biomesCodec.parse(NbtOps.INSTANCE, container)
|
| 172 | .promotePartial(msg -> logErrors(chunkPos, y, msg))
|
| 173 | .getOrThrow(SerializableChunkData.ChunkReadException::new)
|
| 174 | )
|
| 175 | .orElseGet(containerFactory::createForBiomes);
|
| 176 | section = new LevelChunkSection(blocks, biomes);
|
| 177 | } else {
|
| 178 | section = null;
|
| 179 | }
|
| 180 |
|
| 181 | DataLayer blockLight = sectionTag.getByteArray("BlockLight").map(DataLayer::new).orElse(null);
|
| 182 | DataLayer skyLight = sectionTag.getByteArray("SkyLight").map(DataLayer::new).orElse(null);
|
| 183 | sectionData.add(new SerializableChunkData.SectionData(y, section, blockLight, skyLight));
|
| 184 | }
|
| 185 | }
|
| 186 |
|
| 187 | return new SerializableChunkData(
|
| 188 | containerFactory,
|
| 189 | chunkPos,
|
| 190 | levelHeight.getMinSectionY(),
|
| 191 | lastUpdateTime,
|
| 192 | inhabitedTime,
|
| 193 | status,
|
| 194 | blendingData,
|
| 195 | belowZeroRetrogen,
|
| 196 | upgradeData,
|
| 197 | heightmaps,
|
| 198 | packedTicks,
|
| 199 | postProcessingSections,
|
| 200 | lightCorrect,
|
| 201 | sectionData,
|
| 202 | entities,
|
| 203 | blockEntities,
|
| 204 | structureData
|
| 205 | );
|
| 206 | }
|
| 207 |
|
| 208 | public ProtoChunk read(final ServerLevel level, final PoiManager poiManager, final RegionStorageInfo regionInfo, final ChunkPos pos) {
|
| 209 | if (!Objects.equals(pos, this.chunkPos)) {
|
| 210 | LOGGER.error("Chunk file at {} is in the wrong location; relocating. (Expected {}, got {})", pos, pos, this.chunkPos);
|
| 211 | level.getServer().reportMisplacedChunk(this.chunkPos, pos, regionInfo);
|
| 212 | }
|
| 213 |
|
| 214 | int sectionCount = level.getSectionsCount();
|
| 215 | LevelChunkSection[] sections = new LevelChunkSection[sectionCount];
|
| 216 | boolean skyLight = level.dimensionType().hasSkyLight();
|
| 217 | ChunkSource chunkSource = level.getChunkSource();
|
| 218 | LevelLightEngine lightEngine = chunkSource.getLightEngine();
|
| 219 | PalettedContainerFactory containerFactory = level.palettedContainerFactory();
|
| 220 | boolean loadedAnyLight = false;
|
| 221 |
|
| 222 | for (SerializableChunkData.SectionData section : this.sectionData) {
|
| 223 | SectionPos sectionPos = SectionPos.of(pos, section.y);
|
| 224 | if (section.chunkSection != null) {
|
| 225 | sections[level.getSectionIndexFromSectionY(section.y)] = section.chunkSection;
|
| 226 | poiManager.checkConsistencyWithBlocks(sectionPos, section.chunkSection);
|
| 227 | }
|
| 228 |
|
| 229 | boolean hasBlockLight = section.blockLight != null;
|
| 230 | boolean hasSkyLight = skyLight && section.skyLight != null;
|
| 231 | if (hasBlockLight || hasSkyLight) {
|
| 232 | if (!loadedAnyLight) {
|
| 233 | lightEngine.retainData(pos, true);
|
| 234 | loadedAnyLight = true;
|
| 235 | }
|
| 236 |
|
| 237 | if (hasBlockLight) {
|
| 238 | lightEngine.queueSectionData(LightLayer.BLOCK, sectionPos, section.blockLight);
|
| 239 | }
|
| 240 |
|
| 241 | if (hasSkyLight) {
|
| 242 | lightEngine.queueSectionData(LightLayer.SKY, sectionPos, section.skyLight);
|
| 243 | }
|
| 244 | }
|
| 245 | }
|
| 246 |
|
| 247 | ChunkType chunkType = this.chunkStatus.getChunkType();
|
| 248 | ChunkAccess chunk;
|
| 249 | if (chunkType == ChunkType.LEVELCHUNK) {
|
| 250 | LevelChunkTicks<Block> blockTicks = new LevelChunkTicks<>(this.packedTicks.blocks());
|
| 251 | LevelChunkTicks<Fluid> fluidTicks = new LevelChunkTicks<>(this.packedTicks.fluids());
|
| 252 | chunk = new LevelChunk(
|
| 253 | level.getLevel(),
|
| 254 | pos,
|
| 255 | this.upgradeData,
|
| 256 | blockTicks,
|
| 257 | fluidTicks,
|
| 258 | this.inhabitedTime,
|
| 259 | sections,
|
| 260 | postLoadChunk(level, this.entities, this.blockEntities),
|
| 261 | BlendingData.unpack(this.blendingData)
|
| 262 | );
|
| 263 | } else {
|
| 264 | ProtoChunkTicks<Block> blockTicks = ProtoChunkTicks.load(this.packedTicks.blocks());
|
| 265 | ProtoChunkTicks<Fluid> fluidTicks = ProtoChunkTicks.load(this.packedTicks.fluids());
|
| 266 | ProtoChunk protoChunk = new ProtoChunk(
|
| 267 | pos, this.upgradeData, sections, blockTicks, fluidTicks, level, containerFactory, BlendingData.unpack(this.blendingData)
|
| 268 | );
|
| 269 | chunk = protoChunk;
|
| 270 | chunk.setInhabitedTime(this.inhabitedTime);
|
| 271 | if (this.belowZeroRetrogen != null) {
|
| 272 | protoChunk.setBelowZeroRetrogen(this.belowZeroRetrogen);
|
| 273 | }
|
| 274 |
|
| 275 | protoChunk.setPersistedStatus(this.chunkStatus);
|
| 276 | if (this.chunkStatus.isOrAfter(ChunkStatus.INITIALIZE_LIGHT)) {
|
| 277 | protoChunk.setLightEngine(lightEngine);
|
| 278 | }
|
| 279 | }
|
| 280 |
|
| 281 | chunk.setLightCorrect(this.lightCorrect);
|
| 282 | Set<Heightmap.Types> toPrime = EnumSet.copyOf(chunk.getPersistedStatus().heightmapsAfter());
|
| 283 |
|
| 284 | for (Entry<Heightmap.Types, long[]> entry : this.heightmaps.entrySet()) {
|
| 285 | chunk.setHeightmap(entry.getKey(), entry.getValue());
|
| 286 | toPrime.remove(entry.getKey());
|
| 287 | }
|
| 288 |
|
| 289 | Heightmap.primeHeightmaps(chunk, toPrime);
|
| 290 | chunk.setAllStarts(unpackStructureStart(StructurePieceSerializationContext.fromLevel(level), this.structureData, level.getSeed()));
|
| 291 | chunk.setAllReferences(unpackStructureReferences(level.registryAccess(), pos, this.structureData));
|
| 292 |
|
| 293 | for (int sectionIndex = 0; sectionIndex < this.postProcessingSections.length; sectionIndex++) {
|
| 294 | ShortList postProcessingSection = this.postProcessingSections[sectionIndex];
|
| 295 | if (postProcessingSection != null) {
|
| 296 | chunk.addPackedPostProcess(postProcessingSection, sectionIndex);
|
| 297 | }
|
| 298 | }
|
| 299 |
|
| 300 | if (chunkType == ChunkType.LEVELCHUNK) {
|
| 301 | return new ImposterProtoChunk((LevelChunk)chunk, false);
|
| 302 | }
|
| 303 |
|
| 304 | ProtoChunk protoChunk = (ProtoChunk)chunk;
|
| 305 |
|
| 306 | for (CompoundTag entity : this.entities) {
|
| 307 | protoChunk.addEntity(entity);
|
| 308 | }
|
| 309 |
|
| 310 | for (CompoundTag blockEntity : this.blockEntities) {
|
| 311 | protoChunk.setBlockEntityNbt(blockEntity);
|
| 312 | }
|
| 313 |
|
| 314 | return protoChunk;
|
| 315 | }
|
| 316 |
|
| 317 | private static void logErrors(final ChunkPos pos, final int sectionY, final String message) {
|
| 318 | LOGGER.error("Recoverable errors when loading section [{}, {}, {}]: {}", pos.x(), sectionY, pos.z(), message);
|
| 319 | }
|
| 320 |
|
| 321 | public static SerializableChunkData copyOf(final ServerLevel level, final ChunkAccess chunk) {
|
| 322 | if (!chunk.canBeSerialized()) {
|
| 323 | throw new IllegalArgumentException("Chunk can't be serialized: " + chunk);
|
| 324 | }
|
| 325 |
|
| 326 | ChunkPos pos = chunk.getPos();
|
| 327 | List<SerializableChunkData.SectionData> sectionData = new ArrayList<>();
|
| 328 | LevelChunkSection[] chunkSections = chunk.getSections();
|
| 329 | LevelLightEngine lightEngine = level.getChunkSource().getLightEngine();
|
| 330 |
|
| 331 | for (int sectionY = lightEngine.getMinLightSection(); sectionY < lightEngine.getMaxLightSection(); sectionY++) {
|
| 332 | int sectionIndex = chunk.getSectionIndexFromSectionY(sectionY);
|
| 333 | boolean hasSection = sectionIndex >= 0 && sectionIndex < chunkSections.length;
|
| 334 | DataLayer sourceBlockLight = lightEngine.getLayerListener(LightLayer.BLOCK).getDataLayerData(SectionPos.of(pos, sectionY));
|
| 335 | DataLayer sourceSkyLight = lightEngine.getLayerListener(LightLayer.SKY).getDataLayerData(SectionPos.of(pos, sectionY));
|
| 336 | DataLayer blockLight = sourceBlockLight != null && !sourceBlockLight.isEmpty() ? sourceBlockLight.copy() : null;
|
| 337 | DataLayer skyLight = sourceSkyLight != null && !sourceSkyLight.isEmpty() ? sourceSkyLight.copy() : null;
|
| 338 | if (hasSection || blockLight != null || skyLight != null) {
|
| 339 | LevelChunkSection section = hasSection ? chunkSections[sectionIndex].copy() : null;
|
| 340 | sectionData.add(new SerializableChunkData.SectionData(sectionY, section, blockLight, skyLight));
|
| 341 | }
|
| 342 | }
|
| 343 |
|
| 344 | List<CompoundTag> blockEntities = new ArrayList<>(chunk.getBlockEntitiesPos().size());
|
| 345 |
|
| 346 | for (BlockPos blockPos : chunk.getBlockEntitiesPos()) {
|
| 347 | CompoundTag blockEntityTag = chunk.getBlockEntityNbtForSaving(blockPos, level.registryAccess());
|
| 348 | if (blockEntityTag != null) {
|
| 349 | blockEntities.add(blockEntityTag);
|
| 350 | }
|
| 351 | }
|
| 352 |
|
| 353 | List<CompoundTag> entities = new ArrayList<>();
|
| 354 | if (chunk.getPersistedStatus().getChunkType() == ChunkType.PROTOCHUNK) {
|
| 355 | ProtoChunk protoChunk = (ProtoChunk)chunk;
|
| 356 | entities.addAll(protoChunk.getEntities());
|
| 357 | }
|
| 358 |
|
| 359 | Map<Heightmap.Types, long[]> heightmaps = new EnumMap<>(Heightmap.Types.class);
|
| 360 |
|
| 361 | for (Entry<Heightmap.Types, Heightmap> entry : chunk.getHeightmaps()) {
|
| 362 | long[] data = entry.getValue().getRawData();
|
| 363 | heightmaps.put(entry.getKey(), (long[])data.clone());
|
| 364 | }
|
| 365 |
|
| 366 | ChunkAccess.PackedTicks ticksForSerialization = chunk.getTicksForSerialization(level.getGameTime());
|
| 367 | ShortList[] postProcessingSections = Arrays.stream(chunk.getPostProcessing())
|
| 368 | .map(shorts -> shorts != null && !shorts.isEmpty() ? new ShortArrayList(shorts) : null)
|
| 369 | .toArray(ShortList[]::new);
|
| 370 | CompoundTag structureData = packStructureData(StructurePieceSerializationContext.fromLevel(level), pos, chunk.getAllStarts(), chunk.getAllReferences());
|
| 371 | return new SerializableChunkData(
|
| 372 | level.palettedContainerFactory(),
|
| 373 | pos,
|
| 374 | chunk.getMinSectionY(),
|
| 375 | level.getGameTime(),
|
| 376 | chunk.getInhabitedTime(),
|
| 377 | chunk.getPersistedStatus(),
|
| 378 | Optionull.map(chunk.getBlendingData(), BlendingData::pack),
|
| 379 | chunk.getBelowZeroRetrogen(),
|
| 380 | chunk.getUpgradeData().copy(),
|
| 381 | heightmaps,
|
| 382 | ticksForSerialization,
|
| 383 | postProcessingSections,
|
| 384 | chunk.isLightCorrect(),
|
| 385 | sectionData,
|
| 386 | entities,
|
| 387 | blockEntities,
|
| 388 | structureData
|
| 389 | );
|
| 390 | }
|
| 391 |
|
| 392 | public CompoundTag write() {
|
| 393 | CompoundTag tag = NbtUtils.addCurrentDataVersion(new CompoundTag());
|
| 394 | tag.putInt("xPos", this.chunkPos.x());
|
| 395 | tag.putInt("yPos", this.minSectionY);
|
| 396 | tag.putInt("zPos", this.chunkPos.z());
|
| 397 | tag.putLong("LastUpdate", this.lastUpdateTime);
|
| 398 | tag.putLong("InhabitedTime", this.inhabitedTime);
|
| 399 | tag.putString("Status", BuiltInRegistries.CHUNK_STATUS.getKey(this.chunkStatus).toString());
|
| 400 | tag.storeNullable("blending_data", BlendingData.Packed.CODEC, this.blendingData);
|
| 401 | tag.storeNullable("below_zero_retrogen", BelowZeroRetrogen.CODEC, this.belowZeroRetrogen);
|
| 402 | if (!this.upgradeData.isEmpty()) {
|
| 403 | tag.put("UpgradeData", this.upgradeData.write());
|
| 404 | }
|
| 405 |
|
| 406 | ListTag sectionTags = new ListTag();
|
| 407 | Codec<PalettedContainer<BlockState>> blockStatesCodec = this.containerFactory.blockStatesContainerCodec();
|
| 408 | Codec<PalettedContainerRO<Holder<Biome>>> biomeCodec = this.containerFactory.biomeContainerCodec();
|
| 409 |
|
| 410 | for (SerializableChunkData.SectionData section : this.sectionData) {
|
| 411 | CompoundTag sectionTag = new CompoundTag();
|
| 412 | LevelChunkSection chunkSection = section.chunkSection;
|
| 413 | if (chunkSection != null) {
|
| 414 | sectionTag.store("block_states", blockStatesCodec, chunkSection.getStates());
|
| 415 | sectionTag.store("biomes", biomeCodec, chunkSection.getBiomes());
|
| 416 | }
|
| 417 |
|
| 418 | if (section.blockLight != null) {
|
| 419 | sectionTag.putByteArray("BlockLight", section.blockLight.getData());
|
| 420 | }
|
| 421 |
|
| 422 | if (section.skyLight != null) {
|
| 423 | sectionTag.putByteArray("SkyLight", section.skyLight.getData());
|
| 424 | }
|
| 425 |
|
| 426 | if (!sectionTag.isEmpty()) {
|
| 427 | sectionTag.putByte("Y", (byte)section.y);
|
| 428 | sectionTags.add(sectionTag);
|
| 429 | }
|
| 430 | }
|
| 431 |
|
| 432 | tag.put("sections", sectionTags);
|
| 433 | if (this.lightCorrect) {
|
| 434 | tag.putBoolean("isLightOn", true);
|
| 435 | }
|
| 436 |
|
| 437 | ListTag blockEntityTags = new ListTag();
|
| 438 | blockEntityTags.addAll(this.blockEntities);
|
| 439 | tag.put("block_entities", blockEntityTags);
|
| 440 | if (this.chunkStatus.getChunkType() == ChunkType.PROTOCHUNK) {
|
| 441 | ListTag entityTags = new ListTag();
|
| 442 | entityTags.addAll(this.entities);
|
| 443 | tag.put("entities", entityTags);
|
| 444 | }
|
| 445 |
|
| 446 | saveTicks(tag, this.packedTicks);
|
| 447 | tag.put("PostProcessing", packOffsets(this.postProcessingSections));
|
| 448 | CompoundTag heightmapsTag = new CompoundTag();
|
| 449 | this.heightmaps.forEach((type, data) -> heightmapsTag.put(type.getSerializationKey(), new LongArrayTag(data)));
|
| 450 | tag.put("Heightmaps", heightmapsTag);
|
| 451 | tag.put("structures", this.structureData);
|
| 452 | return tag;
|
| 453 | }
|
| 454 |
|
| 455 | private static void saveTicks(final CompoundTag levelData, final ChunkAccess.PackedTicks ticksForSerialization) {
|
| 456 | levelData.store("block_ticks", BLOCK_TICKS_CODEC, ticksForSerialization.blocks());
|
| 457 | levelData.store("fluid_ticks", FLUID_TICKS_CODEC, ticksForSerialization.fluids());
|
| 458 | }
|
| 459 |
|
| 460 | public static ChunkStatus getChunkStatusFromTag(final @Nullable CompoundTag tag) {
|
| 461 | return tag != null ? tag.read("Status", ChunkStatus.CODEC).orElse(ChunkStatus.EMPTY) : ChunkStatus.EMPTY;
|
| 462 | }
|
| 463 |
|
| 464 | private static LevelChunk.@Nullable PostLoadProcessor postLoadChunk(
|
| 465 | final ServerLevel level, final List<CompoundTag> entities, final List<CompoundTag> blockEntities
|
| 466 | ) {
|
| 467 | return entities.isEmpty() && blockEntities.isEmpty()
|
| 468 | ? null
|
| 469 | : levelChunk -> {
|
| 470 | if (!entities.isEmpty()) {
|
| 471 | try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(levelChunk.problemPath(), LOGGER)) {
|
| 472 | level.addLegacyChunkEntities(
|
| 473 | EntityType.loadEntitiesRecursive(TagValueInput.create(reporter, level.registryAccess(), entities), level, EntitySpawnReason.LOAD)
|
| 474 | );
|
| 475 | }
|
| 476 | }
|
| 477 |
|
| 478 | for (CompoundTag entityTag : blockEntities) {
|
| 479 | boolean keepPacked = entityTag.getBooleanOr("keepPacked", false);
|
| 480 | if (keepPacked) {
|
| 481 | levelChunk.setBlockEntityNbt(entityTag);
|
| 482 | } else {
|
| 483 | BlockPos pos = BlockEntity.getPosFromTag(levelChunk.getPos(), entityTag);
|
| 484 | BlockEntity blockEntity = BlockEntity.loadStatic(pos, levelChunk.getBlockState(pos), entityTag, level.registryAccess());
|
| 485 | if (blockEntity != null) {
|
| 486 | levelChunk.setBlockEntity(blockEntity);
|
| 487 | }
|
| 488 | }
|
| 489 | }
|
| 490 | };
|
| 491 | }
|
| 492 |
|
| 493 | private static CompoundTag packStructureData(
|
| 494 | final StructurePieceSerializationContext context, final ChunkPos pos, final Map<Structure, StructureStart> starts, final Map<Structure, LongSet> references
|
| 495 | ) {
|
| 496 | CompoundTag outTag = new CompoundTag();
|
| 497 | CompoundTag startsTag = new CompoundTag();
|
| 498 | Registry<Structure> structuresRegistry = context.registryAccess().lookupOrThrow(Registries.STRUCTURE);
|
| 499 |
|
| 500 | for (Entry<Structure, StructureStart> entry : starts.entrySet()) {
|
| 501 | Identifier key = structuresRegistry.getKey(entry.getKey());
|
| 502 | startsTag.put(key.toString(), entry.getValue().createTag(context, pos));
|
| 503 | }
|
| 504 |
|
| 505 | outTag.put("starts", startsTag);
|
| 506 | CompoundTag referencesTag = new CompoundTag();
|
| 507 |
|
| 508 | for (Entry<Structure, LongSet> entry : references.entrySet()) {
|
| 509 | if (!entry.getValue().isEmpty()) {
|
| 510 | Identifier key = structuresRegistry.getKey(entry.getKey());
|
| 511 | referencesTag.putLongArray(key.toString(), entry.getValue().toLongArray());
|
| 512 | }
|
| 513 | }
|
| 514 |
|
| 515 | outTag.put("References", referencesTag);
|
| 516 | return outTag;
|
| 517 | }
|
| 518 |
|
| 519 | private static Map<Structure, StructureStart> unpackStructureStart(final StructurePieceSerializationContext context, final CompoundTag tag, final long seed) {
|
| 520 | Map<Structure, StructureStart> outmap = Maps.newHashMap();
|
| 521 | Registry<Structure> structuresRegistry = context.registryAccess().lookupOrThrow(Registries.STRUCTURE);
|
| 522 | CompoundTag startsTag = tag.getCompoundOrEmpty("starts");
|
| 523 |
|
| 524 | for (String key : startsTag.keySet()) {
|
| 525 | Identifier id = Identifier.tryParse(key);
|
| 526 | Structure startFeature = structuresRegistry.getValue(id);
|
| 527 | if (startFeature == null) {
|
| 528 | LOGGER.error("Unknown structure start: {}", id);
|
| 529 | } else {
|
| 530 | StructureStart start = StructureStart.loadStaticStart(context, startsTag.getCompoundOrEmpty(key), seed);
|
| 531 | if (start != null) {
|
| 532 | outmap.put(startFeature, start);
|
| 533 | }
|
| 534 | }
|
| 535 | }
|
| 536 |
|
| 537 | return outmap;
|
| 538 | }
|
| 539 |
|
| 540 | private static Map<Structure, LongSet> unpackStructureReferences(final RegistryAccess registryAccess, final ChunkPos pos, final CompoundTag tag) {
|
| 541 | Map<Structure, LongSet> outmap = Maps.newHashMap();
|
| 542 | Registry<Structure> structuresRegistry = registryAccess.lookupOrThrow(Registries.STRUCTURE);
|
| 543 | CompoundTag referencesTag = tag.getCompoundOrEmpty("References");
|
| 544 | referencesTag.forEach((key, entry) -> {
|
| 545 | Identifier structureId = Identifier.tryParse(key);
|
| 546 | Structure structureType = structuresRegistry.getValue(structureId);
|
| 547 | if (structureType == null) {
|
| 548 | LOGGER.warn("Found reference to unknown structure '{}' in chunk {}, discarding", structureId, pos);
|
| 549 | } else {
|
| 550 | Optional<long[]> longArray = entry.asLongArray();
|
| 551 | if (!longArray.isEmpty()) {
|
| 552 | outmap.put(structureType, new LongOpenHashSet(Arrays.stream(longArray.get()).filter(chunkLongPos -> {
|
| 553 | ChunkPos refPos = ChunkPos.unpack(chunkLongPos);
|
| 554 | if (refPos.getChessboardDistance(pos) > 8) {
|
| 555 | LOGGER.warn("Found invalid structure reference [ {} @ {} ] for chunk {}.", structureId, refPos, pos);
|
| 556 | return false;
|
| 557 | } else {
|
| 558 | return true;
|
| 559 | }
|
| 560 | }).toArray()));
|
| 561 | }
|
| 562 | }
|
| 563 | });
|
| 564 | return outmap;
|
| 565 | }
|
| 566 |
|
| 567 | private static ListTag packOffsets(final @Nullable ShortList[] sections) {
|
| 568 | ListTag listTag = new ListTag();
|
| 569 |
|
| 570 | for (ShortList offsetList : sections) {
|
| 571 | ListTag offsetsTag = new ListTag();
|
| 572 | if (offsetList != null) {
|
| 573 | for (int i = 0; i < offsetList.size(); i++) {
|
| 574 | offsetsTag.add(ShortTag.valueOf(offsetList.getShort(i)));
|
| 575 | }
|
| 576 | }
|
| 577 |
|
| 578 | listTag.add(offsetsTag);
|
| 579 | }
|
| 580 |
|
| 581 | return listTag;
|
| 582 | }
|
| 583 |
|
| 584 | public static class ChunkReadException extends NbtException {
|
| 585 | public ChunkReadException(final String message) {
|
| 586 | super(message);
|
| 587 | }
|
| 588 | }
|
| 589 |
|
| 590 | public record SectionData(int y, @Nullable LevelChunkSection chunkSection, @Nullable DataLayer blockLight, @Nullable DataLayer skyLight) {
|
| 591 | }
|
| 592 | }
|
| 593 |
|