| 1 | package net.minecraft.world.level.chunk;
|
| 2 |
|
| 3 | import com.google.common.annotations.VisibleForTesting;
|
| 4 | import com.mojang.serialization.Codec;
|
| 5 | import com.mojang.serialization.DataResult;
|
| 6 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 7 | import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
|
| 8 | import it.unimi.dsi.fastutil.ints.IntArraySet;
|
| 9 | import it.unimi.dsi.fastutil.ints.IntSet;
|
| 10 | import java.util.Arrays;
|
| 11 | import java.util.List;
|
| 12 | import java.util.Optional;
|
| 13 | import java.util.function.Consumer;
|
| 14 | import java.util.function.Predicate;
|
| 15 | import java.util.stream.LongStream;
|
| 16 | import net.minecraft.core.IdMap;
|
| 17 | import net.minecraft.network.FriendlyByteBuf;
|
| 18 | import net.minecraft.util.BitStorage;
|
| 19 | import net.minecraft.util.ExtraCodecs;
|
| 20 | import net.minecraft.util.SimpleBitStorage;
|
| 21 | import net.minecraft.util.ThreadingDetector;
|
| 22 | import net.minecraft.util.ZeroBitStorage;
|
| 23 | import org.jspecify.annotations.Nullable;
|
| 24 |
|
| 25 | public class PalettedContainer<T> implements PaletteResize<T>, PalettedContainerRO<T> {
|
| 26 | private static final int MIN_PALETTE_BITS = 0;
|
| 27 | private volatile PalettedContainer.Data<T> data;
|
| 28 | private final Strategy<T> strategy;
|
| 29 | private final ThreadingDetector threadingDetector = new ThreadingDetector("PalettedContainer");
|
| 30 |
|
| 31 | public void acquire() {
|
| 32 | this.threadingDetector.checkAndLock();
|
| 33 | }
|
| 34 |
|
| 35 | public void release() {
|
| 36 | this.threadingDetector.checkAndUnlock();
|
| 37 | }
|
| 38 |
|
| 39 | public static <T> Codec<PalettedContainer<T>> codecRW(final Codec<T> elementCodec, final Strategy<T> strategy, final T defaultValue) {
|
| 40 | PalettedContainerRO.Unpacker<T, PalettedContainer<T>> unpacker = PalettedContainer::unpack;
|
| 41 | return codec(elementCodec, strategy, defaultValue, unpacker);
|
| 42 | }
|
| 43 |
|
| 44 | public static <T> Codec<PalettedContainerRO<T>> codecRO(final Codec<T> elementCodec, final Strategy<T> strategy, final T defaultValue) {
|
| 45 | PalettedContainerRO.Unpacker<T, PalettedContainerRO<T>> unpacker = (s, data) -> unpack(s, data).map(e -> (PalettedContainerRO<T>)e);
|
| 46 | return codec(elementCodec, strategy, defaultValue, unpacker);
|
| 47 | }
|
| 48 |
|
| 49 | private static <T, C extends PalettedContainerRO<T>> Codec<C> codec(
|
| 50 | final Codec<T> elementCodec, final Strategy<T> strategy, final T defaultValue, final PalettedContainerRO.Unpacker<T, C> unpacker
|
| 51 | ) {
|
| 52 | return RecordCodecBuilder.<PalettedContainerRO.PackedData>create(
|
| 53 | i -> i.group(
|
| 54 | elementCodec.mapResult(ExtraCodecs.orElsePartial(defaultValue)).listOf().fieldOf("palette").forGetter(PalettedContainerRO.PackedData::paletteEntries),
|
| 55 | Codec.LONG_STREAM.lenientOptionalFieldOf("data").forGetter(PalettedContainerRO.PackedData::storage)
|
| 56 | )
|
| 57 | .apply(i, PalettedContainerRO.PackedData::new)
|
| 58 | )
|
| 59 | .comapFlatMap(discData -> unpacker.read(strategy, (PalettedContainerRO.PackedData<T>)discData), palettedContainer -> palettedContainer.pack(strategy));
|
| 60 | }
|
| 61 |
|
| 62 | private PalettedContainer(final Strategy<T> strategy, final Configuration dataConfiguration, final BitStorage storage, final Palette<T> palette) {
|
| 63 | this.strategy = strategy;
|
| 64 | this.data = new PalettedContainer.Data<>(dataConfiguration, storage, palette);
|
| 65 | }
|
| 66 |
|
| 67 | private PalettedContainer(final PalettedContainer<T> source) {
|
| 68 | this.strategy = source.strategy;
|
| 69 | this.data = source.data.copy();
|
| 70 | }
|
| 71 |
|
| 72 | public PalettedContainer(final T initialValue, final Strategy<T> strategy) {
|
| 73 | this.strategy = strategy;
|
| 74 | this.data = this.createOrReuseData(null, 0);
|
| 75 | this.data.palette.idFor(initialValue, this);
|
| 76 | }
|
| 77 |
|
| 78 | private PalettedContainer.Data<T> createOrReuseData(final PalettedContainer.@Nullable Data<T> oldData, final int targetBits) {
|
| 79 | Configuration dataConfiguration = this.strategy.getConfigurationForBitCount(targetBits);
|
| 80 | if (oldData != null && dataConfiguration.equals(oldData.configuration())) {
|
| 81 | return oldData;
|
| 82 | }
|
| 83 |
|
| 84 | BitStorage storage = dataConfiguration.bitsInMemory() == 0
|
| 85 | ? new ZeroBitStorage(this.strategy.entryCount())
|
| 86 | : new SimpleBitStorage(dataConfiguration.bitsInMemory(), this.strategy.entryCount());
|
| 87 | Palette<T> palette = dataConfiguration.createPalette(this.strategy, List.of());
|
| 88 | return new PalettedContainer.Data<>(dataConfiguration, storage, palette);
|
| 89 | }
|
| 90 |
|
| 91 | @Override
|
| 92 | public int onResize(final int bits, final T lastAddedValue) {
|
| 93 | PalettedContainer.Data<T> oldData = this.data;
|
| 94 | PalettedContainer.Data<T> newData = this.createOrReuseData(oldData, bits);
|
| 95 | newData.copyFrom(oldData.palette, oldData.storage);
|
| 96 | this.data = newData;
|
| 97 | return newData.palette.idFor(lastAddedValue, PaletteResize.noResizeExpected());
|
| 98 | }
|
| 99 |
|
| 100 | public T getAndSet(final int x, final int y, final int z, final T value) {
|
| 101 | this.acquire();
|
| 102 |
|
| 103 | try {
|
| 104 | return this.getAndSet(this.strategy.getIndex(x, y, z), value);
|
| 105 | } finally {
|
| 106 | this.release();
|
| 107 | }
|
| 108 | }
|
| 109 |
|
| 110 | public T getAndSetUnchecked(final int x, final int y, final int z, final T value) {
|
| 111 | return this.getAndSet(this.strategy.getIndex(x, y, z), value);
|
| 112 | }
|
| 113 |
|
| 114 | private T getAndSet(final int index, final T value) {
|
| 115 | int id = this.data.palette.idFor(value, this);
|
| 116 | int oldId = this.data.storage.getAndSet(index, id);
|
| 117 | return this.data.palette.valueFor(oldId);
|
| 118 | }
|
| 119 |
|
| 120 | public void set(final int x, final int y, final int z, final T value) {
|
| 121 | this.acquire();
|
| 122 |
|
| 123 | try {
|
| 124 | this.set(this.strategy.getIndex(x, y, z), value);
|
| 125 | } finally {
|
| 126 | this.release();
|
| 127 | }
|
| 128 | }
|
| 129 |
|
| 130 | private void set(final int index, final T value) {
|
| 131 | int id = this.data.palette.idFor(value, this);
|
| 132 | this.data.storage.set(index, id);
|
| 133 | }
|
| 134 |
|
| 135 | @Override
|
| 136 | public T get(final int x, final int y, final int z) {
|
| 137 | return this.get(this.strategy.getIndex(x, y, z));
|
| 138 | }
|
| 139 |
|
| 140 | protected T get(final int index) {
|
| 141 | PalettedContainer.Data<T> data = this.data;
|
| 142 | return data.palette.valueFor(data.storage.get(index));
|
| 143 | }
|
| 144 |
|
| 145 | @Override
|
| 146 | public void getAll(final Consumer<T> consumer) {
|
| 147 | Palette<T> palette = this.data.palette();
|
| 148 | IntSet allExistingEntries = new IntArraySet();
|
| 149 | this.data.storage.getAll(allExistingEntries::add);
|
| 150 | allExistingEntries.forEach(state -> consumer.accept(palette.valueFor(state)));
|
| 151 | }
|
| 152 |
|
| 153 | public void read(final FriendlyByteBuf buffer) {
|
| 154 | this.acquire();
|
| 155 |
|
| 156 | try {
|
| 157 | int newBits = buffer.readByte();
|
| 158 | PalettedContainer.Data<T> newData = this.createOrReuseData(this.data, newBits);
|
| 159 | newData.palette.read(buffer, this.strategy.globalMap());
|
| 160 | buffer.readFixedSizeLongArray(newData.storage.getRaw());
|
| 161 | this.data = newData;
|
| 162 | } finally {
|
| 163 | this.release();
|
| 164 | }
|
| 165 | }
|
| 166 |
|
| 167 | @Override
|
| 168 | public void write(final FriendlyByteBuf buffer) {
|
| 169 | this.acquire();
|
| 170 |
|
| 171 | try {
|
| 172 | this.data.write(buffer, this.strategy.globalMap());
|
| 173 | } finally {
|
| 174 | this.release();
|
| 175 | }
|
| 176 | }
|
| 177 |
|
| 178 | @VisibleForTesting
|
| 179 | public static <T> DataResult<PalettedContainer<T>> unpack(final Strategy<T> strategy, final PalettedContainerRO.PackedData<T> discData) {
|
| 180 | List<T> paletteEntries = discData.paletteEntries();
|
| 181 | int entryCount = strategy.entryCount();
|
| 182 | Configuration storedConfiguration = strategy.getConfigurationForPaletteSize(paletteEntries.size());
|
| 183 | int bitsOnDisc = storedConfiguration.bitsInStorage();
|
| 184 | if (discData.bitsPerEntry() != -1 && bitsOnDisc != discData.bitsPerEntry()) {
|
| 185 | return DataResult.error(() -> "Invalid bit count, calculated " + bitsOnDisc + ", but container declared " + discData.bitsPerEntry());
|
| 186 | }
|
| 187 |
|
| 188 | BitStorage storage;
|
| 189 | Palette<T> palette;
|
| 190 | if (storedConfiguration.bitsInMemory() == 0) {
|
| 191 | palette = storedConfiguration.createPalette(strategy, paletteEntries);
|
| 192 | storage = new ZeroBitStorage(entryCount);
|
| 193 | } else {
|
| 194 | Optional<LongStream> dataOpt = discData.storage();
|
| 195 | if (dataOpt.isEmpty()) {
|
| 196 | return DataResult.error(() -> "Missing values for non-zero storage");
|
| 197 | }
|
| 198 |
|
| 199 | long[] data = dataOpt.get().toArray();
|
| 200 |
|
| 201 | try {
|
| 202 | if (!storedConfiguration.alwaysRepack() && storedConfiguration.bitsInMemory() == bitsOnDisc) {
|
| 203 | palette = storedConfiguration.createPalette(strategy, paletteEntries);
|
| 204 | storage = new SimpleBitStorage(storedConfiguration.bitsInMemory(), entryCount, data);
|
| 205 | } else {
|
| 206 | Palette<T> oldPalette = new HashMapPalette<>(bitsOnDisc, paletteEntries);
|
| 207 | SimpleBitStorage oldStorage = new SimpleBitStorage(bitsOnDisc, entryCount, data);
|
| 208 | Palette<T> newPalette = storedConfiguration.createPalette(strategy, paletteEntries);
|
| 209 | int[] newContents = reencodeContents(oldStorage, oldPalette, newPalette);
|
| 210 | palette = newPalette;
|
| 211 | storage = new SimpleBitStorage(storedConfiguration.bitsInMemory(), entryCount, newContents);
|
| 212 | }
|
| 213 | } catch (SimpleBitStorage.InitializationException exception) {
|
| 214 | return DataResult.error(() -> "Failed to read PalettedContainer: " + exception.getMessage());
|
| 215 | }
|
| 216 | }
|
| 217 |
|
| 218 | return DataResult.success(new PalettedContainer<>(strategy, storedConfiguration, storage, palette));
|
| 219 | }
|
| 220 |
|
| 221 | @Override
|
| 222 | public PalettedContainerRO.PackedData<T> pack(final Strategy<T> strategy) {
|
| 223 | this.acquire();
|
| 224 |
|
| 225 | try {
|
| 226 | BitStorage currentStorage = this.data.storage;
|
| 227 | Palette<T> currentPalette = this.data.palette;
|
| 228 | HashMapPalette<T> newPalette = new HashMapPalette<>(currentStorage.getBits());
|
| 229 | int entryCount = strategy.entryCount();
|
| 230 | int[] newContents = reencodeContents(currentStorage, currentPalette, newPalette);
|
| 231 | Configuration storedConfiguration = strategy.getConfigurationForPaletteSize(newPalette.getSize());
|
| 232 | int bitsOnDisc = storedConfiguration.bitsInStorage();
|
| 233 | Optional<LongStream> values;
|
| 234 | if (bitsOnDisc != 0) {
|
| 235 | SimpleBitStorage storage = new SimpleBitStorage(bitsOnDisc, entryCount, newContents);
|
| 236 | values = Optional.of(Arrays.stream(storage.getRaw()));
|
| 237 | } else {
|
| 238 | values = Optional.empty();
|
| 239 | }
|
| 240 |
|
| 241 | return new PalettedContainerRO.PackedData<>(newPalette.getEntries(), values, bitsOnDisc);
|
| 242 | } finally {
|
| 243 | this.release();
|
| 244 | }
|
| 245 | }
|
| 246 |
|
| 247 | private static <T> int[] reencodeContents(final BitStorage storage, final Palette<T> oldPalette, final Palette<T> newPalette) {
|
| 248 | int[] buffer = new int[storage.getSize()];
|
| 249 | storage.unpack(buffer);
|
| 250 | PaletteResize<T> dummyResizer = PaletteResize.noResizeExpected();
|
| 251 | int lastReadId = -1;
|
| 252 | int lastWrittenId = -1;
|
| 253 |
|
| 254 | for (int index = 0; index < buffer.length; index++) {
|
| 255 | int id = buffer[index];
|
| 256 | if (id != lastReadId) {
|
| 257 | lastReadId = id;
|
| 258 | lastWrittenId = newPalette.idFor(oldPalette.valueFor(id), dummyResizer);
|
| 259 | }
|
| 260 |
|
| 261 | buffer[index] = lastWrittenId;
|
| 262 | }
|
| 263 |
|
| 264 | return buffer;
|
| 265 | }
|
| 266 |
|
| 267 | @Override
|
| 268 | public int getSerializedSize() {
|
| 269 | return this.data.getSerializedSize(this.strategy.globalMap());
|
| 270 | }
|
| 271 |
|
| 272 | @Override
|
| 273 | public int bitsPerEntry() {
|
| 274 | return this.data.storage().getBits();
|
| 275 | }
|
| 276 |
|
| 277 | @Override
|
| 278 | public boolean maybeHas(final Predicate<T> predicate) {
|
| 279 | return this.data.palette.maybeHas(predicate);
|
| 280 | }
|
| 281 |
|
| 282 | @Override
|
| 283 | public void forEachInPalette(final Consumer<T> consumer) {
|
| 284 | for (int i = 0; i < this.data.palette.getSize(); i++) {
|
| 285 | consumer.accept(this.data.palette.valueFor(i));
|
| 286 | }
|
| 287 | }
|
| 288 |
|
| 289 | @Override
|
| 290 | public PalettedContainer<T> copy() {
|
| 291 | return new PalettedContainer<>(this);
|
| 292 | }
|
| 293 |
|
| 294 | @Override
|
| 295 | public PalettedContainer<T> recreate() {
|
| 296 | return new PalettedContainer<>(this.data.palette.valueFor(0), this.strategy);
|
| 297 | }
|
| 298 |
|
| 299 | @Override
|
| 300 | public void count(final PalettedContainer.CountConsumer<T> output) {
|
| 301 | if (this.data.palette.getSize() == 1) {
|
| 302 | output.accept(this.data.palette.valueFor(0), this.data.storage.getSize());
|
| 303 | } else {
|
| 304 | Int2IntOpenHashMap counts = new Int2IntOpenHashMap();
|
| 305 | this.data.storage.getAll(state -> counts.addTo(state, 1));
|
| 306 | counts.int2IntEntrySet().forEach(entry -> output.accept(this.data.palette.valueFor(entry.getIntKey()), entry.getIntValue()));
|
| 307 | }
|
| 308 | }
|
| 309 |
|
| 310 | @FunctionalInterface
|
| 311 | public interface CountConsumer<T> {
|
| 312 | void accept(final T entry, final int count);
|
| 313 | }
|
| 314 |
|
| 315 | private record Data<T>(Configuration configuration, BitStorage storage, Palette<T> palette) {
|
| 316 | public void copyFrom(final Palette<T> oldPalette, final BitStorage oldStorage) {
|
| 317 | PaletteResize<T> dummyResizer = PaletteResize.noResizeExpected();
|
| 318 | if (oldPalette.getSize() == 1) {
|
| 319 | T value = oldPalette.valueFor(0);
|
| 320 | this.storage.fill(this.palette.idFor(value, dummyResizer));
|
| 321 | } else {
|
| 322 | int lastOldId = -1;
|
| 323 | int newId = -1;
|
| 324 |
|
| 325 | for (int i = 0; i < oldStorage.getSize(); i++) {
|
| 326 | int oldId = oldStorage.get(i);
|
| 327 | if (oldId != lastOldId) {
|
| 328 | T value = oldPalette.valueFor(oldId);
|
| 329 | newId = this.palette.idFor(value, dummyResizer);
|
| 330 | lastOldId = oldId;
|
| 331 | }
|
| 332 |
|
| 333 | this.storage.set(i, newId);
|
| 334 | }
|
| 335 | }
|
| 336 | }
|
| 337 |
|
| 338 | public int getSerializedSize(final IdMap<T> globalMap) {
|
| 339 | return 1 + this.palette.getSerializedSize(globalMap) + this.storage.getRaw().length * 8;
|
| 340 | }
|
| 341 |
|
| 342 | public void write(final FriendlyByteBuf buffer, final IdMap<T> globalMap) {
|
| 343 | buffer.writeByte(this.storage.getBits());
|
| 344 | this.palette.write(buffer, globalMap);
|
| 345 | buffer.writeFixedSizeLongArray(this.storage.getRaw());
|
| 346 | }
|
| 347 |
|
| 348 | public PalettedContainer.Data<T> copy() {
|
| 349 | return new PalettedContainer.Data<>(this.configuration, this.storage.copy(), this.palette.copy());
|
| 350 | }
|
| 351 | }
|
| 352 | }
|
| 353 |
|