| 1 | package net.minecraft.util;
|
| 2 |
|
| 3 | import java.util.Locale;
|
| 4 | import java.util.function.Consumer;
|
| 5 | import org.jspecify.annotations.Nullable;
|
| 6 |
|
| 7 | public class StaticCache2D<T> {
|
| 8 | private final int minX;
|
| 9 | private final int minZ;
|
| 10 | private final int sizeX;
|
| 11 | private final int sizeZ;
|
| 12 | private final @Nullable Object[] cache;
|
| 13 |
|
| 14 | public static <T> StaticCache2D<T> create(final int centerX, final int centerZ, final int range, final StaticCache2D.Initializer<T> initializer) {
|
| 15 | int minX = centerX - range;
|
| 16 | int minZ = centerZ - range;
|
| 17 | int size = 2 * range + 1;
|
| 18 | return new StaticCache2D<>(minX, minZ, size, size, initializer);
|
| 19 | }
|
| 20 |
|
| 21 | private StaticCache2D(final int minX, final int minZ, final int sizeX, final int sizeZ, final StaticCache2D.Initializer<T> initializer) {
|
| 22 | this.minX = minX;
|
| 23 | this.minZ = minZ;
|
| 24 | this.sizeX = sizeX;
|
| 25 | this.sizeZ = sizeZ;
|
| 26 | this.cache = new Object[this.sizeX * this.sizeZ];
|
| 27 |
|
| 28 | for (int x = minX; x < minX + sizeX; x++) {
|
| 29 | for (int z = minZ; z < minZ + sizeZ; z++) {
|
| 30 | this.cache[this.getIndex(x, z)] = initializer.get(x, z);
|
| 31 | }
|
| 32 | }
|
| 33 | }
|
| 34 |
|
| 35 | public <U> StaticCache2D<U> map(final StaticCache2D.MappingFunction<T, U> function) {
|
| 36 | return new StaticCache2D(this.minX, this.minZ, this.sizeX, this.sizeZ, (x, z) -> (T)function.apply(this.get(x, z), x, z));
|
| 37 | }
|
| 38 |
|
| 39 | public void forEach(final Consumer<T> consumer) {
|
| 40 | for (Object o : this.cache) {
|
| 41 | consumer.accept((T)o);
|
| 42 | }
|
| 43 | }
|
| 44 |
|
| 45 | public T get(final int x, final int z) {
|
| 46 | if (!this.contains(x, z)) {
|
| 47 | throw new IllegalArgumentException("Requested out of range value (" + x + "," + z + ") from " + this);
|
| 48 | } else {
|
| 49 | return (T)this.cache[this.getIndex(x, z)];
|
| 50 | }
|
| 51 | }
|
| 52 |
|
| 53 | public boolean contains(final int x, final int z) {
|
| 54 | int deltaX = x - this.minX;
|
| 55 | int deltaZ = z - this.minZ;
|
| 56 | return deltaX >= 0 && deltaX < this.sizeX && deltaZ >= 0 && deltaZ < this.sizeZ;
|
| 57 | }
|
| 58 |
|
| 59 | @Override
|
| 60 | public String toString() {
|
| 61 | return String.format(Locale.ROOT, "StaticCache2D[%d, %d, %d, %d]", this.minX, this.minZ, this.minX + this.sizeX, this.minZ + this.sizeZ);
|
| 62 | }
|
| 63 |
|
| 64 | private int getIndex(final int x, final int z) {
|
| 65 | int deltaX = x - this.minX;
|
| 66 | int deltaZ = z - this.minZ;
|
| 67 | return deltaX * this.sizeZ + deltaZ;
|
| 68 | }
|
| 69 |
|
| 70 | @FunctionalInterface
|
| 71 | public interface Initializer<T> {
|
| 72 | T get(int x, int z);
|
| 73 | }
|
| 74 |
|
| 75 | @FunctionalInterface
|
| 76 | public interface MappingFunction<T, U> {
|
| 77 | U apply(T value, int x, int z);
|
| 78 | }
|
| 79 | }
|
| 80 |
|