diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/VolumeMembershipCheck.java b/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/ArrayProximityCheck4D.java similarity index 61% rename from src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/VolumeMembershipCheck.java rename to src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/ArrayProximityCheck4D.java index 94746be4..0799e927 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/VolumeMembershipCheck.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/ArrayProximityCheck4D.java @@ -3,16 +3,19 @@ package com.gtnewhorizon.gtnhlib.datastructs.space; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Objects; + +import javax.annotation.Nonnull; /** - * This is a data structure that allows you to quickly check if an arbitrary point in space is contained within at least - * one of the volumes defined. + * This is a data structure that allows you to quickly check if an arbitrary point in space (dim, x, y, z) is contained + * within at least one of the volumes defined. *

* When adding a volume to an existing position, it won't add a second volume but will instead update the radius of the * element at that position. */ @SuppressWarnings("unused") -public class VolumeMembershipCheck { +public class ArrayProximityCheck4D { // optimization idea : this can be dynamically // replaced with a map if the amount of dims gets too big @@ -20,17 +23,16 @@ public class VolumeMembershipCheck { private final List dimList = new ArrayList<>(); private final VolumeShape shape; - public enum VolumeShape { - SPHERE, - CUBE - } - - public VolumeMembershipCheck(VolumeShape shape) { + public ArrayProximityCheck4D(@Nonnull VolumeShape shape) { + Objects.requireNonNull(shape); this.shape = shape; } + @SuppressWarnings("ForLoopReplaceableByForEach") private DimensionData getDataForDim(int dim) { - for (DimensionData dimData : dimList) { + final int size = dimList.size(); + for (int i = 0; i < size; i++) { + final DimensionData dimData = dimList.get(i); if (dimData.getDimId() == dim) { return dimData; } @@ -38,7 +40,10 @@ public class VolumeMembershipCheck { return null; } - public void putVolume(int dim, int x, int y, int z, int radius) { + public void put(int dim, int x, int y, int z, int radius) { + if (radius < 0) { + throw new IllegalArgumentException("Radius must be strictly positive"); + } DimensionData dimData = getDataForDim(dim); if (dimData == null) { dimData = new DimensionData(dim); @@ -47,7 +52,7 @@ public class VolumeMembershipCheck { dimData.put(x, y, z, radius); } - public void removeVolume(int dim, int x, int y, int z) { + public void remove(int dim, int x, int y, int z) { final DimensionData dimData = getDataForDim(dim); if (dimData == null) { return; @@ -58,22 +63,45 @@ public class VolumeMembershipCheck { } } - public boolean isInVolume(int dim, double x, double y, double z) { + public boolean isInRange(int dim, double x, double y, double z) { final DimensionData dimData = getDataForDim(dim); if (dimData == null) { return false; } - return dimData.isInVolume(x, y, z); + if (shape == VolumeShape.SPHERE) { + return dimData.isInSphere(x, y, z); + } else if (shape == VolumeShape.CUBE) { + return dimData.isInCube(x, y, z); + } + throw new IllegalArgumentException("Invalid shape"); } - private class DimensionData { + @SuppressWarnings("ForLoopReplaceableByForEach") + public int size() { + int size = 0; + final int listSize = dimList.size(); + for (int i = 0; i < listSize; i++) { + size += dimList.get(i).size(); + } + return size; + } + + public boolean isEmpty() { + return dimList.isEmpty(); + } + + public void clear() { + dimList.clear(); + } + + private static class DimensionData { // optimization idea : the data array can be // dynamically replaced with a different // data structure if the size gets too big // implementation note : since we want fast - // isInVolume() checks, when removing volumes, + // isInRange() checks, when removing volumes, // we move the last element to the removed index // so that all the "alive data" in the array // remains at the start @@ -97,6 +125,10 @@ public class VolumeMembershipCheck { return dimId; } + public int size() { + return size; + } + public void put(int x, int y, int z, int radius) { final int maxIndex = size * 4; final int[] a = data; @@ -123,6 +155,9 @@ public class VolumeMembershipCheck { if (x == a[i] && y == a[i + 1] && z == a[i + 2]) { int numMoved = maxIndex - i - 4; if (numMoved > 0) { + // if it's not the last element that got removed, + // move the last element to the removed index + // to keep all data packed at the start of the array System.arraycopy(data, maxIndex - 4, data, i, 4); } size--; @@ -134,32 +169,35 @@ public class VolumeMembershipCheck { } } - public boolean isInVolume(double x, double y, double z) { + public boolean isInSphere(double x, double y, double z) { final int maxIndex = size * 4; final int[] a = data; - if (shape == VolumeShape.SPHERE) { - for (int i = 0; i < maxIndex; i += 4) { - final double dx = x - a[i] - 0.5D; - final double dy = y - a[i + 1] - 0.5D; - final double dz = z - a[i + 2] - 0.5D; - final double radius = a[i + 3]; - if (dx * dx + dy * dy + dz * dz < radius * radius) { - return true; - } + for (int i = 0; i < maxIndex; i += 4) { + final double dx = x - a[i] - 0.5D; + final double dy = y - a[i + 1] - 0.5D; + final double dz = z - a[i + 2] - 0.5D; + final double radius = a[i + 3]; + if (dx * dx + dy * dy + dz * dz < radius * radius) { + return true; } - } else if (shape == VolumeShape.CUBE) { - for (int i = 0; i < maxIndex; i += 4) { - final double centerX = a[i] + 0.5D; - final double centerY = a[i + 1] + 0.5D; - final double centerZ = a[i + 2] + 0.5D; - final double radius = a[i + 3] + 0.5D; - if (centerX - radius < x && x < centerX + radius - && centerY - radius < y - && y < centerY + radius - && centerZ - radius < z - && z < centerZ + radius) { - return true; - } + } + return false; + } + + public boolean isInCube(double x, double y, double z) { + final int maxIndex = size * 4; + final int[] a = data; + for (int i = 0; i < maxIndex; i += 4) { + final double centerX = a[i] + 0.5D; + final double centerY = a[i + 1] + 0.5D; + final double centerZ = a[i + 2] + 0.5D; + final double radius = a[i + 3] + 0.5D; + if (centerX - radius < x && x < centerX + radius + && centerY - radius < y + && y < centerY + radius + && centerZ - radius < z + && z < centerZ + radius) { + return true; } } return false; diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/ArrayProximityMap4D.java b/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/ArrayProximityMap4D.java new file mode 100644 index 00000000..022d4cc1 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/ArrayProximityMap4D.java @@ -0,0 +1,360 @@ +package com.gtnewhorizon.gtnhlib.datastructs.space; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.function.Consumer; + +import javax.annotation.Nonnull; + +/** + * This is a data structure that allows you to quickly check if an arbitrary point in space (dim, x, y, z) is in range + * of at least one of the objects defined. You can also retrieve the closest stored object from that point if any. Or + * perform an action for each object in range. + *

+ * When adding an object to an existing position, it won't add a second object but will instead replace the element at + * this position and update the radius. + */ +@SuppressWarnings("unused") +public class ArrayProximityMap4D { + + // optimization idea : this can be dynamically + // replaced with a map if the amount of dims gets too big + // (I doubt the amount of dimensions will ever be too big) + private final List> dimList = new ArrayList<>(); + private final VolumeShape shape; + + public ArrayProximityMap4D(@Nonnull VolumeShape shape) { + Objects.requireNonNull(shape); + this.shape = shape; + } + + @SuppressWarnings("ForLoopReplaceableByForEach") + private DimensionData getDataForDim(int dim) { + final int size = dimList.size(); + for (int i = 0; i < size; i++) { + final DimensionData dimData = dimList.get(i); + if (dimData.getDimId() == dim) { + return dimData; + } + } + return null; + } + + public void put(T obj, int dim, int x, int y, int z, int radius) { + if (radius < 0) { + throw new IllegalArgumentException("Radius must be strictly positive"); + } + DimensionData dimData = getDataForDim(dim); + if (dimData == null) { + dimData = new DimensionData<>(dim); + dimList.add(dimData); + } + dimData.put(obj, x, y, z, radius); + } + + public T remove(int dim, int x, int y, int z) { + final DimensionData dimData = getDataForDim(dim); + if (dimData == null) { + return null; + } + final T obj = dimData.remove(x, y, z); + if (dimData.isEmpty()) { + dimList.remove(dimData); + } + return obj; + } + + public boolean isInRange(int dim, double x, double y, double z) { + final DimensionData dimData = getDataForDim(dim); + if (dimData == null) { + return false; + } + if (shape == VolumeShape.SPHERE) { + return dimData.isInSphere(x, y, z); + } else if (shape == VolumeShape.CUBE) { + return dimData.isInCube(x, y, z); + } + throw new IllegalArgumentException("Invalid shape"); + } + + public T getClosest(int dim, double x, double y, double z) { + final DimensionData dimData = getDataForDim(dim); + if (dimData == null) { + return null; + } + if (shape == VolumeShape.SPHERE) { + return dimData.closestSphere(x, y, z); + } else if (shape == VolumeShape.CUBE) { + return dimData.closestCube(x, y, z); + } + throw new IllegalArgumentException("Invalid shape"); + } + + public void forEachInRange(int dim, double x, double y, double z, Consumer action) { + final DimensionData dimData = getDataForDim(dim); + if (dimData == null) { + return; + } + if (shape == VolumeShape.SPHERE) { + dimData.forEachInSphere(x, y, z, action); + } else if (shape == VolumeShape.CUBE) { + dimData.forEachInCube(x, y, z, action); + } else { + throw new IllegalArgumentException("Invalid shape"); + } + } + + @SuppressWarnings("ForLoopReplaceableByForEach") + public int size() { + int size = 0; + final int listSize = dimList.size(); + for (int i = 0; i < listSize; i++) { + size += dimList.get(i).size(); + } + return size; + } + + public boolean isEmpty() { + return dimList.isEmpty(); + } + + public void clear() { + dimList.clear(); + } + + private static class DimensionData { + + // optimization idea : the data array can be + // dynamically replaced with a different + // data structure if the size gets too big + + // implementation note : since we want fast + // isInRange() checks, when removing volumes, + // we move the last element to the removed index + // so that all the "alive data" in the array + // remains at the start + + // the data array contains blocks of 4 ints + // 1 = positionX, 2 = positionY, 3 = positionZ, 4 = radius + + private final int dimId; + private int[] data; + private Object[] objects; + private int size; + + private static final int INITIAL_CAPACITY = 8; + + public DimensionData(int dimensionId) { + this.dimId = dimensionId; + this.data = new int[INITIAL_CAPACITY * 4]; + this.objects = new Object[INITIAL_CAPACITY]; + this.size = 0; + } + + public int getDimId() { + return dimId; + } + + public int size() { + return size; + } + + public void put(T obj, int x, int y, int z, int radius) { + final int maxIndex = size * 4; + final int[] a = data; + for (int i = 0; i < maxIndex; i += 4) { + if (x == a[i] && y == a[i + 1] && z == a[i + 2]) { + a[i + 3] = radius; + objects[i / 4] = obj; + return; + } + } + if (maxIndex == data.length) { + data = Arrays.copyOf(data, data.length * 2); + objects = Arrays.copyOf(objects, objects.length * 2); + } + data[maxIndex] = x; + data[maxIndex + 1] = y; + data[maxIndex + 2] = z; + data[maxIndex + 3] = radius; + objects[size] = obj; + size++; + } + + @SuppressWarnings("unchecked") + public T remove(int x, int y, int z) { + final int maxIndex = size * 4; + final int[] a = data; + for (int i = 0; i < maxIndex; i += 4) { + if (x == a[i] && y == a[i + 1] && z == a[i + 2]) { + Object removed = objects[i / 4]; + int numMoved = maxIndex - i - 4; + if (numMoved > 0) { + // if it's not the last element that got removed, + // move the last element to the removed index + // to keep all data packed at the start of the array + System.arraycopy(data, maxIndex - 4, data, i, 4); + objects[i / 4] = objects[size]; + objects[size] = null; + } + size--; + if (data.length >= INITIAL_CAPACITY * 4 * 2 && size * 4 < data.length / 4) { + data = Arrays.copyOf(data, data.length / 2); + objects = Arrays.copyOf(objects, objects.length / 2); + } + return (T) removed; + } + } + return null; + } + + public boolean isInSphere(double x, double y, double z) { + final int maxIndex = size * 4; + final int[] a = data; + for (int i = 0; i < maxIndex; i += 4) { + final double dx = x - a[i] - 0.5D; + final double dy = y - a[i + 1] - 0.5D; + final double dz = z - a[i + 2] - 0.5D; + final double radius = a[i + 3]; + if (dx * dx + dy * dy + dz * dz < radius * radius) { + return true; + } + } + return false; + } + + public boolean isInCube(double x, double y, double z) { + final int maxIndex = size * 4; + final int[] a = data; + for (int i = 0; i < maxIndex; i += 4) { + final double centerX = a[i] + 0.5D; + final double centerY = a[i + 1] + 0.5D; + final double centerZ = a[i + 2] + 0.5D; + final double radius = a[i + 3] + 0.5D; + if (centerX - radius < x && x < centerX + radius + && centerY - radius < y + && y < centerY + radius + && centerZ - radius < z + && z < centerZ + radius) { + return true; + } + } + return false; + } + + @SuppressWarnings("unchecked") + public T closestSphere(double x, double y, double z) { + final int maxIndex = size * 4; + final int[] a = data; + int closestIndex = -1; + double closestDistSq = Double.MAX_VALUE; + for (int i = 0; i < maxIndex; i += 4) { + final double dx = x - a[i] - 0.5D; + final double dy = y - a[i + 1] - 0.5D; + final double dz = z - a[i + 2] - 0.5D; + final double radius = a[i + 3]; + final double distSq = dx * dx + dy * dy + dz * dz; + if (distSq < radius * radius && distSq < closestDistSq) { + closestIndex = i; + closestDistSq = distSq; + } + } + if (closestIndex == -1) return null; + return (T) objects[closestIndex / 4]; + } + + @SuppressWarnings("unchecked") + public T closestCube(double x, double y, double z) { + final int maxIndex = size * 4; + final int[] a = data; + int closestIndex = -1; + double closestDistSq = Double.MAX_VALUE; + for (int i = 0; i < maxIndex; i += 4) { + final double centerX = a[i] + 0.5D; + final double centerY = a[i + 1] + 0.5D; + final double centerZ = a[i + 2] + 0.5D; + final double radius = a[i + 3] + 0.5D; + if (centerX - radius < x && x < centerX + radius + && centerY - radius < y + && y < centerY + radius + && centerZ - radius < z + && z < centerZ + radius) { + final double dx = x - centerX; + final double dy = y - centerY; + final double dz = z - centerZ; + final double distSq = dx * dx + dy * dy + dz * dz; + if (distSq < closestDistSq) { + closestIndex = i; + closestDistSq = distSq; + } + } + } + if (closestIndex == -1) return null; + return (T) objects[closestIndex / 4]; + } + + @SuppressWarnings("unchecked") + public void forEachInSphere(double x, double y, double z, Consumer action) { + final int maxIndex = size * 4; + final int[] a = data; + for (int i = 0; i < maxIndex; i += 4) { + final double dx = x - a[i] - 0.5D; + final double dy = y - a[i + 1] - 0.5D; + final double dz = z - a[i + 2] - 0.5D; + final double radius = a[i + 3]; + final double distSq = dx * dx + dy * dy + dz * dz; + if (distSq < radius * radius) { + action.accept((T) objects[i / 4]); + } + } + } + + @SuppressWarnings("unchecked") + public void forEachInCube(double x, double y, double z, Consumer action) { + final int maxIndex = size * 4; + final int[] a = data; + for (int i = 0; i < maxIndex; i += 4) { + final double centerX = a[i] + 0.5D; + final double centerY = a[i + 1] + 0.5D; + final double centerZ = a[i + 2] + 0.5D; + final double radius = a[i + 3] + 0.5D; + if (centerX - radius < x && x < centerX + radius + && centerY - radius < y + && y < centerY + radius + && centerZ - radius < z + && z < centerZ + radius) { + action.accept((T) objects[i / 4]); + } + } + } + + public boolean isEmpty() { + return size == 0; + } + + @Override + public String toString() { + // spotless:off + final int maxIndex = size * 4; + final int[] a = data; + final StringBuilder sb = new StringBuilder("DimensionData{"); + sb.append("dimId=").append(dimId); + sb.append(", size=").append(size); + sb.append(", data={"); + for (int i = 0; i < maxIndex; i += 4) { + if (i != 0) sb.append(", "); + sb.append("{x=").append(a[i]); + sb.append(", y=").append(a[i + 1]); + sb.append(", z=").append(a[i + 2]); + sb.append(", radius=").append(a[i + 3]); + sb.append(" , obj=").append(objects[i / 4]).append('}'); + } + sb.append("}}"); + return sb.toString(); + // spotless:on + } + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/VolumeShape.java b/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/VolumeShape.java new file mode 100644 index 00000000..da62fc79 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/space/VolumeShape.java @@ -0,0 +1,6 @@ +package com.gtnewhorizon.gtnhlib.datastructs.space; + +public enum VolumeShape { + SPHERE, + CUBE +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/spatialhashgrid/SpatialHashGrid.java b/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/spatialhashgrid/SpatialHashGrid.java deleted file mode 100644 index d34f5f67..00000000 --- a/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/spatialhashgrid/SpatialHashGrid.java +++ /dev/null @@ -1,474 +0,0 @@ -package com.gtnewhorizon.gtnhlib.datastructs.spatialhashgrid; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.function.BiConsumer; - -import org.joml.Vector3i; - -import com.gtnewhorizon.gtnhlib.util.CoordinatePacker; -import com.gtnewhorizon.gtnhlib.util.DistanceUtil; - -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; - -/** - * 3D Spatial Grid
- * Objects are hashed using their position - * - * @param object type to store - */ -@SuppressWarnings("unused") -public class SpatialHashGrid { - - private final int cellSize; - private final BiConsumer positionExtractor; - private final Vector3i scratch = new Vector3i(); - private final Long2ObjectOpenHashMap> grid = new Long2ObjectOpenHashMap<>(); - - public enum DistanceFormula implements DistanceMetric { - - SquaredEuclidean(new DistanceMetric() { - - @Override - public double distance(double x1, double y1, double z1, double x2, double y2, double z2) { - return DistanceUtil.squaredEuclideanDistance(x1, y1, z1, x2, y2, z2); - } - - @Override - public double transformCompareDistance(double radius) { - return radius * radius; - } - }), - /** - * Chessboard - */ - Chebyshev(DistanceUtil::chebyshevDistance), - - /** - * Taxicab - */ - Manhattan(DistanceUtil::manhattanDistance); - - private final DistanceMetric metric; - - DistanceFormula(DistanceMetric metric) { - this.metric = metric; - } - - @Override - public double distance(double x1, double y1, double z1, double x2, double y2, double z2) { - return this.metric.distance(x1, y1, z1, x2, y2, z2); - } - - @Override - public double transformCompareDistance(double radius) { - return this.metric.transformCompareDistance(radius); - } - } - - @FunctionalInterface - public interface DistanceMetric { - - double distance(double x1, double y1, double z1, double x2, double y2, double z2); - - default double transformCompareDistance(double radius) { - return radius; - } - } - - public SpatialHashGrid(int cellSize, BiConsumer positionExtractor) { - if (cellSize <= 0) throw new IllegalArgumentException("cellSize can not be less than or equal to 0"); - this.cellSize = cellSize; - this.positionExtractor = positionExtractor; - } - - private static long pack(int x, int y, int z) { - return CoordinatePacker.pack(x, y, z); - } - - private static long hash(int cellSize, int x, int y, int z) { - return pack(Math.floorDiv(x, cellSize), Math.floorDiv(y, cellSize), Math.floorDiv(z, cellSize)); - } - - /** - * Insert an object into the grid - */ - public void insert(T obj) { - positionExtractor.accept(scratch, obj); - long key = hash(cellSize, scratch.x, scratch.y, scratch.z); - ObjectArrayList list = grid.computeIfAbsent(key, k -> new ObjectArrayList<>()); - list.add(obj); - } - - /** - * Remove an object for the grid - */ - public void remove(T obj) { - positionExtractor.accept(scratch, obj); - long key = hash(cellSize, scratch.x, scratch.y, scratch.z); - ObjectArrayList list = grid.get(key); - if (list == null) return; - - list.remove(obj); - if (!list.isEmpty()) return; - - grid.remove(key); - } - - public boolean contains(T obj) { - positionExtractor.accept(scratch, obj); - long key = hash(cellSize, scratch.x, scratch.y, scratch.z); - ObjectArrayList list = grid.get(key); - if (list == null) return false; - - return list.contains(obj); - } - - /** - * Search the grid for nearby objects using Squared Euclidean Distance Formula. - * - * @param radius distance in blocks to check (sphere) - * @return list of nearby objects - */ - public List collectNearbySquaredEuclidean(int x, int y, int z, int radius) { - return collectNearbyWithMetric(x, y, z, radius, DistanceFormula.SquaredEuclidean); - } - - /** - * Search the grid for nearby objects using Chebyshev (Chessboard) Distance Formula. - * - * @param radius distance in blocks to check (sphere) - * @return list of nearby objects - */ - public List collectNearbyChebyshev(int x, int y, int z, int radius) { - return collectNearbyWithMetric(x, y, z, radius, DistanceFormula.Chebyshev); - } - - /** - * Search the grid for nearby objects using Manhattan (Taxicab) Distance Formula. - * - * @param radius distance in blocks to check (sphere) - * @return list of nearby objects - */ - public List collectNearbyManhattan(int x, int y, int z, int radius) { - return collectNearbyWithMetric(x, y, z, radius, DistanceFormula.Manhattan); - } - - /** - * Find the first nearby object using Squared Euclidean Distance Formula. - * - * @param x position to check - * @param y position to check - * @param z position to check - * @param radius distance in blocks to check (sphere) - * @return the first nearby object or null if none found - */ - public T findFirstNearbySquaredEuclidean(int x, int y, int z, int radius) { - return findFirstNearbyWithMetric(x, y, z, radius, DistanceFormula.SquaredEuclidean); - } - - /** - * Find the first nearby object using Chebyshev (Chessboard) Distance Formula. - * - * @param x position to check - * @param y position to check - * @param z position to check - * @param radius distance in blocks to check (sphere) - * @return the first nearby object or null if none found - */ - public T findFirstNearbyChebyshev(int x, int y, int z, int radius) { - return findFirstNearbyWithMetric(x, y, z, radius, DistanceFormula.Chebyshev); - } - - /** - * Find the first nearby object using Manhattan (Taxicab) Distance Formula. - * - * @param x position to check - * @param y position to check - * @param z position to check - * @param radius distance in blocks to check (sphere) - * @return the first nearby object or null if none found - */ - public T findFirstNearbyManhattan(int x, int y, int z, int radius) { - return findFirstNearbyWithMetric(x, y, z, radius, DistanceFormula.Manhattan); - } - - /** - * Find the closest nearby object using Squared Euclidean Distance Formula. - * - * @param x position to check - * @param y position to check - * @param z position to check - * @param radius distance in blocks to check (sphere) - * @return the closest nearby object or null if none found - */ - public T findClosestSquaredEuclidean(int x, int y, int z, int radius) { - return findClosestWithMetric(x, y, z, radius, DistanceFormula.SquaredEuclidean); - } - - /** - * Find the closest nearby object using Chebyshev (Chessboard) Distance Formula. - * - * @param x position to check - * @param y position to check - * @param z position to check - * @param radius distance in blocks to check (sphere) - * @return the closest nearby object or null if none found - */ - public T findClosestChebyshev(int x, int y, int z, int radius) { - return findClosestWithMetric(x, y, z, radius, DistanceFormula.Chebyshev); - } - - /** - * Find the closest nearby object using Manhattan (Taxicab) Distance Formula. - * - * @param x position to check - * @param y position to check - * @param z position to check - * @param radius distance in blocks to check (sphere) - * @return the closest nearby object or null if none found - */ - public T findClosestManhattan(int x, int y, int z, int radius) { - return findClosestWithMetric(x, y, z, radius, DistanceFormula.Manhattan); - } - - /** - * Find the first nearby object using a specified distance metric.
- * Note: This method does not return the closest object - * - * @param x position to check - * @param y position to check - * @param z position to check - * @param radius distance in blocks to check (sphere) - * @param distanceMetric distance metric to use - * @return the first nearby object or null if none found - * @see #findClosestWithMetric(int, int, int, int, DistanceMetric) - */ - public T findFirstNearbyWithMetric(int x, int y, int z, int radius, DistanceMetric distanceMetric) { - Iterator iterator = iterNearbyWithMetric(x, y, z, radius, distanceMetric); - return (iterator.hasNext() ? iterator.next() : null); - } - - /** - * Find the closest nearby object using a specified distance metric. - * - * @param x position to check - * @param y position to check - * @param z position to check - * @param radius distance in blocks to check (sphere) - * @param distanceMetric distance metric to use - * @return the closest nearby object or null if none found - */ - public T findClosestWithMetric(int x, int y, int z, int radius, DistanceMetric distanceMetric) { - Iterator iterator = iterNearbyWithMetric(x, y, z, radius, distanceMetric); - T closestObject = null; - double closestDistance = Double.MAX_VALUE; - - while (iterator.hasNext()) { - T obj = iterator.next(); - positionExtractor.accept(scratch, obj); - double distance = distanceMetric.distance(x, y, z, scratch.x, scratch.y, scratch.z); - - if (distance < closestDistance) { - closestDistance = distance; - closestObject = obj; - } - } - - return closestObject; - } - - /** - * Collect all nearby objects using a specified distance metric. - * - * @param x position to check - * @param y position to check - * @param z position to check - * @param radius distance in blocks to check (sphere) - * @param distanceMetric distance metric to use - * @return list of nearby objects - */ - public List collectNearbyWithMetric(int x, int y, int z, int radius, DistanceMetric distanceMetric) { - Iterator iterator = iterNearbyWithMetric(x, y, z, radius, distanceMetric); - List resultList = new ArrayList<>(); - - while (iterator.hasNext()) { - T obj = iterator.next(); - resultList.add(obj); - } - - return resultList; - } - - /** - * Search the grid for nearby objects using a specified distance metric. - * - * @param x position to check - * @param y position to check - * @param z position to check - * @param radius distance in blocks to check (sphere) - * @param distanceMetric distance metric to use - * @return iterator of nearby objects - */ - public Iterator iterNearbyWithMetric(int x, int y, int z, int radius, DistanceMetric distanceMetric) { - radius = Math.abs(radius); // just no - final int cellX = Math.floorDiv(x, cellSize); - final int cellY = Math.floorDiv(y, cellSize); - final int cellZ = Math.floorDiv(z, cellSize); - - return new GridIterator<>(grid, x, y, z, radius, cellSize, distanceMetric, positionExtractor); - } - - public static class GridIterator implements Iterator { - - private final Long2ObjectOpenHashMap> grid; - private final int x, y, z; - private final int cellSize; - private final int minCellX, minCellY, minCellZ; - private final int maxCellX, maxCellY, maxCellZ; - private final double distanceCompared; - private final DistanceMetric distanceMetric; - private final BiConsumer positionExtractor; - private final Vector3i scratch = new Vector3i(); - - private int currCellX, currCellY, currCellZ; - private boolean isEdgeCell; - private ObjectArrayList currentCell; - private int currCellIdx; - - private T nextElement; - private boolean hasNextElement; - - public GridIterator(Long2ObjectOpenHashMap> grid, int x, int y, int z, int radius, - int cellSize, DistanceMetric distanceMetric, BiConsumer positionExtractor) { - this.grid = grid; - this.x = x; - this.y = y; - this.z = z; - this.cellSize = cellSize; - this.distanceCompared = distanceMetric.transformCompareDistance(radius); - this.distanceMetric = distanceMetric; - this.positionExtractor = positionExtractor; - - this.minCellX = Math.floorDiv(x - radius, cellSize); - this.minCellY = Math.floorDiv(y - radius, cellSize); - this.minCellZ = Math.floorDiv(z - radius, cellSize); - this.maxCellX = Math.floorDiv(x + radius + cellSize - 1, cellSize); - this.maxCellY = Math.floorDiv(y + radius + cellSize - 1, cellSize); - this.maxCellZ = Math.floorDiv(z + radius + cellSize - 1, cellSize); - this.currCellX = minCellX; - this.currCellY = minCellY; - this.currCellZ = minCellZ; - - computeNext(); - } - - @Override - public boolean hasNext() { - return hasNextElement; - } - - @Override - public T next() { - if (!hasNextElement) throw new NoSuchElementException(); - T result = nextElement; - computeNext(); - return result; - } - - public T peek() { - if (!hasNextElement) throw new NoSuchElementException(); - return nextElement; - } - - private void computeNext() { - hasNextElement = false; - nextElement = null; - - do { - if (findNextElementInCell()) return; - } while (findNextCell()); - } - - private boolean isCellPotentiallyInRange(int cellX, int cellY, int cellZ) { - int nx = nearest(x, cellX, cellX + cellSize - 1); - int ny = nearest(y, cellY, cellY + cellSize - 1); - int nz = nearest(z, cellZ, cellZ + cellSize - 1); - - return distanceMetric.distance(x, y, z, nx, ny, nz) <= distanceCompared; - } - - private boolean isCellFullyInRange(int cellX, int cellY, int cellZ) { - int fx = farthest(x, cellX, cellX + cellSize - 1); - int fy = farthest(y, cellY, cellY + cellSize - 1); - int fz = farthest(z, cellZ, cellZ + cellSize - 1); - - return distanceMetric.distance(x, y, z, fx, fy, fz) <= distanceCompared; - } - - private static int farthest(int p, int min, int max) { - if (p < min) return max; - if (p > max) return min; - return ((p - min) > (max - p)) ? min : max; - } - - private static int nearest(int v, int min, int max) { - if (v < min) return min; - return Math.min(v, max); - } - - private boolean findNextCell() { - while (currCellX <= maxCellX) { - while (currCellY <= maxCellY) { - while (currCellZ <= maxCellZ) { - int currCellZ = this.currCellZ++; - - int cx = currCellX * cellSize; - int cy = currCellY * cellSize; - int cz = currCellZ * cellSize; - - boolean isCellInRange = isCellPotentiallyInRange(cx, cy, cz); - if (!isCellInRange) continue; - - long key = pack(currCellX, currCellY, currCellZ); - ObjectArrayList cell = grid.get(key); - if (cell != null && !cell.isEmpty()) { - currentCell = cell; - isEdgeCell = !isCellFullyInRange(cx, cy, cz); - currCellIdx = 0; - return true; - } - } - currCellZ = minCellZ; - currCellY++; - } - currCellY = minCellY; - currCellX++; - } - return false; - } - - private boolean findNextElementInCell() { - if (currentCell == null) return false; - while (currCellIdx < currentCell.size()) { - T candidate = currentCell.get(currCellIdx++); - if (!isEdgeCell || isEdgeElementInRange(candidate)) { - nextElement = candidate; - hasNextElement = true; - return true; - } - } - currentCell = null; - return false; - } - - private boolean isEdgeElementInRange(T candidate) { - positionExtractor.accept(scratch, candidate); - double dist = distanceMetric.distance(x, y, z, scratch.x, scratch.y, scratch.z); - return dist <= distanceCompared; - } - } -} diff --git a/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/space/ArrayProximityTest.java b/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/space/ArrayProximityTest.java new file mode 100644 index 00000000..1be91ff5 --- /dev/null +++ b/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/space/ArrayProximityTest.java @@ -0,0 +1,203 @@ +package com.gtnewhorizon.gtnhlib.test.datastructs.space; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.gtnewhorizon.gtnhlib.datastructs.space.ArrayProximityCheck4D; +import com.gtnewhorizon.gtnhlib.datastructs.space.ArrayProximityMap4D; +import com.gtnewhorizon.gtnhlib.datastructs.space.VolumeShape; + +class ArrayProximityTest { + + private ArrayProximityCheck4D sphereCheck; + private ArrayProximityCheck4D cubeCheck; + private ArrayProximityMap4D mapSphere; + private ArrayProximityMap4D mapCube; + + @BeforeEach + void setUp() { + sphereCheck = new ArrayProximityCheck4D(VolumeShape.SPHERE); + cubeCheck = new ArrayProximityCheck4D(VolumeShape.CUBE); + mapSphere = new ArrayProximityMap4D<>(VolumeShape.SPHERE); + mapCube = new ArrayProximityMap4D<>(VolumeShape.CUBE); + } + + @Test + void testPutAndIsInVolume() { + sphereCheck.put(0, 10, 10, 10, 5); + assertTrue(sphereCheck.isInRange(0, 10.0, 10.0, 10.0)); + assertFalse(sphereCheck.isInRange(0, 20.0, 20.0, 20.0)); + + cubeCheck.put(1, 0, 0, 0, 1); + assertTrue(cubeCheck.isInRange(1, 0.5, 0.5, 0.5)); + assertFalse(cubeCheck.isInRange(1, 3.0, 3.0, 3.0)); + } + + @Test + void testOverwriteRadius() { + sphereCheck.put(0, 5, 5, 5, 3); + assertTrue(sphereCheck.isInRange(0, 7.0, 5.0, 5.0)); + sphereCheck.put(0, 5, 5, 5, 1); + assertFalse(sphereCheck.isInRange(0, 7.0, 5.0, 5.0)); + + cubeCheck.put(0, 5, 5, 5, 3); + assertTrue(cubeCheck.isInRange(0, 7.0, 5.0, 5.0)); + cubeCheck.put(0, 5, 5, 5, 1); + assertFalse(cubeCheck.isInRange(0, 7.0, 5.0, 5.0)); + } + + @Test + void testRemoveVolume() { + sphereCheck.put(0, 2, 2, 2, 2); + assertTrue(sphereCheck.isInRange(0, 2.0, 2.0, 2.0)); + sphereCheck.remove(0, 2, 2, 2); + assertFalse(sphereCheck.isInRange(0, 2.0, 2.0, 2.0)); + + cubeCheck.put(0, 2, 2, 2, 2); + assertTrue(cubeCheck.isInRange(0, 2.0, 2.0, 2.0)); + cubeCheck.remove(0, 2, 2, 2); + assertFalse(cubeCheck.isInRange(0, 2.0, 2.0, 2.0)); + } + + @Test + void testSizeAndIsEmpty() { + assertTrue(sphereCheck.isEmpty()); + assertEquals(0, sphereCheck.size()); + sphereCheck.put(0, 1, 1, 1, 1); + sphereCheck.put(0, 2, 2, 2, 1); + assertFalse(sphereCheck.isEmpty()); + assertEquals(2, sphereCheck.size()); + sphereCheck.remove(0, 1, 1, 1); + sphereCheck.remove(0, 2, 2, 2); + assertTrue(sphereCheck.isEmpty()); + assertEquals(0, sphereCheck.size()); + + assertTrue(cubeCheck.isEmpty()); + assertEquals(0, cubeCheck.size()); + cubeCheck.put(0, 1, 1, 1, 1); + cubeCheck.put(0, 2, 2, 2, 1); + assertFalse(cubeCheck.isEmpty()); + assertEquals(2, cubeCheck.size()); + cubeCheck.remove(0, 1, 1, 1); + cubeCheck.remove(0, 2, 2, 2); + assertTrue(cubeCheck.isEmpty()); + assertEquals(0, cubeCheck.size()); + } + + @Test + void testMultipleDimensions() { + sphereCheck.put(0, 0, 0, 0, 2); + sphereCheck.put(1, 10, 10, 10, 3); + + assertTrue(sphereCheck.isInRange(0, 0.0, 0.0, 0.0)); + assertTrue(sphereCheck.isInRange(1, 10.0, 10.0, 10.0)); + assertFalse(sphereCheck.isInRange(2, 10.0, 10.0, 10.0)); + + assertEquals(2, sphereCheck.size()); + } + + @Test + void testRemoveNonexistentVolume() { + sphereCheck.put(0, 1, 1, 1, 1); + sphereCheck.remove(0, 9, 9, 9); + assertEquals(1, sphereCheck.size()); + } + + @Test + void testPutAndSize() { + mapSphere.put("A", 0, 10, 20, 30, 5); + assertEquals(1, mapSphere.size()); + mapSphere.put("B", 0, 15, 25, 35, 5); + assertEquals(2, mapSphere.size()); + } + + @Test + void testPutReplacesSameCoords() { + mapSphere.put("A", 0, 10, 20, 30, 5); + mapSphere.put("B", 0, 10, 20, 30, 10); + assertEquals(1, mapSphere.size()); + assertEquals("B", mapSphere.getClosest(0, 10.5, 20.5, 30.5)); + } + + @Test + void testRemoveExisting() { + mapSphere.put("A", 0, 10, 20, 30, 5); + String removed = mapSphere.remove(0, 10, 20, 30); + assertEquals("A", removed); + assertEquals(0, mapSphere.size()); + } + + @Test + void testRemoveNonexistent() { + assertNull(mapSphere.remove(0, 1, 2, 3)); + assertNull(mapCube.remove(0, 1, 2, 3)); + } + + @Test + void testIsInVolumeSphere() { + mapSphere.put("Center", 0, 10, 10, 10, 5); + assertTrue(mapSphere.isInRange(0, 10.5, 10.5, 10.5)); + assertFalse(mapSphere.isInRange(0, 20.0, 20.0, 20.0)); + } + + @Test + void testIsInVolumeCube() { + mapCube.put("Center", 0, 10, 10, 10, 5); + assertTrue(mapCube.isInRange(0, 11.0, 10.0, 9.0)); + assertFalse(mapCube.isInRange(0, 20.0, 20.0, 20.0)); + } + + @Test + void testGetClosestSphere() { + mapSphere.put("A", 0, 5, 5, 5, 3); + mapSphere.put("B", 0, 10, 10, 10, 3); + assertEquals("A", mapSphere.getClosest(0, 5.5, 5.5, 5.5)); + assertEquals("B", mapSphere.getClosest(0, 10.5, 10.5, 10.5)); + } + + @Test + void testGetClosestCube() { + mapCube.put("A", 0, 5, 5, 5, 20); + mapCube.put("B", 0, 10, 10, 10, 20); + assertEquals("A", mapCube.getClosest(0, 5.2, 5.2, 5.2)); + assertEquals("B", mapCube.getClosest(0, 10.3, 10.3, 10.3)); + } + + @Test + void testMultipleDimensionsMap() { + mapSphere.put("Dim0", 0, 1, 1, 1, 20); + assertTrue(mapSphere.isInRange(0, 1.5, 1.5, 1.5)); + assertFalse(mapSphere.isInRange(1, 1.5, 1.5, 1.5)); + mapSphere.put("Dim1", 1, 1, 1, 1, 20); + assertEquals("Dim1", mapSphere.getClosest(1, 1.5, 1.5, 1.5)); + } + + @Test + void testMultiRemove() { + mapSphere.put("A", 0, 0, 0, 0, 50); + mapSphere.put("B", 0, 10, 10, 10, 50); + mapSphere.put("C", 0, 10, 0, 10, 50); + mapSphere.put("D", 0, 10, -10, 10, 50); + mapSphere.put("E", 0, -10, -10, -10, 50); + + assertEquals(mapSphere.size(), 5); + assertEquals("D", mapSphere.getClosest(0, 11, -10, 10)); + + mapSphere.remove(0, 10, -10, 10); + assertEquals("C", mapSphere.getClosest(0, 11, -10, 10)); + mapSphere.remove(0, -10, -10, -10); + assertEquals(3, mapSphere.size()); + } + + @Test + void testIsEmptyAndClear() { + assertTrue(mapSphere.isEmpty()); + mapSphere.put("Something", 0, 1, 2, 3, 4); + assertFalse(mapSphere.isEmpty()); + mapSphere.clear(); + assertTrue(mapSphere.isEmpty()); + assertEquals(0, mapSphere.size()); + } +} diff --git a/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/SpatialHashGridTest.java b/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/SpatialHashGridTest.java deleted file mode 100644 index 5ccb834b..00000000 --- a/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/SpatialHashGridTest.java +++ /dev/null @@ -1,363 +0,0 @@ -package com.gtnewhorizon.gtnhlib.test.datastructs.spatialhashgrid; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.junit.jupiter.api.Test; - -import com.gtnewhorizon.gtnhlib.datastructs.spatialhashgrid.SpatialHashGrid; - -public class SpatialHashGridTest { - - @Test - void testInsertAndQuery() { - SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - TestObject obj = new TestObject(5, 5, 5); - grid.insert(obj); - - Collection results = grid.collectNearbyChebyshev(5, 5, 5, 1); - assertNotNull(results); - assertTrue(results.contains(obj)); - assertEquals(1, results.size()); - } - - @Test - void testInsertAndQueryFormula() { - SpatialHashGrid grid = new SpatialHashGrid<>(1, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - TestObject obj = new TestObject(5, 5, 5); - TestObject obj2 = new TestObject(1, 1, 1); - grid.insert(obj); - grid.insert(obj2); - - Collection results = grid.collectNearbyManhattan(5, 5, 5, 12); - - assertNotNull(results); - assertEquals(2, results.size()); - assertTrue(results.contains(obj)); - assertTrue(results.contains(obj2)); - } - - @Test - void testMultipleInserts() { - SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - TestObject obj1 = new TestObject(5, 5, 5); - TestObject obj2 = new TestObject(3, 3, 3); - grid.insert(obj1); - grid.insert(obj2); - - Collection results = grid.collectNearbyChebyshev(5, 5, 5, 10); - assertNotNull(results); - assertTrue(results.contains(obj1)); - assertTrue(results.contains(obj2)); - assertEquals(2, results.size()); - } - - @Test - void testEmptyGrid() { - SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - Collection results = grid.collectNearbyChebyshev(0, 0, 0, 10); - assertNotNull(results); - assertTrue(results.isEmpty()); - } - - @Test - void testNegativeCoordinates() { - SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - TestObject obj = new TestObject(-5, -5, -5); - grid.insert(obj); - - Collection results = grid.collectNearbyChebyshev(-5, -5, -5, 1); - assertNotNull(results); - assertTrue(results.contains(obj)); - assertEquals(1, results.size()); - } - - @Test - void testObjectMove() { - SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - TestObject obj = new TestObject(5, 5, 5); - grid.insert(obj); - - grid.remove(obj); - obj.x = 15; - grid.insert(obj); - - Collection results = grid.collectNearbyChebyshev(15, 5, 5, 1); - assertNotNull(results); - assertTrue(results.contains(obj)); - assertEquals(1, results.size()); - } - - @Test - void testClosest() { - SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - TestObject obj = new TestObject(5, 5, 5); - grid.insert(obj); - TestObject obj2 = new TestObject(10, 5, 5); - grid.insert(obj2); - - TestObject result = grid.findClosestChebyshev(9, 5, 5, 10); - assertNotNull(result); - assertEquals(result, obj2); - } - - @Test - void testFirst() { - SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - TestObject obj = new TestObject(5, 5, 5); - grid.insert(obj); - TestObject obj2 = new TestObject(10, 5, 5); - grid.insert(obj2); - - TestObject result = grid.findFirstNearbyChebyshev(6, 5, 5, 10); - assertNotNull(result); - assertEquals(result, obj); - } - - @Test - void testZeroRadiusIncludesExactMatch() { - SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - TestObject obj = new TestObject(1, 2, 3); - grid.insert(obj); - - List result = grid.collectNearbySquaredEuclidean(1, 2, 3, 0); - assertEquals(1, result.size()); - assertTrue(result.contains(obj)); - } - - @Test - void testOutsideRadiusExcluded() { - SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - TestObject obj = new TestObject(5, 5, 5); - grid.insert(obj); - - List result = grid.collectNearbySquaredEuclidean(5, 5, 5 + 2, 1); // too far (dist² = 4 > 1²) - assertTrue(result.isEmpty()); - } - - @Test - void testIteratorCorrectness() { - SpatialHashGrid grid = new SpatialHashGrid<>(2, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - TestObject obj = new TestObject(0, 0, 0); - grid.insert(obj); - - Iterator it = grid.iterNearbyWithMetric(0, 0, 0, 5, SpatialHashGrid.DistanceFormula.Manhattan); - assertTrue(it.hasNext()); - assertEquals(obj, it.next()); - assertFalse(it.hasNext()); - } - - @Test - void testMassInsertAndRemove() { - SpatialHashGrid grid = new SpatialHashGrid<>(3, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - List all = new ArrayList<>(); - for (int i = 0; i < 1000; i++) { - TestObject obj = new TestObject(i, i % 10, i % 5); - all.add(obj); - grid.insert(obj); - } - - for (TestObject obj : all) { - assertTrue(grid.collectNearbyChebyshev(obj.x, obj.y, obj.z, 0).contains(obj)); - grid.remove(obj); - } - - // Everything should now be gone - assertTrue(grid.collectNearbyChebyshev(0, 0, 0, 1000).isEmpty()); - } - - @Test - void testObjectsOnCellBoundaries() { - // cellSize = 5 means cells run [0..4], [5..9], etc. for non-negative coordinates. - SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - // Place objects exactly at (5,0,0) and (0,5,0) (both are cell boundaries). - TestObject onXBoundary = new TestObject(5, 0, 0); - TestObject onYBoundary = new TestObject(0, 5, 0); - grid.insert(onXBoundary); - grid.insert(onYBoundary); - - // Query at exactly (5,0,0) with radius=0 (Squared Euclidean) - Collection eucResults = grid.collectNearbySquaredEuclidean(5, 0, 0, 0); - assertTrue(eucResults.contains(onXBoundary)); - assertEquals(1, eucResults.size()); - - // Query at (4,0,0) with radius=1 (should include (5,0,0) in squared Euclidean) - eucResults = grid.collectNearbySquaredEuclidean(4, 0, 0, 1); - assertTrue(eucResults.contains(onXBoundary)); - assertFalse(eucResults.contains(onYBoundary)); - assertEquals(1, eucResults.size()); - - // Query at (5,1,0) with radius=1 Manhattan: |5−5|+|1−0|+|0−0|=1 => include onXBoundary - Collection manResults = grid.collectNearbyManhattan(5, 1, 0, 1); - assertTrue(manResults.contains(onXBoundary)); - assertFalse(manResults.contains(onYBoundary)); - - // Query at (1,5,0) with radius=1 Chebyshev: max(|1−0|,|5−5|,0)=1 => include onYBoundary - Collection chebResults = grid.collectNearbyChebyshev(1, 5, 0, 1); - assertTrue(chebResults.contains(onYBoundary)); - assertFalse(chebResults.contains(onXBoundary)); - } - - @Test - void testMetricDifference() { - SpatialHashGrid grid = new SpatialHashGrid<>(1, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - // Place a single object at (2,2,2) - TestObject obj = new TestObject(2, 2, 2); - grid.insert(obj); - - // Query from (0,0,0) with radius=3: - // ‣ Squared Euclidean: dist²(0→2) = 4+4+4 =12 → 12 > 9 → exclude - Collection sqResults = grid.collectNearbySquaredEuclidean(0, 0, 0, 3); - assertTrue(sqResults.isEmpty()); - - // ‣ Manhattan: |2|+|2|+|2| = 6 → 6 > 3 → exclude - Collection manResults = grid.collectNearbyManhattan(0, 0, 0, 3); - assertTrue(manResults.isEmpty()); - - // ‣ Chebyshev: max(|2|,|2|,|2|) = 2 → 2 ≤ 3 → include - Collection chebResults = grid.collectNearbyChebyshev(0, 0, 0, 3); - assertTrue(chebResults.contains(obj)); - assertEquals(1, chebResults.size()); - } - - @Test - void testZeroRadiusManhattanAndChebyshev() { - SpatialHashGrid grid = new SpatialHashGrid<>(2, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - TestObject exactly = new TestObject(4, 4, 4); - TestObject near1 = new TestObject(4, 5, 4); - TestObject near2 = new TestObject(3, 4, 4); - - grid.insert(exactly); - grid.insert(near1); - grid.insert(near2); - - // Radius 0 (Manhattan): only (4,4,4) has L1=0 - assertEquals(Collections.singleton(exactly), new HashSet<>(grid.collectNearbyManhattan(4, 4, 4, 0))); - - // Radius 0 (Chebyshev): only (4,4,4) has L∞=0 - assertEquals(Collections.singleton(exactly), new HashSet<>(grid.collectNearbyChebyshev(4, 4, 4, 0))); - } - - @Test - void testLargeRadiusSpanningManyCells() { - int cellSize = 10; - SpatialHashGrid grid = new SpatialHashGrid<>(cellSize, (pos, obj) -> { - pos.x = obj.x; - pos.y = obj.y; - pos.z = obj.z; - }); - - List inserted = new ArrayList<>(); - // Insert objects at (±i, 0, 0), for i from 0..50 - for (int i = -50; i <= 50; i += 10) { - TestObject o = new TestObject(i, 0, 0); - inserted.add(o); - grid.insert(o); - } - - // Query around (0,0,0) with radius = 45 (SquaredEuclidean means R²=2025) - // Only objects with |x| ≤ 45 should be included (i.e. at -40, -30, -20, -10, 0, 10, 20, 30, 40) - Collection eucResults = grid.collectNearbySquaredEuclidean(0, 0, 0, 45); - Set expected = new HashSet<>(); - for (TestObject o : inserted) { - if (o.x * o.x + o.y * o.y + o.z * o.z <= 45 * 45) { - expected.add(o); - } - } - assertEquals(expected, new HashSet<>(eucResults)); - - // Query Chebyshev with radius=25: that includes all objects with max(|x|,0,0) ≤ 25 → |x| ≤ 25 - Collection chebResults = grid.collectNearbyChebyshev(0, 0, 0, 25); - expected.clear(); - for (TestObject o : inserted) { - if (Math.abs(o.x) <= 25) expected.add(o); - } - assertEquals(expected.size(), chebResults.size()); - assertTrue(chebResults.containsAll(expected)); - } -} diff --git a/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/TestObject.java b/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/TestObject.java deleted file mode 100644 index 68a026cf..00000000 --- a/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/TestObject.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.gtnewhorizon.gtnhlib.test.datastructs.spatialhashgrid; - -public class TestObject { - - public int x, y, z; - - public TestObject(int x, int y, int z) { - this.x = x; - this.y = y; - this.z = z; - } - - @Override - public String toString() { - return "[" + x + ", " + y + ", " + z + "]"; - } -}