├── settings.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── renovate.json ├── jitpack.yml ├── .gitattributes ├── src ├── main │ └── java │ │ └── dev │ │ └── emortal │ │ └── rayfast │ │ ├── area │ │ ├── ResultImpl.java │ │ ├── area2d │ │ │ ├── Area2dLike.java │ │ │ ├── Area2dRectangleImpl.java │ │ │ ├── Area2dPolygon.java │ │ │ ├── Area2d.java │ │ │ └── Area2dRectangle.java │ │ ├── area3d │ │ │ ├── Area3dLike.java │ │ │ ├── Area3dRectangularPrismImpl.java │ │ │ ├── Area3d.java │ │ │ └── Area3dRectangularPrism.java │ │ ├── Area.java │ │ ├── Intersection.java │ │ └── IntersectionImpl.java │ │ ├── vector │ │ ├── Vector2dImpl.java │ │ ├── Vector3dImpl.java │ │ ├── Vector2d.java │ │ ├── Vector3d.java │ │ └── Vector.java │ │ ├── util │ │ ├── VectorMathUtil.java │ │ ├── FunctionalInterfaces.java │ │ ├── Converter.java │ │ ├── Intersection2dUtils.java │ │ └── Intersection3dUtils.java │ │ └── casting │ │ ├── combined │ │ ├── CombinedCastResult.java │ │ └── CombinedCast.java │ │ └── grid │ │ └── GridCast.java └── test │ └── java │ └── dev │ └── emortal │ └── rayfast │ └── test │ ├── examples │ ├── WikiExamples.java │ └── ExampleRaycastEntity.java │ ├── unit │ └── Intersection2dUtilsTest.java │ └── benchmarks │ └── RunBenchmarks.java ├── .gitignore ├── README.md ├── .github └── workflows │ └── maven.yaml ├── LICENSE ├── gradlew.bat └── gradlew /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "rayfast" 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/emortalmc/Rayfast/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:base" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /jitpack.yml: -------------------------------------------------------------------------------- 1 | before_install: 2 | - source "$HOME/.sdkman/bin/sdkman-init.sh" 3 | - sdk update 4 | - sdk install java 17-open 5 | - sdk use java 17-open -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | *.bat text eol=crlf 5 | *.sh text eol=lf 6 | gradlew text eol=lf 7 | 8 | *.jar binary 9 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/ResultImpl.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area; 2 | 3 | record ResultImpl(I intersection, I normal, A subject, double distance) implements Intersection.Result { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/area2d/Area2dLike.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area.area2d; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | public interface Area2dLike { 6 | @NotNull Area2d asArea2d(); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/area2d/Area2dRectangleImpl.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area.area2d; 2 | 3 | record Area2dRectangleImpl(double minX, double minY, double maxX, double maxY) implements Area2dRectangle { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/area3d/Area3dLike.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area.area3d; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | public interface Area3dLike { 6 | @NotNull Area3d asArea3d(); 7 | } 8 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/vector/Vector2dImpl.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.vector; 2 | 3 | record Vector2dImpl(double x, double y) implements Vector2d { 4 | 5 | @Override 6 | public String toString() { 7 | return "Vector2d(" + x + ", " + y + ")"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/vector/Vector3dImpl.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.vector; 2 | 3 | record Vector3dImpl(double x, double y, double z) implements Vector3d { 4 | @Override 5 | public String toString() { 6 | return "Vector3d(" + x + ", " + y + ", " + z + ")"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/area3d/Area3dRectangularPrismImpl.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area.area3d; 2 | 3 | record Area3dRectangularPrismImpl(double minX, double minY, double minZ, 4 | double maxX, double maxY, double maxZ) implements Area3dRectangularPrism { 5 | } 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | .idea/ 3 | /build/ 4 | 5 | # Ignore Gradle GUI config 6 | gradle-app.setting 7 | 8 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 9 | !gradle-wrapper.jar 10 | 11 | # Cache of project 12 | .gradletasknamecache 13 | 14 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 15 | # gradle/wrapper/gradle-wrapper.properties 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ##### NOTE: Rayfast is still in development and is not completely stable api-wise. GridCasting likely will not change, however Area3d's may have some improvements on the way. 2 | 3 | # 🚀 Rayfast 🚀 4 | A 🚀 wayfast 🚀 raycast ~~🚀Rust🚀~~ java library. 5 | 6 | See the [🚀 wiki 🚀](https://github.com/EmortalMC/Rayfast/wiki) for usage. 7 | Download and use via [Jitpack](https://jitpack.io/#EmortalMC/Rayfast) 8 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/util/VectorMathUtil.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.util; 2 | 3 | import dev.emortal.rayfast.vector.Vector3d; 4 | import org.jetbrains.annotations.ApiStatus; 5 | 6 | /** 7 | * Internal Vector Math Utils. 8 | * 9 | * INTERNAL ONLY. 10 | * If any issues arise using this class, that's on you. 11 | */ 12 | @ApiStatus.Internal 13 | public class VectorMathUtil { 14 | /** 15 | * Finds the distance between two vectors 16 | */ 17 | public static double distance(Vector3d a, Vector3d b) { 18 | return Math.sqrt(distanceSquared(a, b)); 19 | } 20 | 21 | public static double distanceSquared(Vector3d a, Vector3d b) { 22 | return Math.pow(b.x() - a.x(), 2) + Math.pow(b.y() - a.y(), 2) + Math.pow(b.z() - a.z(), 2); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/dev/emortal/rayfast/test/examples/WikiExamples.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.test.examples; 2 | 3 | import dev.emortal.rayfast.area.area3d.Area3d; 4 | import dev.emortal.rayfast.area.area3d.Area3dRectangularPrism; 5 | import dev.emortal.rayfast.vector.Vector3d; 6 | 7 | public class WikiExamples { 8 | public static void main(String[] args) { 9 | // Create a rectangular prism with random coordinates 10 | Area3d rectangularPrism = Area3dRectangularPrism.of( 11 | Math.random(), Math.random(), Math.random(), // Min position 12 | Math.random(), Math.random(), Math.random() // Max position 13 | ); 14 | 15 | // Cast a ray though it, and check if it was intersected 16 | Vector3d intersection = rectangularPrism.lineIntersection( 17 | Math.random(), Math.random(), Math.random(), // Line point 18 | Math.random(), Math.random(), Math.random() // Line direction 19 | ); 20 | 21 | System.out.println("Line Intersected: " + (intersection != null)); 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /.github/workflows/maven.yaml: -------------------------------------------------------------------------------- 1 | name: Publish to development (snapshot) repo 2 | on: push 3 | 4 | jobs: 5 | publish: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v3 9 | - name: Get Commit Hash 10 | id: commit 11 | uses: pr-mpt/actions-commit-hash@v2 12 | - name: Set up Java 13 | uses: actions/setup-java@v3 14 | with: 15 | java-version: '17' 16 | distribution: 'adopt' 17 | - name: Validate Gradle wrapper 18 | uses: gradle/wrapper-validation-action@ccb4328a959376b642e027874838f60f8e596de3 19 | - name: Publish package 20 | uses: gradle/gradle-build-action@680037c65b998d750280aefaffd22cd3560fc9db 21 | with: 22 | arguments: publishMavenPublicationToDevelopmentRepository 23 | env: 24 | MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} 25 | MAVEN_SECRET: ${{ secrets.MAVEN_SECRET }} 26 | COMMIT_HASH: ${{ steps.commit.outputs.hash }} 27 | COMMIT_HASH_SHORT: ${{ steps.commit.outputs.short }} 28 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/vector/Vector2d.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.vector; 2 | 3 | import dev.emortal.rayfast.util.Converter; 4 | 5 | import java.util.function.Function; 6 | 7 | /** 8 | * An immutable 2d vector 9 | */ 10 | public interface Vector2d extends Vector { 11 | Converter CONVERTER = new Converter<>(); 12 | 13 | double x(); 14 | double y(); 15 | 16 | @Override 17 | default int dimensions() { 18 | return 2; 19 | } 20 | 21 | @Override 22 | default double get(int index) { 23 | return switch (index) { 24 | case 0 -> x(); 25 | case 1 -> y(); 26 | default -> throw new IndexOutOfBoundsException(); 27 | }; 28 | } 29 | 30 | @Override 31 | default Vector2d with(double... values) { 32 | if (values.length != 2) { 33 | throw new IllegalArgumentException("Vector2d requires 2 values"); 34 | } 35 | return Vector2d.of(values[0], values[1]); 36 | } 37 | 38 | static Vector2d of(double x, double y) { 39 | return new Vector2dImpl(x, y); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 KrystilizeNevaDies 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/vector/Vector3d.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.vector; 2 | 3 | import dev.emortal.rayfast.util.Converter; 4 | 5 | import java.util.function.Function; 6 | 7 | public interface Vector3d extends Vector { 8 | Converter CONVERTER = new Converter<>(); 9 | 10 | double x(); 11 | double y(); 12 | double z(); 13 | 14 | @Override 15 | default int dimensions() { 16 | return 3; 17 | } 18 | 19 | @Override 20 | default double get(int index) { 21 | return switch (index) { 22 | case 0 -> x(); 23 | case 1 -> y(); 24 | case 2 -> z(); 25 | default -> throw new IllegalArgumentException("Index must be between 0 and 2"); 26 | }; 27 | } 28 | 29 | @Override 30 | default Vector3d with(double... values) { 31 | if (values.length != 3) { 32 | throw new IllegalArgumentException("Vector3d requires 3 values"); 33 | } 34 | return Vector3d.of(values[0], values[1], values[2]); 35 | } 36 | 37 | static Vector3d of(double x, double y, double z) { 38 | return new Vector3dImpl(x, y, z); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/util/FunctionalInterfaces.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.util; 2 | 3 | import dev.emortal.rayfast.area.area3d.Area3d; 4 | import dev.emortal.rayfast.vector.Vector2d; 5 | import dev.emortal.rayfast.vector.Vector3d; 6 | import org.jetbrains.annotations.ApiStatus; 7 | import org.jetbrains.annotations.NotNull; 8 | 9 | import java.util.Map; 10 | import java.util.function.Function; 11 | 12 | @ApiStatus.Internal 13 | public class FunctionalInterfaces { 14 | 15 | @FunctionalInterface 16 | public interface Vector3dToBoolean { 17 | boolean apply(@NotNull Vector3d vector3d); 18 | } 19 | 20 | @FunctionalInterface 21 | public interface Vector3dArea3dToBoolean { 22 | boolean apply(@NotNull Vector3d vector3d, @NotNull Area3d area3d); 23 | } 24 | 25 | @FunctionalInterface 26 | public interface DoubleWrapper { 27 | double get(@NotNull T object); 28 | } 29 | 30 | @FunctionalInterface 31 | public interface Lines2dWrapper extends Function> { 32 | } 33 | 34 | @FunctionalInterface 35 | public interface Lines3dWrapper extends Function> { 36 | } 37 | 38 | @FunctionalInterface 39 | public interface Vector3dWrapper extends Function { 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/casting/combined/CombinedCastResult.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.casting.combined; 2 | 3 | import dev.emortal.rayfast.vector.Vector3d; 4 | import org.jetbrains.annotations.NotNull; 5 | import org.jetbrains.annotations.Nullable; 6 | 7 | public interface CombinedCastResult { 8 | 9 | class HitResult { 10 | 11 | private final Object subject; 12 | private final HitType type; 13 | private final Vector3d position; 14 | private final double distanceSquared; 15 | 16 | public HitResult( 17 | @Nullable Object subject, 18 | @NotNull HitType type, 19 | @NotNull Vector3d position, 20 | double distanceSquared 21 | ) { 22 | this.subject = subject; 23 | this.type = type; 24 | this.position = position; 25 | this.distanceSquared = distanceSquared; 26 | } 27 | 28 | @SuppressWarnings("unchecked") 29 | public @NotNull R subject() { 30 | if (subject == null) 31 | throw new IllegalStateException("Subject was null"); 32 | return (R) subject; 33 | } 34 | 35 | public @NotNull HitType type() { 36 | return type; 37 | } 38 | 39 | public @NotNull Vector3d position() { 40 | return position; 41 | } 42 | 43 | public double distanceSquared() { 44 | return distanceSquared; 45 | } 46 | } 47 | 48 | enum HitType { 49 | GRIDUNIT, 50 | AREA3D 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/Area.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area; 2 | 3 | import dev.emortal.rayfast.area.area2d.Area2d; 4 | import dev.emortal.rayfast.vector.Vector; 5 | import dev.emortal.rayfast.vector.Vector2d; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.jetbrains.annotations.Nullable; 8 | 9 | import java.util.Collection; 10 | 11 | public interface Area> { 12 | 13 | //////////////////// 14 | // Contains point // 15 | //////////////////// 16 | 17 | // This intersection option is used to find whether the area contains this point 18 | Intersection>> ALL_FORWARDS = Intersection.builder() 19 | .area2d() 20 | .forwards() 21 | .all() 22 | .none(); 23 | 24 | /** 25 | * Returns true if the specified point is inside this area 26 | * @param point the point 27 | * @return true if the point is inside this area, false otherwise 28 | */ 29 | boolean containsPoint(@NotNull V point); 30 | 31 | /////////////////////// 32 | // Line intersection // 33 | /////////////////////// 34 | 35 | /** 36 | * Returns the specified intersection result if a line intersection was done with this area. 37 | * 38 | * @param pos the start position of the line 39 | * @param dir the direction of the line 40 | * @param intersection the specified intersection result to return 41 | * @param the intersection result type 42 | * @return the intersection result 43 | */ 44 | @Nullable R lineIntersection(@NotNull V pos, @NotNull V dir, @NotNull Intersection intersection); 45 | 46 | double area(); 47 | @Deprecated(forRemoval = true) 48 | default double size() { 49 | return area(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/util/Converter.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.util; 2 | 3 | import java.util.Map; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | import java.util.function.Function; 6 | 7 | /** 8 | * Used to generate converters of specified types 9 | * 10 | * @param 11 | */ 12 | public class Converter { 13 | 14 | public Converter() {} 15 | 16 | private final Map, Function> convertingFunctions = new ConcurrentHashMap<>(); 17 | 18 | /** 19 | * Registers a conversion function for a specific class 20 | * 21 | * @param clazz the class of the converter function 22 | * @param converterFunction the converter function 23 | * @param the class 24 | */ 25 | public void register(Class clazz, Function converterFunction) { 26 | convertingFunctions.put(clazz, converterFunction); 27 | } 28 | 29 | 30 | /** 31 | * Converts an object to another. 32 | *

33 | * The object needs to have a registered converting function. These 34 | * functions can be registered using #register 35 | */ 36 | @SuppressWarnings("unchecked") 37 | public C from(T object) { 38 | 39 | final Class originalClazz = object.getClass(); 40 | Class clazz = originalClazz; 41 | 42 | while (clazz != null) { 43 | 44 | Function convertingFunction = (Function) convertingFunctions.get(clazz); 45 | 46 | if (convertingFunction != null) { 47 | if (clazz != originalClazz) { 48 | convertingFunctions.put(originalClazz, convertingFunction); 49 | } 50 | 51 | return convertingFunction.apply(object); 52 | } 53 | 54 | clazz = clazz.getSuperclass(); 55 | } 56 | 57 | assert originalClazz != null; 58 | throw new IllegalArgumentException(originalClazz.getName() + " object provided to Converter#from did not have a registered converter"); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/dev/emortal/rayfast/test/unit/Intersection2dUtilsTest.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.test.unit; 2 | 3 | import dev.emortal.rayfast.area.Intersection; 4 | import dev.emortal.rayfast.area.area2d.Area2d; 5 | import dev.emortal.rayfast.area.area2d.Area2dRectangle; 6 | import dev.emortal.rayfast.util.Intersection2dUtils; 7 | import dev.emortal.rayfast.vector.Vector2d; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.TestInstance; 10 | 11 | import static org.junit.jupiter.api.Assertions.*; 12 | 13 | class Intersection2dUtilsTest { 14 | @Test 15 | public void testIntersection() { 16 | assertIntersection(Vector2d.of(0, 0), Vector2d.of(1, 0), 17 | Vector2d.of(3, -1), Vector2d.of(3, 1), 18 | Vector2d.of(3, 0)); 19 | assertIntersection(Vector2d.of(0, 0), Vector2d.of(-1, 0), 20 | Vector2d.of(-3, -1), Vector2d.of(-3, 1), 21 | Vector2d.of(-3, 0)); 22 | assertIntersection(Vector2d.of(0, 0), Vector2d.of(0, 1), 23 | Vector2d.of(-1, 3), Vector2d.of(1, 3), 24 | Vector2d.of(0, 3)); 25 | assertIntersection(Vector2d.of(0, 0), Vector2d.of(0, -1), 26 | Vector2d.of(-1, -3), Vector2d.of(1, -3), 27 | Vector2d.of(0, -3)); 28 | } 29 | 30 | private void assertIntersection(Vector2d lineAStart, Vector2d lineADir, Vector2d lineBStart, Vector2d lineBDir, Vector2d result) { 31 | Area2d area = Area2d.combined(); 32 | var intersectionResult = Intersection2dUtils.lineIntersection(area, Intersection.Direction.ANY, 33 | lineAStart.x(), lineAStart.y(), 34 | lineADir.x(), lineADir.y(), 35 | lineBStart.x(), lineBStart.y(), 36 | lineBDir.x(), lineBDir.y()); 37 | 38 | Vector2d intersection = intersectionResult.intersection(); 39 | 40 | assertEquals(result.x(), intersection.x(), 0.00001); 41 | assertEquals(result.y(), intersection.y(), 0.00001); 42 | } 43 | } -------------------------------------------------------------------------------- /src/test/java/dev/emortal/rayfast/test/examples/ExampleRaycastEntity.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.test.examples; 2 | 3 | import dev.emortal.rayfast.area.area3d.Area3d; 4 | import dev.emortal.rayfast.area.area3d.Area3dLike; 5 | import dev.emortal.rayfast.area.area3d.Area3dRectangularPrism; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | /** 9 | * An example usage of an entity with a bounding box. 10 | *

11 | * As the entity position changes while the bounding box stays the same, this can be used for multiple raycasts 12 | * consecutively with no overhead. 13 | *

14 | * This is an ideal situation for mutable shapes in rayfast. 15 | */ 16 | public abstract class ExampleRaycastEntity implements Area3dLike { 17 | 18 | public abstract BoundingBox getBoundingBox(); 19 | 20 | @Override 21 | public @NotNull Area3d asArea3d() { 22 | return getBoundingBox(); 23 | } 24 | 25 | public abstract double getX(); 26 | public abstract double getY(); 27 | public abstract double getZ(); 28 | 29 | public static class BoundingBox implements Area3dRectangularPrism { 30 | 31 | private final ExampleRaycastEntity exampleRaycastEntity; 32 | private final double halfWidth; 33 | private final double halfHeight; 34 | private final double halfDepth; 35 | 36 | public BoundingBox(ExampleRaycastEntity exampleRaycastEntity, double width, double height, double depth) { 37 | this.exampleRaycastEntity = exampleRaycastEntity; 38 | this.halfWidth = width / 2.0; 39 | this.halfHeight = height / 2.0; 40 | this.halfDepth = depth / 2.0; 41 | } 42 | 43 | // Coordinates 44 | public double minX() { 45 | return exampleRaycastEntity.getX() - halfWidth; 46 | } 47 | 48 | public double minY() { 49 | return exampleRaycastEntity.getY() - halfHeight; 50 | } 51 | 52 | public double minZ() { 53 | return exampleRaycastEntity.getZ() - halfDepth; 54 | } 55 | 56 | public double maxX() { 57 | return exampleRaycastEntity.getX() + halfWidth; 58 | } 59 | 60 | public double maxY() { 61 | return exampleRaycastEntity.getY() + halfHeight; 62 | } 63 | 64 | public double maxZ() { 65 | return exampleRaycastEntity.getZ() + halfDepth; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/area2d/Area2dPolygon.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area.area2d; 2 | 3 | import dev.emortal.rayfast.area.Intersection; 4 | import dev.emortal.rayfast.util.FunctionalInterfaces; 5 | import dev.emortal.rayfast.util.Intersection2dUtils; 6 | import dev.emortal.rayfast.vector.Vector2d; 7 | import org.jetbrains.annotations.ApiStatus; 8 | import org.jetbrains.annotations.NotNull; 9 | 10 | import java.util.Map; 11 | import java.util.stream.Collectors; 12 | 13 | /** 14 | * Represents a 2d polygon 15 | */ 16 | public interface Area2dPolygon extends Area2d { 17 | 18 | Map lines(); 19 | 20 | @Override 21 | @ApiStatus.Internal 22 | @SuppressWarnings("unchecked") 23 | default @NotNull R lineIntersection(double posX, double posY, double dirX, double dirY, @NotNull Intersection intersection) { 24 | Intersection.Direction direction = intersection.direction(); 25 | Intersection.Orderer> orderer = 26 | (Intersection.Orderer>) intersection.orderer(); 27 | 28 | final double posXb = dirX + posX; 29 | final double posYb = dirY + posY; 30 | 31 | return switch (intersection.collector()) { 32 | case SINGLE -> (R) lines().entrySet().stream() 33 | .map(entry -> { 34 | Vector2d pos1 = entry.getKey(); 35 | Vector2d pos2 = entry.getValue(); 36 | 37 | return Intersection2dUtils.lineIntersection( 38 | this, 39 | direction, 40 | 41 | posX, posY, 42 | posXb, posYb, 43 | 44 | pos1.x(), pos1.y(), 45 | pos2.x(), pos2.y() 46 | ); 47 | }) 48 | .min(orderer) 49 | .orElseGet(() -> Intersection.Result.none(this)); 50 | case ALL -> (R) lines().entrySet() 51 | .stream() 52 | .map(entry -> { 53 | Vector2d pos1 = entry.getKey(); 54 | Vector2d pos2 = entry.getValue(); 55 | 56 | return Intersection2dUtils.lineIntersection( 57 | this, 58 | direction, 59 | 60 | posX, posY, 61 | posXb, posYb, 62 | 63 | pos1.x(), pos1.y(), 64 | pos2.x(), pos2.y() 65 | ); 66 | }) 67 | .sorted(orderer) 68 | .collect(Collectors.toList()); 69 | }; 70 | } 71 | 72 | /** 73 | * Generates a wrapper for the specified object using the specified getters. 74 | *

75 | * This is a suboptimal implementation. An ideal implementation implements the 76 | * Area2dPolygon interface directly on the object. 77 | * 78 | * @param object the object to wrap 79 | * @param linesGetter the getter for the lines 80 | * @param the type of the wrapped object 81 | * @return the area that is represented by this wrapped object 82 | */ 83 | static Area2d wrapper(T object, FunctionalInterfaces.Lines2dWrapper linesGetter) { 84 | return (Area2dPolygon) () -> linesGetter.apply(object); 85 | } 86 | 87 | @Override 88 | default double area() { 89 | Map lines = lines(); 90 | double area = 0; 91 | for (Map.Entry entry : lines.entrySet()) { 92 | Vector2d pos1 = entry.getKey(); 93 | Vector2d pos2 = entry.getValue(); 94 | area += pos1.x() * (pos2.y() - pos1.y()) + pos2.x() * (pos1.y() - pos2.y()); 95 | } 96 | area /= 2; 97 | return area; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/Intersection.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area; 2 | 3 | import dev.emortal.rayfast.area.area2d.Area2d; 4 | import dev.emortal.rayfast.area.area3d.Area3d; 5 | import dev.emortal.rayfast.vector.Vector; 6 | import dev.emortal.rayfast.vector.Vector2d; 7 | import dev.emortal.rayfast.vector.Vector3d; 8 | import org.jetbrains.annotations.ApiStatus; 9 | import org.jetbrains.annotations.NotNull; 10 | import org.jetbrains.annotations.Nullable; 11 | 12 | import java.util.Collection; 13 | import java.util.Comparator; 14 | import java.util.List; 15 | 16 | /** 17 | * Represents a filter of an Intersection 18 | * @param 19 | */ 20 | public interface Intersection { 21 | 22 | Intersection> ANY_2D = Intersection.builder() 23 | .area2d() 24 | .any() 25 | .any(); 26 | 27 | Intersection> ANY_3D = Intersection.builder() 28 | .area3d() 29 | .any() 30 | .any(); 31 | 32 | static @NotNull Builder.Start builder() { 33 | return IntersectionImpl.builder(); 34 | } 35 | 36 | 37 | @ApiStatus.Internal 38 | Collector collector(); 39 | @ApiStatus.Internal 40 | Direction direction(); 41 | 42 | Orderer orderer(); 43 | 44 | @ApiStatus.Internal 45 | enum Collector { 46 | // TODO: FIRST, LAST 47 | SINGLE, 48 | ALL 49 | } 50 | 51 | @ApiStatus.Internal 52 | enum Direction { 53 | ANY, 54 | FORWARDS, 55 | BACKWARDS 56 | } 57 | 58 | interface Orderer extends Comparator { 59 | Orderer>> DISTANCE = (a, b) -> { 60 | double distA = a.distance(); 61 | double distB = b.distance(); 62 | return Double.compare(distA, distB); 63 | }; 64 | 65 | Orderer, ?>> SIZE = (a, b) -> { 66 | Area sizeA = a.subject(); 67 | Area sizeB = b.subject(); 68 | return Double.compare(sizeA.area(), sizeB.area()); 69 | }; 70 | 71 | Orderer NONE = (a, b) -> 0; 72 | } 73 | 74 | interface Builder { 75 | interface Start { 76 | Direction area2d(); 77 | Direction area3d(); 78 | Direction vector2d(); 79 | Direction vector3d(); 80 | } 81 | 82 | interface Direction { 83 | Collector any(); 84 | Collector forwards(); 85 | Collector backwards(); 86 | } 87 | 88 | interface Collector { 89 | Intersection> any(); 90 | Order> first(); 91 | Order> last(); 92 | 93 | AllOrder> all(); 94 | } 95 | 96 | interface Order { 97 | Intersection distance(); 98 | Intersection size(); 99 | } 100 | 101 | interface AllOrder extends Order> { 102 | Intersection> none(); 103 | } 104 | } 105 | 106 | /** 107 | * The result of an intersection. 108 | * @param the area(s) of the intersection 109 | * @param the intersection 110 | */ 111 | interface Result { 112 | static Result none(A area) { 113 | return new ResultImpl<>(null, null, area, Double.NaN); 114 | } 115 | 116 | /** 117 | * The intersection between the two objects. 118 | * @return The intersection between the two objects. 119 | */ 120 | @Nullable I intersection(); 121 | 122 | /** 123 | * The normal (perpendicular) object of the intersection. 124 | * @return The normal (perpendicular) object of the intersection. 125 | */ 126 | @ApiStatus.Experimental 127 | I normal(); 128 | 129 | /** 130 | * The subject(s) of the intersection. 131 | * @return The subject(s) of the intersection. 132 | */ 133 | @ApiStatus.Experimental 134 | A subject(); 135 | 136 | /** 137 | * The distance between the start of the ray and the intersection. 138 | * @return The distance between the start of the ray and the intersection. Double.NaN if no intersection. 139 | */ 140 | double distance(); 141 | 142 | static Result of(@Nullable I intersection, I normal, A subject, double distance) { 143 | return new ResultImpl<>(intersection, normal, subject, distance); 144 | } 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/util/Intersection2dUtils.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.util; 2 | 3 | 4 | import dev.emortal.rayfast.area.Intersection; 5 | import dev.emortal.rayfast.area.area2d.Area2d; 6 | import dev.emortal.rayfast.vector.Vector; 7 | import dev.emortal.rayfast.vector.Vector2d; 8 | import dev.emortal.rayfast.vector.Vector3d; 9 | import org.jetbrains.annotations.ApiStatus; 10 | import org.jetbrains.annotations.NotNull; 11 | import org.jetbrains.annotations.Nullable; 12 | 13 | /** 14 | * Internal Intersection Utils. 15 | * 16 | * INTERNAL ONLY. 17 | * If any issues arise using this class, that's on you. 18 | */ 19 | @ApiStatus.Internal 20 | public class Intersection2dUtils { 21 | 22 | private static class IncompleteResult { 23 | Vector2d start; 24 | Vector2d direction; 25 | @Nullable Vector2d intersection; 26 | @Nullable Vector2d normal; 27 | } 28 | 29 | private static final ThreadLocal THREAD_LOCAL = ThreadLocal.withInitial(IncompleteResult::new); 30 | 31 | /* 32 | A line intersection bounded by the intersecting line points 33 | */ 34 | 35 | /** 36 | * 37 | * @param direction the direction 38 | * 39 | * @param a the x of line A, point 1 40 | * @param b the y of line A, point 1 41 | * @param c the x of line A, point 2 42 | * @param d the y of line A, point 2 43 | * 44 | * @param e the x of line B, point 1 45 | * @param f the y of line B, point 1 46 | * @param g the x of line B, point 2 47 | * @param h the y of line B, point 2 48 | * 49 | * @return the intersection 50 | */ 51 | @ApiStatus.Internal 52 | public static @NotNull Intersection.Result lineIntersection( 53 | A area, 54 | Intersection.Direction direction, 55 | 56 | // Source Line 57 | double a, double b, 58 | double c, double d, 59 | 60 | // Intersecting Line (Bounded) 61 | double e, double f, 62 | double g, double h 63 | ) { 64 | IncompleteResult result = THREAD_LOCAL.get(); 65 | result.start = Vector2d.of(a, b); 66 | result.direction = Vector2d.of(c, d); 67 | 68 | // Find x & y 69 | double s1_x = c - a; 70 | double s1_y = d - b; 71 | double s2_x = g - e; 72 | double s2_y = h - f; 73 | 74 | double v = -s2_x * s1_y + s1_x * s2_y; 75 | double s = (-s1_y * (a - e) + s1_x * (b - f)) / v; 76 | double t = ( s2_x * (b - f) - s2_y * (a - e)) / v; 77 | 78 | double x = a + (t * s1_x); 79 | double y = b + (t * s1_y); 80 | 81 | if (s == Double.NEGATIVE_INFINITY || s == Double.POSITIVE_INFINITY || Double.isNaN(s) || 82 | t == Double.NEGATIVE_INFINITY || t == Double.POSITIVE_INFINITY || Double.isNaN(t)) { 83 | return Intersection.Result.none(area); 84 | } 85 | 86 | // Find the normal 87 | final double normalX = -(d - b); 88 | final double normalY = a - c; 89 | 90 | // Find the distance between the start and end 91 | Vector2d start = result.start; 92 | Vector2d end = Vector2d.of(x, y); 93 | 94 | double distX = start.x() - end.x(); 95 | double distY = start.y() - end.y(); 96 | double dist = Math.sqrt(distX * distX + distY * distY); 97 | 98 | result.intersection = end; 99 | result.normal = Vector2d.of(normalX, normalY); 100 | 101 | // Assert that intersection was in bounds set by second line 102 | if (isNotBetweenUnordered(x, e, g)) { 103 | return Intersection.Result.none(area); 104 | } 105 | 106 | if (isNotBetweenUnordered(y, f, h)) { 107 | return Intersection.Result.none(area); 108 | } 109 | 110 | if (direction == Intersection.Direction.ANY) { 111 | return Intersection.Result.of(result.intersection, result.normal, area, dist); 112 | } 113 | 114 | // Determine if the direction is correct 115 | double dotProduct = (c - a) * (x - a) + (d - b) * (y - b); 116 | 117 | if (direction == Intersection.Direction.FORWARDS) { 118 | if (dotProduct < 0) { 119 | return Intersection.Result.none(area); 120 | } 121 | } else { 122 | if (dotProduct > 0) { 123 | return Intersection.Result.none(area); 124 | } 125 | } 126 | 127 | return Intersection.Result.of(result.intersection, result.normal, area, dist); 128 | } 129 | 130 | // Returns 1 if the lines intersect, otherwise 0. In addition, if the lines 131 | // intersect the intersection point may be stored in the floats i_x and i_y. 132 | 133 | @ApiStatus.Internal 134 | private static boolean isNotBetweenUnordered(double number, double compare1, double compare2) { 135 | if (compare1 > compare2) { 136 | return !(number >= compare2) || !(number <= compare1); 137 | } 138 | return !(number >= compare1) || !(number <= compare2); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/IntersectionImpl.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area; 2 | 3 | import dev.emortal.rayfast.area.area2d.Area2d; 4 | import dev.emortal.rayfast.area.area3d.Area3d; 5 | import dev.emortal.rayfast.vector.Vector2d; 6 | import dev.emortal.rayfast.vector.Vector3d; 7 | 8 | import java.util.Collection; 9 | import java.util.List; 10 | 11 | record IntersectionImpl(Collector collector, Direction direction, 12 | Orderer> orderer) implements Intersection> { 13 | 14 | private IntersectionImpl(BuilderImpl builder) { 15 | //noinspection unchecked 16 | this(builder.collector, builder.direction, (Orderer>) builder.orderer); 17 | } 18 | 19 | static Builder.Start builder() { 20 | return new BuilderStartImpl(); 21 | } 22 | 23 | 24 | private static class BuilderStartImpl implements Builder.Start { 25 | @Override 26 | public Builder.Direction area2d() { 27 | return new BuilderImpl().direction(); 28 | } 29 | 30 | @Override 31 | public Builder.Direction area3d() { 32 | return new BuilderImpl().direction(); 33 | } 34 | 35 | @Override 36 | public Builder.Direction vector2d() { 37 | return new BuilderImpl().direction(); 38 | } 39 | 40 | @Override 41 | public Builder.Direction vector3d() { 42 | return new BuilderImpl().direction(); 43 | } 44 | } 45 | 46 | private static class BuilderImpl { 47 | 48 | private Collector collector = Collector.SINGLE; 49 | private Direction direction = Direction.ANY; 50 | private Orderer orderer = Orderer.NONE; 51 | 52 | private BuilderImpl() { 53 | } 54 | 55 | private Builder.Direction direction() { 56 | return new BuilderDirection<>(); 57 | } 58 | 59 | private Builder.Collector collector() { 60 | return new BuilderCollector<>(); 61 | } 62 | 63 | private Builder.Order order() { 64 | return new BuilderOrder<>(); 65 | } 66 | 67 | private Builder.AllOrder allOrder() { 68 | return new BuilderAllOrder<>(); 69 | } 70 | 71 | private class BuilderDirection implements Builder.Direction { 72 | @Override 73 | public Builder.Collector any() { 74 | direction = Direction.ANY; 75 | return collector(); 76 | } 77 | 78 | @Override 79 | public Builder.Collector forwards() { 80 | direction = Direction.FORWARDS; 81 | return collector(); 82 | } 83 | 84 | @Override 85 | public Builder.Collector backwards() { 86 | direction = Direction.BACKWARDS; 87 | return collector(); 88 | } 89 | } 90 | 91 | private class BuilderCollector implements Builder.Collector { 92 | 93 | @Override 94 | public Intersection> any() { 95 | collector = Collector.SINGLE; 96 | return new IntersectionImpl<>(BuilderImpl.this); 97 | } 98 | 99 | @Override 100 | public Builder.Order> first() { 101 | // TODO: FIRST 102 | collector = Collector.SINGLE; 103 | return order(); 104 | } 105 | 106 | @Override 107 | public Builder.Order> last() { 108 | // TODO: LAST 109 | collector = Collector.SINGLE; 110 | return order(); 111 | } 112 | 113 | @Override 114 | public Builder.AllOrder> all() { 115 | collector = Collector.ALL; 116 | return allOrder(); 117 | } 118 | } 119 | 120 | private class BuilderOrder implements Builder.Order { 121 | @Override 122 | public Intersection distance() { 123 | orderer = Orderer.DISTANCE; 124 | //noinspection unchecked 125 | return (Intersection) new IntersectionImpl<>(BuilderImpl.this); 126 | } 127 | 128 | @Override 129 | public Intersection size() { 130 | orderer = Orderer.SIZE; 131 | //noinspection unchecked 132 | return (Intersection) new IntersectionImpl<>(BuilderImpl.this); 133 | } 134 | } 135 | 136 | private class BuilderAllOrder implements Builder.AllOrder { 137 | @Override 138 | public Intersection> none() { 139 | orderer = Orderer.NONE; 140 | //noinspection unchecked 141 | return (Intersection>) (Object) new IntersectionImpl<>(BuilderImpl.this); 142 | } 143 | 144 | @Override 145 | public Intersection> distance() { 146 | orderer = Orderer.DISTANCE; 147 | //noinspection unchecked 148 | return (Intersection>) (Object) new IntersectionImpl<>(BuilderImpl.this); 149 | } 150 | 151 | @Override 152 | public Intersection> size() { 153 | orderer = Orderer.SIZE; 154 | //noinspection unchecked 155 | return (Intersection>) (Object) new IntersectionImpl<>(BuilderImpl.this); 156 | } 157 | } 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/vector/Vector.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.vector; 2 | 3 | import java.util.function.Function; 4 | 5 | /** 6 | * Represents an immutable vector with n-dimensions 7 | */ 8 | public interface Vector> { 9 | 10 | /** 11 | * Returns the number of dimensions 12 | * @return the number of dimensions 13 | */ 14 | int dimensions(); 15 | 16 | /** 17 | * Returns the value of the specified dimension 18 | * @param dimension the dimension 19 | * @return the value of the specified dimension 20 | */ 21 | double get(int dimension); 22 | 23 | /** 24 | * Creates a new vector with the specified values 25 | * @param values the values 26 | * @return a new vector with the specified values 27 | */ 28 | V with(double... values); 29 | 30 | /** 31 | * Returns the sum of this vector and the specified vector 32 | * @param v the vector 33 | * @return the sum of this vector and the specified vector 34 | */ 35 | default V add(V v) { 36 | // Add all the values 37 | double[] values = new double[dimensions()]; 38 | for (int i = 0; i < values.length; i++) { 39 | values[i] = get(i) + v.get(i); 40 | } 41 | // Return the new vector 42 | return with(values); 43 | } 44 | 45 | /** 46 | * Returns the difference of this vector and the specified vector 47 | * @param v the vector 48 | * @return the difference of this vector and the specified vector 49 | */ 50 | default V subtract(V v) { 51 | // Subtract all the values 52 | double[] values = new double[dimensions()]; 53 | for (int i = 0; i < values.length; i++) { 54 | values[i] = get(i) - v.get(i); 55 | } 56 | // Return the new vector 57 | return with(values); 58 | } 59 | 60 | /** 61 | * Returns the product of this vector and the specified vector 62 | * @param v the vector 63 | * @return the product of this vector and the specified vector 64 | */ 65 | default V multiply(V v) { 66 | // Multiply all the values 67 | double[] values = new double[dimensions()]; 68 | for (int i = 0; i < values.length; i++) { 69 | values[i] = get(i) * v.get(i); 70 | } 71 | // Return the new vector 72 | return with(values); 73 | } 74 | 75 | /** 76 | * Returns the quotient of this vector and the specified vector 77 | * @param v the vector 78 | * @return the quotient of this vector and the specified vector 79 | */ 80 | default V divide(V v) { 81 | // Divide all the values 82 | double[] values = new double[dimensions()]; 83 | for (int i = 0; i < values.length; i++) { 84 | values[i] = get(i) / v.get(i); 85 | } 86 | // Return the new vector 87 | return with(values); 88 | } 89 | 90 | /** 91 | * Returns the scalar product of this vector and the specified vector 92 | * @param v the vector 93 | * @return the scalar product of this vector and the specified vector 94 | */ 95 | default double dot(V v) { 96 | // Multiply all the values 97 | double result = 0; 98 | for (int i = 0; i < dimensions(); i++) { 99 | result += get(i) * v.get(i); 100 | } 101 | // Return the new vector 102 | return result; 103 | } 104 | 105 | /** 106 | * Returns the magnitude of this vector 107 | * @return the magnitude of this vector 108 | */ 109 | default double magnitude() { 110 | // Multiply all the values 111 | double result = 0; 112 | for (int i = 0; i < dimensions(); i++) { 113 | result += get(i) * get(i); 114 | } 115 | // Return the new vector 116 | return Math.sqrt(result); 117 | } 118 | 119 | /** 120 | * Returns the unit vector of this vector 121 | * @return the unit vector of this vector 122 | */ 123 | default V unit() { 124 | // Multiply all the values 125 | double[] values = new double[dimensions()]; 126 | for (int i = 0; i < values.length; i++) { 127 | values[i] = get(i) / magnitude(); 128 | } 129 | // Return the new vector 130 | return with(values); 131 | } 132 | 133 | /** 134 | * Returns the projection of this vector onto the specified vector 135 | * @param v the vector 136 | * @return the projection of this vector onto the specified vector 137 | */ 138 | default V project(V v) { 139 | // Multiply all the values 140 | double[] values = new double[dimensions()]; 141 | for (int i = 0; i < values.length; i++) { 142 | values[i] = get(i) * dot(v) / dot(v); 143 | } 144 | // Return the new vector 145 | return with(values); 146 | } 147 | 148 | /** 149 | * Returns the rejection of this vector onto the specified vector 150 | * @param v the vector 151 | * @return the rejection of this vector onto the specified vector 152 | */ 153 | default V reject(V v) { 154 | // Multiply all the values 155 | double[] values = new double[dimensions()]; 156 | for (int i = 0; i < values.length; i++) { 157 | values[i] = get(i) - dot(v) / dot(v); 158 | } 159 | // Return the new vector 160 | return with(values); 161 | } 162 | 163 | /** 164 | * Returns the cross product of this vector and the specified vector 165 | * @param v the vector 166 | * @return the cross product of this vector and the specified vector 167 | */ 168 | default V cross(V v) { 169 | // Multiply all the values 170 | double[] values = new double[dimensions()]; 171 | for (int i = 0; i < values.length; i++) { 172 | values[i] = get(i) * v.get(i); 173 | } 174 | // Return the new vector 175 | return with(values); 176 | } 177 | 178 | /** 179 | * Converts this vector to a string 180 | * @return the string 181 | */ 182 | default String asString() { 183 | // Create the string 184 | StringBuilder sb = new StringBuilder(); 185 | sb.append("("); 186 | for (int i = 0; i < dimensions(); i++) { 187 | sb.append(get(i)); 188 | if (i < dimensions() - 1) { 189 | sb.append(", "); 190 | } 191 | } 192 | sb.append(")"); 193 | // Return the string 194 | return sb.toString(); 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/area2d/Area2d.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area.area2d; 2 | 3 | import dev.emortal.rayfast.area.Area; 4 | import dev.emortal.rayfast.area.Intersection; 5 | import dev.emortal.rayfast.util.Converter; 6 | import dev.emortal.rayfast.vector.Vector2d; 7 | import org.jetbrains.annotations.NotNull; 8 | 9 | import java.util.Collection; 10 | import java.util.List; 11 | import java.util.stream.Collectors; 12 | 13 | public interface Area2d extends Area, Area2dLike { 14 | Converter CONVERTER = new Converter<>(); 15 | 16 | /** 17 | * Returns true if the specified point is inside this area 18 | * @param x the point X 19 | * @param y the point Y 20 | * @return true if the point is inside this area, false otherwise 21 | */ 22 | default boolean containsPoint(double x, double y) { 23 | // Find all intersections 24 | var result = lineIntersection(x, y, 0.5, 0.5, ALL_FORWARDS); 25 | 26 | // If number is odd, then return true 27 | return result.size() % 2 != 0; 28 | } 29 | 30 | @Override 31 | default boolean containsPoint(@NotNull Vector2d point) { 32 | return containsPoint(point.x(), point.y()); 33 | } 34 | 35 | /** 36 | * Returns the intersection between the specified line and this object. 37 | *

38 | * @param posX line X position 39 | * @param posY line Y position 40 | * @param dirX line X direction 41 | * @param dirY line Y direction 42 | * @return the computed line intersection position, null if none 43 | */ 44 | @NotNull R lineIntersection(double posX, double posY, double dirX, double dirY, @NotNull Intersection intersection); 45 | 46 | /** 47 | * Returns the intersection between the specified line and this object 48 | *

49 | * @param pos line position 50 | * @param dir line direction 51 | * @return the computed line intersection position, null if none 52 | */ 53 | default @NotNull R lineIntersection(@NotNull Vector2d pos, @NotNull Vector2d dir, @NotNull Intersection intersection) { 54 | return lineIntersection(pos.x(), pos.y(), dir.x(), dir.y(), intersection); 55 | } 56 | 57 | /** 58 | * Returns true if the specified line intersects this object. 59 | *

60 | * @param posX line X position 61 | * @param posY line Y position 62 | * @param dirX line X direction 63 | * @param dirY line Y direction 64 | * @return true if the line intersects this object, false otherwise 65 | */ 66 | default boolean lineIntersects(double posX, double posY, double dirX, double dirY) { 67 | return lineIntersection(posX, posY, dirX, dirY, Intersection.ANY_2D).intersection() != null; 68 | } 69 | 70 | /** 71 | * Returns any intersection between the specified line and this area 72 | *

73 | * @param pos line position 74 | * @param dir line direction 75 | * @return any line intersection position, null if none 76 | */ 77 | default @NotNull Intersection.Result lineIntersection(@NotNull Vector2d pos, @NotNull Vector2d dir) { 78 | return lineIntersection(pos, dir, Intersection.ANY_2D); 79 | } 80 | 81 | /** 82 | * Returns true if the specified line intersects this area. 83 | *

84 | * @param pos line position 85 | * @param dir line direction 86 | * @return true if the line intersects this object, false otherwise 87 | */ 88 | default boolean lineIntersects(@NotNull Vector2d pos, @NotNull Vector2d dir) { 89 | return lineIntersection(pos, dir).intersection() != null; 90 | } 91 | 92 | /** 93 | * Creates a combined area3d of all the planes contained in the areas passed to this function, accounting for 94 | * mutability if applicable. 95 | *

96 | * This method will produce a CombinedArea3d or DynamicCombinedArea3d, depending on which 97 | * 98 | * @param area2ds the area3ds to take the planes from 99 | * @return the new CombinedArea3d or DynamicCombinedArea3d 100 | */ 101 | static Area2d combined(Area2d... area2ds) { 102 | return new Area2d.Area2dCombined(area2ds); 103 | } 104 | 105 | /** 106 | * Creates a combined area3d of all the planes contained in the areas passed to this function, accounting for 107 | * dynamism if applicable. 108 | *

109 | * This method will produce a CombinedArea3d or DynamicCombinedArea3d, depending on which 110 | * 111 | * @param area2ds the area3ds to take the planes from 112 | * @return the new CombinedArea3d or DynamicCombinedArea3d 113 | */ 114 | static Area2d combined(@NotNull Collection area2ds) { 115 | return combined(area2ds.toArray(Area2d[]::new)); 116 | } 117 | 118 | class Area2dCombined implements Area2d { 119 | 120 | private final List all; 121 | 122 | private Area2dCombined(Area2d... area2ds) { 123 | this.all = List.of(area2ds); 124 | } 125 | 126 | @Override 127 | @SuppressWarnings("unchecked") 128 | public @NotNull R lineIntersection(double posX, double posY, double dirX, double dirY, @NotNull Intersection intersection) { 129 | Intersection.Collector collector = intersection.collector(); 130 | Intersection.Orderer> orderer = 131 | (Intersection.Orderer>) intersection.orderer(); 132 | 133 | return switch (collector) { 134 | case SINGLE -> (R) all.stream() 135 | .map(area -> area.lineIntersection(posX, posY, dirX, dirY, intersection)) 136 | .map(result -> (Intersection.Result) result) 137 | .filter(result -> result.intersection() != null) 138 | .min(orderer) 139 | .orElseGet(() -> Intersection.Result.none(this)); 140 | case ALL -> (R) all.stream() 141 | .map(area -> area.lineIntersection(posX, posY, dirX, dirY, intersection)) 142 | .map(result -> (Collection>) result) 143 | .flatMap(Collection::stream) 144 | .sorted(orderer) 145 | .collect(Collectors.toList()); 146 | }; 147 | } 148 | 149 | @Override 150 | public double area() { 151 | // TODO: Make this work correctly, right now it is an estimate 152 | return all.stream().mapToDouble(Area2d::area).sum(); 153 | } 154 | } 155 | 156 | @Override 157 | default @NotNull Area2d asArea2d() { 158 | return this; 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/area2d/Area2dRectangle.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area.area2d; 2 | 3 | import dev.emortal.rayfast.area.Intersection; 4 | import dev.emortal.rayfast.util.FunctionalInterfaces; 5 | import dev.emortal.rayfast.util.Intersection2dUtils; 6 | import dev.emortal.rayfast.vector.Vector2d; 7 | import org.jetbrains.annotations.NotNull; 8 | import org.jetbrains.annotations.Nullable; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | public interface Area2dRectangle extends Area2d { 14 | 15 | double minX(); 16 | double minY(); 17 | double maxX(); 18 | double maxY(); 19 | 20 | @SuppressWarnings("unchecked") 21 | default @NotNull R lineIntersection(double posX, double posY, double dirX, double dirY, @NotNull Intersection intersection) { 22 | Intersection.Direction direction = intersection.direction(); 23 | 24 | double posXb = posX + dirX; 25 | double posYb = posY + dirY; 26 | 27 | switch (intersection.collector()) { 28 | case SINGLE -> { 29 | // Bottom line 30 | { 31 | Intersection.Result result = Intersection2dUtils.lineIntersection( 32 | this, 33 | direction, 34 | minX(), minY(), 35 | maxX(), minY(), 36 | posX, posY, posXb, posYb 37 | ); 38 | if (result.intersection() != null) { 39 | return (R) result; 40 | } 41 | } 42 | 43 | // Left line 44 | { 45 | Intersection.Result result = Intersection2dUtils.lineIntersection( 46 | this, 47 | direction, 48 | minX(), minY(), 49 | minX(), maxY(), 50 | posX, posY, posXb, posYb 51 | ); 52 | 53 | if (result.intersection() != null) { 54 | return (R) result; 55 | } 56 | } 57 | 58 | // Right line 59 | { 60 | Intersection.Result result = Intersection2dUtils.lineIntersection( 61 | this, 62 | direction, 63 | maxX(), minY(), 64 | maxX(), maxY(), 65 | posX, posY, posXb, posYb 66 | ); 67 | 68 | if (result.intersection() != null) { 69 | return (R) result; 70 | } 71 | } 72 | 73 | // Top line 74 | { 75 | Intersection.Result result = Intersection2dUtils.lineIntersection( 76 | this, 77 | direction, 78 | minX(), maxY(), 79 | maxX(), maxY(), 80 | posX, posY, posXb, posYb 81 | ); 82 | 83 | if (result.intersection() != null) { 84 | return (R) result; 85 | } 86 | } 87 | return (R) Intersection.Result.none(this); 88 | } 89 | case ALL -> { 90 | List> results = new ArrayList<>(); 91 | // Bottom line 92 | { 93 | Intersection.@NotNull Result result = Intersection2dUtils.lineIntersection( 94 | this, 95 | direction, 96 | minX(), minY(), 97 | maxX(), minY(), 98 | posX, posY, posXb, posYb 99 | ); 100 | if (result.intersection() != null) { 101 | results.add(result); 102 | } 103 | } 104 | 105 | // Left line 106 | { 107 | Intersection.@NotNull Result result = Intersection2dUtils.lineIntersection( 108 | this, 109 | direction, 110 | minX(), minY(), 111 | minX(), maxY(), 112 | posX, posY, posXb, posYb 113 | ); 114 | if (result.intersection() != null) { 115 | results.add(result); 116 | } 117 | } 118 | 119 | // Right line 120 | { 121 | Intersection.@NotNull Result result = Intersection2dUtils.lineIntersection( 122 | this, 123 | direction, 124 | maxX(), minY(), 125 | maxX(), maxY(), 126 | posX, posY, posXb, posYb 127 | ); 128 | if (result.intersection() != null) { 129 | results.add(result); 130 | } 131 | } 132 | 133 | // Top line 134 | { 135 | Intersection.@NotNull Result result = Intersection2dUtils.lineIntersection( 136 | this, 137 | direction, 138 | minX(), maxY(), 139 | maxX(), maxY(), 140 | posX, posY, posXb, posYb 141 | ); 142 | if (result.intersection() != null) { 143 | results.add(result); 144 | } 145 | } 146 | return (R) results; 147 | } 148 | } 149 | 150 | throw new IllegalStateException("Unknown intersection collector: " + intersection.collector()); 151 | }; 152 | 153 | /** 154 | * Generates a wrapper for the specified object using the specified getters. 155 | *

156 | * This is a sub-optimal implementation. An ideal implementation implements the 157 | * Area2dRectangle interface directly on the object. 158 | * 159 | * @param object the object to wrap 160 | * @param minXGetter the getter for the minimum x value 161 | * @param minYGetter the getter for the minimum y value 162 | * @param maxXGetter the getter for the maximum x value 163 | * @param maxYGetter the getter for the maximum y value 164 | * @param the type of the wrapped object 165 | * @return the area that is represented by this wrapped object 166 | */ 167 | static Area2d wrapper( 168 | T object, 169 | FunctionalInterfaces.DoubleWrapper minXGetter, 170 | FunctionalInterfaces.DoubleWrapper maxXGetter, 171 | FunctionalInterfaces.DoubleWrapper minYGetter, 172 | FunctionalInterfaces.DoubleWrapper maxYGetter 173 | ) { 174 | return new Area2dRectangle() { 175 | @Override 176 | public double minX() { 177 | return minXGetter.get(object); 178 | } 179 | 180 | @Override 181 | public double minY() { 182 | return minYGetter.get(object); 183 | } 184 | 185 | @Override 186 | public double maxX() { 187 | return maxXGetter.get(object); 188 | } 189 | 190 | @Override 191 | public double maxY() { 192 | return maxYGetter.get(object); 193 | } 194 | }; 195 | } 196 | 197 | static @NotNull Area2dRectangle of(double minX, double minY, double maxX, double maxY) { 198 | return new Area2dRectangleImpl(minX, minY, maxX, maxY); 199 | } 200 | 201 | @Override 202 | default double area() { 203 | return (maxX() - minX()) * (maxY() - minY()); 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/util/Intersection3dUtils.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.util; 2 | 3 | 4 | import dev.emortal.rayfast.area.Intersection; 5 | import dev.emortal.rayfast.vector.Vector3d; 6 | import org.jetbrains.annotations.ApiStatus; 7 | import org.jetbrains.annotations.NotNull; 8 | import org.jetbrains.annotations.Nullable; 9 | 10 | /** 11 | * Internal Intersection Utils. 12 | * 13 | * INTERNAL ONLY. 14 | * If any issues arise using this class, that's on you. 15 | */ 16 | @ApiStatus.Internal 17 | public class Intersection3dUtils { 18 | private static class IncompleteResult { 19 | Vector3d start; 20 | Vector3d direction; 21 | @Nullable Vector3d intersection; 22 | @Nullable Vector3d normal; 23 | } 24 | 25 | private static final ThreadLocal THREAD_LOCAL = ThreadLocal.withInitial(IncompleteResult::new); 26 | 27 | @ApiStatus.Internal 28 | public static @NotNull
Intersection.Result planeIntersection( 29 | A area, 30 | Intersection.Direction direction, 31 | // Line 32 | double posX, double posY, double posZ, // Position vector 33 | double dirX, double dirY, double dirZ, // Direction vector 34 | // Plane 35 | double minX, double minY, double minZ, 36 | double adjX, double adjY, double adjZ, 37 | double maxX, double maxY, double maxZ) { 38 | 39 | IncompleteResult result = THREAD_LOCAL.get(); 40 | result.start = Vector3d.of(posX, posY, posZ); 41 | result.direction = Vector3d.of(dirX, dirY, dirZ); 42 | result.intersection = null; 43 | result.normal = null; 44 | 45 | getIntersection(direction, result, 46 | minX, minY, minZ, 47 | adjX, adjY, adjZ, 48 | maxX, maxY, maxZ); 49 | 50 | if (result.intersection == null) { 51 | return Intersection.Result.none(area); 52 | } 53 | 54 | double x = result.intersection.x(); 55 | double y = result.intersection.y(); 56 | double z = result.intersection.z(); 57 | 58 | int fits = 0; 59 | 60 | if ((minX != maxX) && isBetweenUnordered(x, minX, maxX)) { 61 | fits++; 62 | } 63 | 64 | if ((minY != maxY) && isBetweenUnordered(y, minY, maxY)) { 65 | fits++; 66 | } 67 | 68 | if ((minZ != maxZ) && isBetweenUnordered(z, minZ, maxZ)) { 69 | fits++; 70 | } 71 | 72 | if (fits < 2) { 73 | return Intersection.Result.none(area); 74 | } 75 | 76 | Vector3d start = result.start; 77 | Vector3d end = result.intersection; 78 | 79 | // Find distance 80 | double distX = start.x() - end.x(); 81 | double distY = start.y() - end.y(); 82 | double distZ = start.z() - end.z(); 83 | double dist = Math.sqrt(distX * distX + distY * distY + distZ * distZ); 84 | 85 | return Intersection.Result.of(result.intersection, result.normal, area, dist); 86 | } 87 | 88 | @ApiStatus.Internal 89 | private static boolean isBetweenUnordered(double number, double compare1, double compare2) { 90 | if (compare1 > compare2) { 91 | return number >= compare2 && number <= compare1; 92 | } 93 | return number >= compare1 && number <= compare2; 94 | } 95 | 96 | @ApiStatus.Internal 97 | public static void getIntersection( 98 | // Line direction 99 | Intersection.Direction direction, 100 | // Result 101 | IncompleteResult result, 102 | // Plane 103 | double planeX, double planeY, double planeZ, // Plane point 104 | double planeDirX, double planeDirY, double planeDirZ // Plane normal 105 | ) { 106 | double posX = result.start.x(); double posY = result.start.y(); double posZ = result.start.z(); 107 | double dirX = result.direction.x(); double dirY = result.direction.y(); double dirZ = result.direction.z(); 108 | 109 | // Sensitive (speed oriented) code: 110 | double dotA = planeDirX * planeX + planeDirY * planeY + planeDirZ * planeZ; 111 | double dotB = planeDirX * posX + planeDirY * posY + planeDirZ * posZ; 112 | double dotC = planeDirX * dirX + planeDirY * dirY + planeDirZ * dirZ; 113 | double t = (dotA - dotB) / dotC; 114 | 115 | double x = posX + (dirX * t); 116 | double y = posY + (dirY * t); 117 | double z = posZ + (dirZ * t); 118 | 119 | // Get the normal vector 120 | double normalX = planeX - x; 121 | double normalY = planeY - y; 122 | double normalZ = planeZ - z; 123 | 124 | Vector3d intersection = Vector3d.of(x, y, z); 125 | Vector3d normal = Vector3d.of(normalX, normalY, normalZ); 126 | 127 | if (direction == Intersection.Direction.ANY) { 128 | result.intersection = intersection; 129 | result.normal = normal; 130 | return; 131 | } 132 | 133 | double dotProduct = dirX * (x - posX) + dirY * (y - posY) + dirZ * (z - posZ); 134 | 135 | if (direction == Intersection.Direction.FORWARDS) { 136 | if (dotProduct < 0) { 137 | return; 138 | } 139 | } else if (direction == Intersection.Direction.BACKWARDS) { 140 | if (dotProduct > 0) { 141 | return; 142 | } 143 | } 144 | 145 | result.intersection = intersection; 146 | result.normal = normal; 147 | } 148 | 149 | @ApiStatus.Internal 150 | public static void getIntersection( 151 | // Line Direction 152 | Intersection.Direction direction, 153 | // Result 154 | IncompleteResult result, 155 | // Plane 156 | double minX, double minY, double minZ, 157 | double adjX, double adjY, double adjZ, 158 | double maxX, double maxY, double maxZ) { 159 | 160 | double v1x = minX - adjX; 161 | double v1y = minY - adjY; 162 | double v1z = minZ - adjZ; 163 | double v2x = minX - maxX; 164 | double v2y = minY - maxY; 165 | double v2z = minZ - maxZ; 166 | 167 | double crossX = v1y * v2z - v2y * v1z; 168 | double crossY = v1z * v2x - v2z * v1x; 169 | double crossZ = v1x * v2y - v2x * v1y; 170 | 171 | getIntersection( 172 | // Line Direction 173 | direction, 174 | // Line 175 | result, 176 | // Plane 177 | minX, minY, minZ, 178 | crossX, crossY, crossZ 179 | ); 180 | 181 | // TODO: fix this (faster) method 182 | /* 183 | System.out.println("LINE:"); 184 | System.out.println("DIR: " + dirX + ":" + dirY + ":" + dirZ); 185 | System.out.println("POS: " + posX + ":" + posY + ":" + posZ); 186 | 187 | double ABx = maxX - minX; 188 | double ABy = maxY - minY; 189 | double ABz = maxZ - minZ; 190 | 191 | double ACx = adjX - minX; 192 | double ACy = adjY - minY; 193 | double ACz = adjZ - minZ; 194 | 195 | double perpenX = ABy * ACz - ACy * ABz; 196 | double perpenY = ACx * ABz - ABx * ACz; 197 | double perpenZ = ABx * ACy - ACx * ABy; 198 | 199 | // Line equation: r = pos + t * dir 200 | // x = posX + (dirX * t) 201 | // y = posY + (dirY * t) 202 | // z = posZ + (dirZ * t) 203 | 204 | // Plane equation 205 | // 0 = pointX(x - perpenX) + pointY(y - perpenY) + pointZ(z - perpenZ) 206 | // 0 = pointX(posX + (dirX * t) - perpenX) + pointY(posY + (dirY * t) - perpenY) + pointZ(posZ + (dirZ * t) - perpenZ) 207 | 208 | // Combine equations to find t (distance to point) 209 | // 0 = g(d + (a * t) - j) + h(e + (b * t) - k) + i(f + (c * t) - l) 210 | // t = (-dg+jg-if-eh+li+kh) / (ag+bh+ci) 211 | double t = (-posX * adjX + perpenX * adjX - adjZ * posZ - posY * adjY + perpenZ * adjZ + perpenY * adjY) / (dirX * adjX + dirY * adjY + dirZ * adjZ); 212 | 213 | // A = -B * C 214 | 215 | // Now use t to get the point 216 | // x = posX + (dirX * t) 217 | // y = posY + (dirY * t) 218 | // z = posZ + (dirZ * t) 219 | 220 | double x = posX + (dirX * t); 221 | double y = posY + (dirY * t); 222 | double z = posZ + (dirZ * t); 223 | */ 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/area3d/Area3d.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area.area3d; 2 | 3 | import dev.emortal.rayfast.area.Area; 4 | import dev.emortal.rayfast.area.Intersection; 5 | import dev.emortal.rayfast.util.Converter; 6 | import dev.emortal.rayfast.vector.Vector3d; 7 | import org.jetbrains.annotations.NotNull; 8 | import org.jetbrains.annotations.Nullable; 9 | 10 | import java.util.Collection; 11 | import java.util.List; 12 | import java.util.stream.Collectors; 13 | 14 | /** 15 | * Specifies an object that represents some arbitrary 3d area. 16 | */ 17 | 18 | public interface Area3d extends Area, Area3dLike { 19 | Converter CONVERTER = new Converter<>(); 20 | 21 | /** 22 | * Returns true if the specified point is inside this area 23 | * @param pointX the point X 24 | * @param pointY the point Y 25 | * @param pointZ the point Z 26 | * @return true if the point is inside this area, false otherwise 27 | */ 28 | default boolean containsPoint(double pointX, double pointY, double pointZ) { 29 | // Find all forwards intersections 30 | var result = lineIntersection(pointX, pointY, pointZ, 0.5, 0.5, 0.5, ALL_FORWARDS); 31 | 32 | // If number is odd, then return true 33 | return result.size() % 2 != 0; 34 | } 35 | 36 | /** 37 | * Returns true if the specified point is inside this area 38 | * @param point the point 39 | * @return true if the point is inside this area, false otherwise 40 | */ 41 | default boolean containsPoint(@NotNull Vector3d point) { 42 | return containsPoint(point.x(), point.y(), point.z()); 43 | } 44 | 45 | /** 46 | * Returns the intersection between the specified line and this object. 47 | *

48 | * @param posX line X position 49 | * @param posY line Y position 50 | * @param posZ line Z position 51 | * @param dirX line X direction 52 | * @param dirY line Y direction 53 | * @param dirZ line Z direction 54 | * @return the computed line intersection position, null if none 55 | */ 56 | @NotNull R lineIntersection(double posX, double posY, double posZ, double dirX, double dirY, double dirZ, @NotNull Intersection intersection); 57 | 58 | /** 59 | * Returns the intersection between the specified line and this object 60 | *

61 | * @param pos line position 62 | * @param dir line direction 63 | * @return the computed line intersection position, null if none 64 | */ 65 | default @NotNull R lineIntersection(@NotNull Vector3d pos, @NotNull Vector3d dir, @NotNull Intersection intersection) { 66 | return lineIntersection(pos.x(), pos.y(), pos.z(), dir.x(), dir.y(), dir.z(), intersection); 67 | } 68 | 69 | /** 70 | * Returns true if the specified line intersects this object. 71 | *

72 | * @param posX line X position 73 | * @param posY line Y position 74 | * @param posZ line Z position 75 | * @param dirX line X direction 76 | * @param dirY line Y direction 77 | * @param dirZ line Z direction 78 | * @return true if the line intersects this object, false otherwise 79 | */ 80 | default boolean lineIntersects(double posX, double posY, double posZ, double dirX, double dirY, double dirZ) { 81 | return lineIntersection(posX, posY, posZ, dirX, dirY, dirZ, Intersection.ANY_3D).intersection() != null; 82 | } 83 | 84 | /** 85 | * Returns any intersection between the specified line and this area 86 | *

87 | * @param pos line position 88 | * @param dir line direction 89 | * @return any line intersection position, null if none 90 | */ 91 | default @Nullable Vector3d lineIntersection(@NotNull Vector3d pos, @NotNull Vector3d dir) { 92 | return lineIntersection(pos, dir, Intersection.ANY_3D).intersection(); 93 | } 94 | 95 | /** 96 | * Returns any intersection between the specified line and this area 97 | *

98 | * @param posX line x position 99 | * @param posY line y position 100 | * @param posZ line z position 101 | * @param dirX line x direction 102 | * @param dirY line y direction 103 | * @param dirZ line z direction 104 | * @return any line intersection position, null if none 105 | */ 106 | default @Nullable Vector3d lineIntersection(double posX, double posY, double posZ, double dirX, double dirY, double dirZ) { 107 | return lineIntersection(posX, posY, posZ, dirX, dirY, dirZ, Intersection.ANY_3D).intersection(); 108 | } 109 | 110 | /** 111 | * Returns true if the specified line intersects this area. 112 | *

113 | * @param pos line position 114 | * @param dir line direction 115 | * @return true if the line intersects this object, false otherwise 116 | */ 117 | default boolean lineIntersects(@NotNull Vector3d pos, @NotNull Vector3d dir) { 118 | return lineIntersection(pos, dir) != null; 119 | } 120 | 121 | /** 122 | * Creates a combined area3d of all the planes contained in the areas passed to this function, accounting for 123 | * mutability if applicable. 124 | *

125 | * This method will produce a CombinedArea3d or DynamicCombinedArea3d, depending on which 126 | * 127 | * @param area3ds the area3ds to take the planes from 128 | * @return the new CombinedArea3d or DynamicCombinedArea3d 129 | */ 130 | static Area3d combined(Area3d... area3ds) { 131 | return new Area3dCombined(area3ds); 132 | } 133 | 134 | /** 135 | * Creates a combined area3d of all the planes contained in the areas passed to this function, accounting for 136 | * dynamism if applicable. 137 | *

138 | * This method will produce a CombinedArea3d or DynamicCombinedArea3d, depending on which 139 | * 140 | * @param area3ds the area3ds to take the planes from 141 | * @return the new Area3d 142 | */ 143 | static Area3d combined(@NotNull Collection area3ds) { 144 | return new Area3dCombined(area3ds); 145 | } 146 | 147 | class Area3dCombined implements Area3d { 148 | 149 | private final List all; 150 | 151 | public Area3dCombined(Area3d... area3ds) { 152 | this.all = List.of(area3ds); 153 | } 154 | 155 | public Area3dCombined(Collection area3ds) { 156 | this(area3ds.toArray(Area3d[]::new)); 157 | } 158 | 159 | @Override 160 | public boolean containsPoint(double pointX, double pointY, double pointZ) { 161 | 162 | for (Area3d area3d : all) { 163 | boolean result = area3d.containsPoint(pointX, pointY, pointZ); 164 | 165 | if (result) { 166 | return true; 167 | } 168 | } 169 | 170 | return false; 171 | } 172 | 173 | @Override 174 | @SuppressWarnings("unchecked") 175 | public @NotNull R lineIntersection(double posX, double posY, double posZ, double dirX, double dirY, double dirZ, @NotNull Intersection intersection) { 176 | Intersection.Collector collector = intersection.collector(); 177 | Intersection.Orderer> orderer = 178 | (Intersection.Orderer>) intersection.orderer(); 179 | 180 | return switch (collector) { 181 | case SINGLE -> (R) all.stream() 182 | .map(area -> area.lineIntersection(posX, posY, posZ, dirX, dirY, dirZ, intersection)) 183 | .map(result -> (Intersection.Result) result) 184 | .filter(result -> result.intersection() != null) 185 | .min(orderer) 186 | .orElseGet(() -> Intersection.Result.none(this)); 187 | case ALL -> (R) all.stream() 188 | .map(area -> area.lineIntersection(posX, posY, posZ, dirX, dirY, dirZ, intersection)) 189 | .map(result -> (Collection>) result) 190 | .flatMap(Collection::stream) 191 | .sorted(orderer) 192 | .collect(Collectors.toList()); 193 | }; 194 | } 195 | 196 | @Override 197 | public double area() { 198 | // TODO: Make this work correctly, right now it is an estimate 199 | return all.stream().mapToDouble(Area3d::area).sum(); 200 | } 201 | } 202 | 203 | @Override 204 | default @NotNull Area3d asArea3d() { 205 | return this; 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /src/test/java/dev/emortal/rayfast/test/benchmarks/RunBenchmarks.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.test.benchmarks; 2 | 3 | import dev.emortal.rayfast.area.Intersection; 4 | import dev.emortal.rayfast.area.area2d.Area2d; 5 | import dev.emortal.rayfast.area.area2d.Area2dPolygon; 6 | import dev.emortal.rayfast.area.area3d.Area3d; 7 | import dev.emortal.rayfast.area.area3d.Area3dLike; 8 | import dev.emortal.rayfast.area.area3d.Area3dRectangularPrism; 9 | import dev.emortal.rayfast.casting.combined.CombinedCast; 10 | import dev.emortal.rayfast.casting.grid.GridCast; 11 | import dev.emortal.rayfast.test.examples.ExampleRaycastEntity; 12 | import dev.emortal.rayfast.vector.Vector2d; 13 | import dev.emortal.rayfast.vector.Vector3d; 14 | 15 | import java.util.Arrays; 16 | import java.util.Collection; 17 | import java.util.HashSet; 18 | import java.util.Map; 19 | 20 | /** 21 | * Performance tests. 22 | */ 23 | public class RunBenchmarks { 24 | 25 | private static Area3d interfacedCombined; 26 | private static Area3d wrapperCombined; 27 | private static Area2d polygonTests; 28 | 29 | private static Collection combinedCastAreas; 30 | 31 | public static void main(String[] args) { 32 | // TODO: Use jmh to run the benchmarks 33 | long startMillis = System.currentTimeMillis(); 34 | System.out.println("Setting up Area3ds"); 35 | 36 | Area3d[] interfaced = new Area3d[1000]; 37 | 38 | // Create new entity 39 | ExampleRaycastEntity exampleRaycastEntity = new ExampleRaycastEntity() { 40 | private final BoundingBox box = new BoundingBox(this, 123, 456, 789); 41 | 42 | @Override 43 | public BoundingBox getBoundingBox() { 44 | return box; 45 | } 46 | 47 | @Override 48 | public double getX() { 49 | return Math.random(); 50 | } 51 | 52 | @Override 53 | public double getY() { 54 | return Math.random(); 55 | } 56 | 57 | @Override 58 | public double getZ() { 59 | return Math.random(); 60 | } 61 | }; 62 | 63 | Arrays.fill(interfaced, exampleRaycastEntity.asArea3d()); 64 | 65 | interfacedCombined = Area3d.combined(interfaced); 66 | 67 | 68 | Area3d[] wrappers = new Area3d[1000]; 69 | 70 | Arrays.fill(wrappers, Area3dRectangularPrism.wrapper( 71 | exampleRaycastEntity.getBoundingBox(), 72 | ExampleRaycastEntity.BoundingBox::minX, 73 | ExampleRaycastEntity.BoundingBox::minY, 74 | ExampleRaycastEntity.BoundingBox::minZ, 75 | ExampleRaycastEntity.BoundingBox::maxX, 76 | ExampleRaycastEntity.BoundingBox::maxY, 77 | ExampleRaycastEntity.BoundingBox::maxZ 78 | )); 79 | 80 | wrapperCombined = Area3d.combined(wrappers); 81 | 82 | Area2d[] polygons = new Area2d[1000]; 83 | 84 | Vector2d pos1 = Vector2d.of(Math.random(), Math.random()); 85 | Vector2d pos2 = Vector2d.of(Math.random(), Math.random()); 86 | Vector2d pos3 = Vector2d.of(Math.random(), Math.random()); 87 | 88 | final Map lines = Map.of( 89 | pos1, pos2, 90 | pos2, pos3, 91 | pos3, pos1 92 | ); 93 | 94 | Arrays.fill(polygons, (Area2dPolygon) () -> lines); 95 | 96 | polygonTests = Area2d.combined(polygons); 97 | 98 | System.out.println("Finished after " + (System.currentTimeMillis() - startMillis) + "ms"); 99 | 100 | combinedCastAreas = new HashSet<>(); 101 | 102 | for (int i = 0; i < 100; i++) { 103 | double minX = Math.random(); double maxX = Math.random(); 104 | double minY = Math.random(); double maxY = Math.random(); 105 | double minZ = Math.random(); double maxZ = Math.random(); 106 | 107 | combinedCastAreas.add(new Area3dRectangularPrism() { 108 | @Override 109 | public double minX() { 110 | return minX; 111 | } 112 | 113 | @Override 114 | public double minY() { 115 | return minY; 116 | } 117 | 118 | @Override 119 | public double minZ() { 120 | return minZ; 121 | } 122 | 123 | @Override 124 | public double maxX() { 125 | return maxX; 126 | } 127 | 128 | @Override 129 | public double maxY() { 130 | return maxY; 131 | } 132 | 133 | @Override 134 | public double maxZ() { 135 | return maxZ; 136 | } 137 | }); 138 | } 139 | 140 | benchmarkArea2d(); 141 | benchmarkArea2d(); 142 | benchmarkBlocks(); 143 | benchmarkCombinedCast(); 144 | } 145 | 146 | private static void benchmarkBlocks() { 147 | long startMillis = System.currentTimeMillis(); 148 | 149 | Iterable iterable = GridCast.createGridIterator( 150 | Math.random(), Math.random(), Math.random(), 151 | Math.random(), Math.random(), Math.random(), 152 | 1, 153 | 100_000 154 | ); 155 | 156 | int i = 0; 157 | 158 | for (Vector3d ignored : iterable) { 159 | i++; 160 | } 161 | 162 | System.out.println("took " + (System.currentTimeMillis() - startMillis) + "ms to iterate over " + i + " grid units (1x1 cubes)"); 163 | } 164 | 165 | private static void benchmarkArea3d() { 166 | 167 | final Intersection> intersection = Intersection.ANY_3D; 168 | 169 | { 170 | long millis = System.currentTimeMillis(); 171 | 172 | for (int i = 0; i < 100_000; i++) 173 | interfacedCombined.lineIntersection( 174 | Math.random(), Math.random(), Math.random(), 175 | Math.random(), Math.random(), Math.random(), 176 | intersection 177 | ); 178 | 179 | System.out.println("took " + (System.currentTimeMillis() - millis) + "ms to intersect 100 mil interfaced rectangular prisms"); 180 | } 181 | 182 | { 183 | long millis = System.currentTimeMillis(); 184 | 185 | for (int i = 0; i < 100_000; i++) 186 | wrapperCombined.lineIntersection( 187 | Math.random(), Math.random(), Math.random(), 188 | Math.random(), Math.random(), Math.random(), 189 | intersection 190 | ); 191 | 192 | System.out.println("took " + (System.currentTimeMillis() - millis) + "ms to intersect 100 mil wrapped rectangular prisms"); 193 | } 194 | } 195 | 196 | private static void benchmarkArea2d() { 197 | 198 | final Intersection> intersection = Intersection.ANY_2D; 199 | 200 | { 201 | long millis = System.currentTimeMillis(); 202 | 203 | for (int i = 0; i < 1000; i++) 204 | polygonTests.lineIntersection( 205 | Math.random(), Math.random(), 206 | Math.random(), Math.random(), 207 | intersection 208 | ); 209 | 210 | System.out.println("took " + (System.currentTimeMillis() - millis) + "ms to intersect 100_000 2d polygons"); 211 | } 212 | } 213 | 214 | private static void benchmarkCombinedCast() { 215 | final CombinedCast combinedCast = CombinedCast.builder() 216 | .gridSize(1.0) 217 | .max(100.0) 218 | .ordered(true) 219 | .build(); 220 | 221 | { 222 | Vector3d vecA = Vector3d.of(Math.random(), Math.random(), Math.random()); 223 | Vector3d vecB = Vector3d.of(Math.random(), Math.random(), Math.random()); 224 | 225 | combinedCast.apply(combinedCastAreas, vecA, vecB); 226 | } 227 | 228 | { 229 | long millis = System.currentTimeMillis(); 230 | 231 | int amount = 1000; 232 | 233 | for (int i = 0; i < amount; i++) { 234 | 235 | Vector3d vecA = Vector3d.of(Math.random(), Math.random(), Math.random()); 236 | Vector3d vecB = Vector3d.of(Math.random(), Math.random(), Math.random()); 237 | 238 | combinedCast.apply(combinedCastAreas, vecA, vecB); 239 | } 240 | 241 | System.out.println("took " + (System.currentTimeMillis() - millis) + "ms to do " + amount + " combined casts with 100 entities and 100 block range"); 242 | } 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/casting/grid/GridCast.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.casting.grid; 2 | 3 | import dev.emortal.rayfast.vector.Vector3d; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | import java.util.Iterator; 7 | 8 | public class GridCast { 9 | 10 | /** 11 | * Creates an iterator that iterates through blocks on a 3d 1x1 grid forever. 12 | * 13 | * @param startX iterator start position X 14 | * @param startY iterator start position Y 15 | * @param startZ iterator start position Z 16 | * @param dirX iterator direction X 17 | * @param dirY iterator direction Y 18 | * @param dirZ iterator direction Z 19 | * @return the iterator 20 | */ 21 | public static GridIterator createGridIterator( 22 | double startX, 23 | double startY, 24 | double startZ, 25 | double dirX, 26 | double dirY, 27 | double dirZ 28 | ) { 29 | return createGridIterator(startX, startY, startZ, dirX, dirY, dirZ, 1.0, Double.MAX_VALUE); 30 | } 31 | 32 | /** 33 | * Creates an iterator that iterates through blocks on a 3d 1x1 grid forever. 34 | * 35 | * @param start iterator start position 36 | * @param dir iterator direction 37 | * @return the iterator 38 | */ 39 | public static GridIterator createGridIterator( 40 | Vector3d start, 41 | Vector3d dir 42 | ) { 43 | return createGridIterator(start.x(), start.y(), start.z(), dir.x(), dir.y(), dir.z(), 1.0, Double.MAX_VALUE); 44 | } 45 | 46 | /** 47 | * Creates an iterator that iterates through blocks on a 3d grid of the specified grid size, until the total length 48 | * exceeds the length specified. 49 | * 50 | * @param startX iterator start position X 51 | * @param startY iterator start position Y 52 | * @param startZ iterator start position Z 53 | * @param dirX iterator direction X 54 | * @param dirY iterator direction Y 55 | * @param dirZ iterator direction Z 56 | * @param gridSize the size of the grid 57 | * @param length the maximum length of the iterator 58 | * @return the iterator 59 | */ 60 | public static GridIterator createGridIterator( 61 | double startX, 62 | double startY, 63 | double startZ, 64 | double dirX, 65 | double dirY, 66 | double dirZ, 67 | double gridSize, 68 | double length 69 | ) { 70 | return new GridIterator(startX, startY, startZ, dirX, dirY, dirZ, gridSize, length); 71 | } 72 | 73 | /** 74 | * Creates an iterator that iterates through blocks on a 3d grid of the specified grid size, until the total length 75 | * exceeds the length specified. 76 | * 77 | * @param start iterator start position 78 | * @param dir iterator direction 79 | * @param gridSize the size of the grid 80 | * @param length the maximum length of the iterator 81 | * @return the iterator 82 | */ 83 | public static GridIterator createGridIterator( 84 | Vector3d start, 85 | Vector3d dir, 86 | double gridSize, 87 | double length 88 | ) { 89 | return new GridIterator(start.x(), start.y(), start.z(), dir.x(), dir.y(), dir.z(), gridSize, length); 90 | } 91 | 92 | /** 93 | * Creates an iterator that iterates through blocks on a 3d grid of the specified grid size, giving the exact 94 | * position that was hit when any grid unit was intersected. It does this until the total length exceeds the length 95 | * specified. 96 | * 97 | * @param start iterator start position 98 | * @param dir iterator direction 99 | * @param gridSize the size of the grid 100 | * @param length the maximum length of the iterator 101 | * @return the iterator 102 | */ 103 | public static GridIterator createExactGridIterator( 104 | Vector3d start, 105 | Vector3d dir, 106 | double gridSize, 107 | double length 108 | ) { 109 | return new ExactGridIterator(start.x(), start.y(), start.z(), dir.x(), dir.y(), dir.z(), gridSize, length); 110 | } 111 | 112 | /** 113 | * Creates an iterator that iterates through blocks on a 3d grid of the specified grid size, giving the exact 114 | * position that was hit when any grid unit was intersected. It does this until the total length exceeds the length 115 | * specified. 116 | * 117 | * @param startX iterator start position X 118 | * @param startY iterator start position Y 119 | * @param startZ iterator start position Z 120 | * @param dirX iterator direction X 121 | * @param dirY iterator direction Y 122 | * @param dirZ iterator direction Z 123 | * @param gridSize the size of the grid 124 | * @param length the maximum length of the iterator 125 | * @return the iterator 126 | */ 127 | public static GridIterator createExactGridIterator( 128 | double startX, 129 | double startY, 130 | double startZ, 131 | double dirX, 132 | double dirY, 133 | double dirZ, 134 | double gridSize, 135 | double length 136 | ) { 137 | return new ExactGridIterator(startX, startY, startZ, dirX, dirY, dirZ, gridSize, length); 138 | } 139 | 140 | private static class GridIterator implements Iterator, Iterable { 141 | 142 | protected double posX; 143 | protected double posY; 144 | protected double posZ; 145 | protected final double dirX; 146 | protected final double dirY; 147 | protected final double dirZ; 148 | protected final double gridSize; 149 | protected final double length; 150 | protected double currentLength = 0; 151 | 152 | protected GridIterator( 153 | double startX, 154 | double startY, 155 | double startZ, 156 | double dirX, 157 | double dirY, 158 | double dirZ, 159 | double gridSize, 160 | double length 161 | ) { 162 | this.posX = startX; 163 | this.posY = startY; 164 | this.posZ = startZ; 165 | this.dirX = dirX; 166 | this.dirY = dirY; 167 | this.dirZ = dirZ; 168 | this.gridSize = gridSize; 169 | this.length = length; 170 | } 171 | 172 | @Override 173 | public boolean hasNext() { 174 | return currentLength < length; 175 | } 176 | 177 | @Override 178 | public Vector3d next() { 179 | // Find the length to the next block 180 | double lengthX = (gridSize - (Math.abs(posX) % gridSize)) / Math.abs(dirX); 181 | double lengthY = (gridSize - (Math.abs(posY) % gridSize)) / Math.abs(dirY); 182 | double lengthZ = (gridSize - (Math.abs(posZ) % gridSize)) / Math.abs(dirZ); 183 | 184 | // Find the lowest of all 185 | double lowest = Math.min(lengthX, Math.min(lengthY, lengthZ)); 186 | 187 | // Cast to the next block 188 | this.posX += dirX * lowest; 189 | this.posY += dirY * lowest; 190 | this.posZ += dirZ * lowest; 191 | 192 | // Add length to current 193 | currentLength += lowest; 194 | 195 | return Vector3d.of( 196 | posX - posX % gridSize, 197 | posY - posY % gridSize, 198 | posZ - posZ % gridSize 199 | ); 200 | } 201 | 202 | @Override 203 | public @NotNull Iterator iterator() { 204 | return this; 205 | } 206 | } 207 | 208 | private static class ExactGridIterator extends GridIterator { 209 | protected ExactGridIterator(double startX, double startY, double startZ, double dirX, double dirY, double dirZ, double gridSize, double length) { 210 | super(startX, startY, startZ, dirX, dirY, dirZ, gridSize, length); 211 | } 212 | 213 | @Override 214 | public Vector3d next() { 215 | // Find the length to the next block 216 | double lengthX = (gridSize - (Math.abs(posX) % gridSize)) / Math.abs(dirX); 217 | double lengthY = (gridSize - (Math.abs(posY) % gridSize)) / Math.abs(dirY); 218 | double lengthZ = (gridSize - (Math.abs(posZ) % gridSize)) / Math.abs(dirZ); 219 | 220 | // Find the lowest of all 221 | double lowest = Math.min(lengthX, Math.min(lengthY, lengthZ)); 222 | 223 | // Cast to the next block 224 | this.posX += dirX * lowest; 225 | this.posY += dirY * lowest; 226 | this.posZ += dirZ * lowest; 227 | 228 | // Add length to current 229 | currentLength += lowest; 230 | 231 | return Vector3d.of( 232 | posX, 233 | posY, 234 | posZ 235 | ); 236 | } 237 | } 238 | 239 | 240 | } 241 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/casting/combined/CombinedCast.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.casting.combined; 2 | 3 | import dev.emortal.rayfast.area.Intersection; 4 | import dev.emortal.rayfast.area.area3d.Area3d; 5 | import dev.emortal.rayfast.area.area3d.Area3dLike; 6 | import dev.emortal.rayfast.casting.grid.GridCast; 7 | import dev.emortal.rayfast.util.FunctionalInterfaces; 8 | import dev.emortal.rayfast.util.VectorMathUtil; 9 | import dev.emortal.rayfast.vector.Vector; 10 | import dev.emortal.rayfast.vector.Vector2d; 11 | import dev.emortal.rayfast.vector.Vector3d; 12 | import org.jetbrains.annotations.ApiStatus; 13 | import org.jetbrains.annotations.NotNull; 14 | import org.jetbrains.annotations.Nullable; 15 | 16 | import java.util.*; 17 | 18 | import static dev.emortal.rayfast.casting.combined.CombinedCastResult.HitResult; 19 | import static dev.emortal.rayfast.casting.combined.CombinedCastResult.HitType; 20 | import static dev.emortal.rayfast.util.FunctionalInterfaces.Vector3dArea3dToBoolean; 21 | import static dev.emortal.rayfast.util.FunctionalInterfaces.Vector3dToBoolean; 22 | 23 | // TODO: Ordering & Collection for combined cast 24 | public class CombinedCast { 25 | 26 | private static final @NotNull Intersection> INTERSECTION_3D_FORWARDS_ANY = Intersection.builder() 27 | .vector3d() 28 | .forwards() 29 | .first() 30 | .distance(); 31 | 32 | private final double max; 33 | private final double min; 34 | private final double gridSize; 35 | private final boolean ordered; 36 | private final @Nullable FunctionalInterfaces.Vector3dArea3dToBoolean areaFunction; 37 | private final @Nullable Vector3dToBoolean gridFunction; 38 | 39 | @ApiStatus.Internal 40 | private CombinedCast(double min, double max, double gridSize, boolean ordered, 41 | @Nullable FunctionalInterfaces.Vector3dArea3dToBoolean areaFunction, 42 | @Nullable Vector3dToBoolean gridFunction) { 43 | this.max = max; 44 | this.min = min; 45 | this.gridSize = gridSize; 46 | this.ordered = ordered; 47 | this.areaFunction = areaFunction; 48 | this.gridFunction = gridFunction; 49 | } 50 | 51 | /** 52 | * Applies this CombinedCast to the specified areas, using the pos and dir to specify the line. 53 | * @param area3ds the area3ds to intersect 54 | * @param pos the line pos 55 | * @param dir the line dir 56 | * @return the list of all the hit results 57 | */ 58 | public @NotNull List apply(@NotNull Collection area3ds, @NotNull Vector3d pos, 59 | @NotNull Vector3d dir) { 60 | // Cache the squared distance to remove the sqrt operation when checking distance 61 | double maxRange = max * max; 62 | 63 | List hitResults = new ArrayList<>(); 64 | 65 | // Do Area3ds first 66 | Map area3dVector3dMap = new HashMap<>(); 67 | 68 | maxRange = handleArea3ds(area3ds, pos, dir, area3dVector3dMap, hitResults, maxRange); 69 | 70 | // Now do grid cast 71 | handleGridCast(pos, dir, hitResults, maxRange); 72 | 73 | // Sort hit results if ordered 74 | if (ordered) { 75 | hitResults.sort((result1, result2) -> (int) Math.signum(result1.distanceSquared() - result2.distanceSquared())); 76 | } 77 | 78 | return hitResults; 79 | } 80 | 81 | private double handleArea3ds(@NotNull Collection area3ds, @NotNull Vector3d pos, @NotNull Vector3d dir, 82 | @NotNull Map area3dVector3dMap, @NotNull List hitResults, 83 | final double maxRange) { 84 | 85 | double intermediateMaxRange = maxRange; 86 | 87 | // Now intersect all the area3ds 88 | for (Area3dLike area3dLike : area3ds) { 89 | // Do the deed 90 | Area3d area3d = area3dLike.asArea3d(); 91 | 92 | Vector3d intersection = area3d.lineIntersection(pos, dir, INTERSECTION_3D_FORWARDS_ANY).intersection(); 93 | 94 | if (intersection == null) { 95 | continue; 96 | } 97 | 98 | // cache intersection position 99 | area3dVector3dMap.put(area3d, intersection); 100 | 101 | // Continue if areaFunction specified not to cancel 102 | if (areaFunction != null && !areaFunction.apply(intersection, area3d)) { 103 | continue; 104 | } 105 | 106 | // Update max range 107 | intermediateMaxRange = Math.max(min, Math.min(intermediateMaxRange, VectorMathUtil.distanceSquared(pos, intersection))); 108 | } 109 | 110 | // Now collect all hit results 111 | area3dVector3dMap.forEach((area3d, vector3d) -> { 112 | 113 | // Filter out areas beyond the max range 114 | final double distanceSquared = VectorMathUtil.distanceSquared(pos, vector3d); 115 | if (distanceSquared > maxRange) { 116 | return; 117 | } 118 | 119 | // Generate and add hit result 120 | HitResult result = new HitResult(area3d, HitType.AREA3D, vector3d, distanceSquared); 121 | 122 | hitResults.add(result); 123 | }); 124 | 125 | return intermediateMaxRange; 126 | } 127 | 128 | private double handleGridCast(@NotNull Vector3d pos, @NotNull Vector3d dir, @NotNull List hitResults, 129 | final double maxRange) { 130 | double intermediateMaxRange = maxRange; 131 | 132 | // Create gridcast iterator 133 | Iterator iterator = GridCast.createExactGridIterator(pos, dir, gridSize, max); 134 | boolean running = true; 135 | 136 | // Run the iterator 137 | while (running && iterator.hasNext()) { 138 | final Vector3d vector3d = iterator.next(); 139 | 140 | double distanceSquared = VectorMathUtil.distanceSquared(pos, vector3d); 141 | 142 | // Generate and add hit result 143 | HitResult result = new HitResult(null, HitType.GRIDUNIT, vector3d, distanceSquared); 144 | 145 | hitResults.add(result); 146 | 147 | if (gridFunction == null) { 148 | continue; 149 | } 150 | 151 | if (!gridFunction.apply(vector3d)) { 152 | continue; 153 | } 154 | 155 | // Cap max range and stop gridcast 156 | intermediateMaxRange = Math.max(min, distanceSquared); 157 | running = false; 158 | } 159 | 160 | return intermediateMaxRange; 161 | } 162 | 163 | /** 164 | * Returns a builder of the combined cast. This builder is used to determine the attributes of the combined cast 165 | * that is being built. It is advised to build CombinedCast objects once and reuse them whenever possible. 166 | * @return the builder 167 | */ 168 | public static @NotNull Builder builder() { 169 | return new Builder(); 170 | } 171 | 172 | public static class Builder { 173 | private Builder() { 174 | } 175 | 176 | private double max = Double.MAX_VALUE; 177 | private double min = 0; 178 | private double gridSize = 1.0; 179 | private boolean ordered = false; 180 | private @Nullable FunctionalInterfaces.Vector3dArea3dToBoolean areaFunction; 181 | private @Nullable Vector3dToBoolean gridFunction; 182 | 183 | /** 184 | * Sets the distance to terminate the cast at. 185 | * @param max the distance to terminate the cast at 186 | * @return the builder 187 | */ 188 | public @NotNull Builder max(double max) { 189 | this.max = max; 190 | return this; 191 | } 192 | 193 | /** 194 | * Sets the minimum distance to cast to before terminating 195 | * @param min the minimum distance to cast to 196 | * @return the builder 197 | */ 198 | public @NotNull Builder min(double min) { 199 | this.min = min; 200 | return this; 201 | } 202 | 203 | /** 204 | * Sets the function to run for every area3d intersected, which limits the combined cast to the current 205 | * distance if the function returns true. 206 | *

207 | * Notes:
208 | * This function will be run for all area3ds within the max range set in the combined cast builder.
209 | * This function has no guaranteed order, regardless of {@link Builder#ordered(boolean)}.
210 | * @param areaFunction the consumer to run for every area3d, returns true to limit the cast 211 | * @return the builder 212 | */ 213 | public @NotNull Builder stopWhen(@Nullable Vector3dArea3dToBoolean areaFunction) { 214 | this.areaFunction = areaFunction; 215 | return this; 216 | } 217 | 218 | /** 219 | * Sets the function to run for every grid unit intersected, which limits the combined cast to the current 220 | * distance if the function returns true. 221 | * Notes:
222 | * This function will be run for all grid units until the max range is reached, or this function returns true.
223 | * This function has a guaranteed order, regardless of {@link Builder#ordered(boolean)}.
224 | * @param gridFunction the function to run for every grid unit, returns true to limit the cast 225 | * @return the builder 226 | */ 227 | public @NotNull Builder stopWhen(@Nullable Vector3dToBoolean gridFunction) { 228 | this.gridFunction = gridFunction; 229 | return this; 230 | } 231 | 232 | /** 233 | * Sets whether the {@link CombinedCast} result is ordered or not 234 | * @param ordered whether the {@link CombinedCast} result is ordered or not 235 | * @return the builder 236 | */ 237 | public @NotNull Builder ordered(boolean ordered) { 238 | this.ordered = ordered; 239 | return this; 240 | } 241 | 242 | /** 243 | * Sets the grid size of this cast 244 | * @param gridSize the size of the gridcast units 245 | * @return the builder 246 | */ 247 | public @NotNull Builder gridSize(double gridSize) { 248 | this.gridSize = gridSize; 249 | return this; 250 | } 251 | 252 | /** 253 | * Builds the {@link CombinedCast} object 254 | * @return the {@link CombinedCast} object 255 | */ 256 | public @NotNull CombinedCast build() { 257 | return new CombinedCast(min, max, gridSize, ordered, areaFunction, gridFunction); 258 | } 259 | } 260 | 261 | } 262 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/rayfast/area/area3d/Area3dRectangularPrism.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.rayfast.area.area3d; 2 | 3 | import dev.emortal.rayfast.area.Intersection; 4 | import dev.emortal.rayfast.util.FunctionalInterfaces; 5 | import dev.emortal.rayfast.util.Intersection3dUtils; 6 | import dev.emortal.rayfast.vector.Vector3d; 7 | import org.jetbrains.annotations.ApiStatus; 8 | import org.jetbrains.annotations.NotNull; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * A rectangular pyramid 15 | */ 16 | public interface Area3dRectangularPrism extends Area3d { 17 | 18 | // Coordinates 19 | double minX(); 20 | double minY(); 21 | double minZ(); 22 | double maxX(); 23 | double maxY(); 24 | double maxZ(); 25 | 26 | @Override 27 | @ApiStatus.Internal 28 | @SuppressWarnings("unchecked") 29 | default @NotNull R lineIntersection(double posX, double posY, double posZ, 30 | double dirX, double dirY, double dirZ, 31 | @NotNull Intersection intersection) { 32 | // Update and get planes 33 | double minX = minX(); 34 | double minY = minY(); 35 | double minZ = minZ(); 36 | double maxX = maxX(); 37 | double maxY = maxY(); 38 | double maxZ = maxZ(); 39 | 40 | List> results = null; 41 | 42 | Intersection.Collector collector = intersection.collector(); 43 | Intersection.Direction direction = intersection.direction(); 44 | 45 | if (collector == Intersection.Collector.ALL) { 46 | results = new ArrayList<>(); 47 | } 48 | 49 | { // Front 50 | Intersection.Result result = Intersection3dUtils.planeIntersection( 51 | this, 52 | // Line direction 53 | direction, 54 | // Line 55 | posX, posY, posZ, 56 | dirX, dirY, dirZ, 57 | // Plane 58 | minX, minY, minZ, 59 | minX, maxY, minZ, 60 | maxX, maxY, minZ 61 | ); 62 | 63 | if (result.intersection() != null) { 64 | switch (collector) { 65 | case SINGLE: return (R) result; 66 | case ALL: results.add(result); 67 | } 68 | } 69 | } 70 | 71 | { // Back 72 | Intersection.Result result = Intersection3dUtils.planeIntersection( 73 | this, 74 | // Line direction 75 | direction, 76 | // Line 77 | posX, posY, posZ, 78 | dirX, dirY, dirZ, 79 | // Plane 80 | minX, minY, maxZ, 81 | minX, maxY, maxZ, 82 | maxX, maxY, maxZ 83 | ); 84 | 85 | if (result.intersection() != null) { 86 | switch (collector) { 87 | case SINGLE: return (R) result; 88 | case ALL: results.add(result); 89 | } 90 | } 91 | } 92 | 93 | { // Left 94 | Intersection.Result result = Intersection3dUtils.planeIntersection( 95 | this, 96 | // Line direction 97 | direction, 98 | // Line 99 | posX, posY, posZ, 100 | dirX, dirY, dirZ, 101 | // Plane 102 | minX, minY, minZ, 103 | minX, maxY, minZ, 104 | minX, maxY, maxZ 105 | ); 106 | 107 | if (result.intersection() != null) { 108 | switch (collector) { 109 | case SINGLE: return (R) result; 110 | case ALL: results.add(result); 111 | } 112 | } 113 | } 114 | 115 | { // Right 116 | Intersection.Result result = Intersection3dUtils.planeIntersection( 117 | this, 118 | // Line direction 119 | direction, 120 | // Line 121 | posX, posY, posZ, 122 | dirX, dirY, dirZ, 123 | // Plane 124 | maxX, minY, minZ, 125 | maxX, maxY, minZ, 126 | maxX, maxY, maxZ 127 | ); 128 | 129 | if (result.intersection() != null) { 130 | switch (collector) { 131 | case SINGLE: return (R) result; 132 | case ALL: results.add(result); 133 | } 134 | } 135 | } 136 | 137 | { // Top 138 | Intersection.Result result = Intersection3dUtils.planeIntersection( 139 | this, 140 | // Line direction 141 | direction, 142 | // Line 143 | posX, posY, posZ, 144 | dirX, dirY, dirZ, 145 | // Plane 146 | minX, maxY, minZ, 147 | maxX, maxY, minZ, 148 | maxX, maxY, maxZ 149 | ); 150 | 151 | if (result.intersection() != null) { 152 | switch (collector) { 153 | case SINGLE: return (R) result; 154 | case ALL: results.add(result); 155 | } 156 | } 157 | } 158 | 159 | { // Bottom 160 | Intersection.Result result = Intersection3dUtils.planeIntersection( 161 | this, 162 | // Line direction 163 | direction, 164 | // Line 165 | posX, posY, posZ, 166 | dirX, dirY, dirZ, 167 | // Plane 168 | minX, minY, minZ, 169 | maxX, minY, minZ, 170 | maxX, minY, maxZ 171 | ); 172 | 173 | if (result.intersection() != null) { 174 | switch (collector) { 175 | case SINGLE: return (R) result; 176 | case ALL: results.add(result); 177 | } 178 | } 179 | } 180 | if (results == null) { 181 | return (R) Intersection.Result.none(this); 182 | } 183 | 184 | return (R) results; 185 | } 186 | 187 | @Override 188 | @ApiStatus.Internal 189 | default @NotNull R lineIntersection(@NotNull Vector3d pos, @NotNull Vector3d dir, @NotNull Intersection intersection) { 190 | return lineIntersection(pos.x(), pos.y(), pos.z(), dir.x(), dir.y(), dir.z(), intersection); 191 | } 192 | 193 | /** 194 | * Generates a wrapper for the specified object using the specified getters. 195 | *

196 | * This is a suboptimal implementation. An ideal implementation implements the 197 | * Area3dRectangularPrism interface directly on the object. 198 | * 199 | * @param object the object to wrap 200 | * @param minXGetter the getter for minX 201 | * @param minYGetter the getter for minY 202 | * @param minZGetter the getter for minZ 203 | * @param maxXGetter the getter for maxX 204 | * @param maxYGetter the getter for maxY 205 | * @param maxZGetter the getter for maxZ 206 | * @param the type of the wrapped object 207 | * @return the area that is represented by this wrapped object 208 | */ 209 | static Area3dRectangularPrism wrapper(T object, 210 | FunctionalInterfaces.DoubleWrapper minXGetter, 211 | FunctionalInterfaces.DoubleWrapper minYGetter, 212 | FunctionalInterfaces.DoubleWrapper minZGetter, 213 | FunctionalInterfaces.DoubleWrapper maxXGetter, 214 | FunctionalInterfaces.DoubleWrapper maxYGetter, 215 | FunctionalInterfaces.DoubleWrapper maxZGetter) { 216 | return new Area3dRectangularPrism() { 217 | @Override 218 | public double area() { 219 | double minX = minX(); double minY = minY(); double minZ = minZ(); 220 | double maxX = maxX(); double maxY = maxY(); double maxZ = maxZ(); 221 | return (maxX - minX) * (maxY - minY) * (maxZ - minZ); 222 | } 223 | 224 | @Override 225 | public double minX() { 226 | return minXGetter.get(object); 227 | } 228 | 229 | @Override 230 | public double minY() { 231 | return minYGetter.get(object); 232 | } 233 | 234 | @Override 235 | public double minZ() { 236 | return minZGetter.get(object); 237 | } 238 | 239 | @Override 240 | public double maxX() { 241 | return maxXGetter.get(object); 242 | } 243 | 244 | @Override 245 | public double maxY() { 246 | return maxYGetter.get(object); 247 | } 248 | 249 | @Override 250 | public double maxZ() { 251 | return maxZGetter.get(object); 252 | } 253 | }; 254 | } 255 | 256 | /** 257 | * Generates a wrapper for the specified object using the specified getters. 258 | *

259 | * This is a suboptimal implementation. An ideal implementation implements the 260 | * Area3dRectangularPrism interface directly on the object. 261 | * 262 | * @param object the object to wrap 263 | * @param minGetter the getter for min 264 | * @param maxGetter the getter for max 265 | * @param the type of the wrapped object 266 | * @return the area that is represented by this wrapped object 267 | */ 268 | static Area3dRectangularPrism wrapper(T object, 269 | FunctionalInterfaces.Vector3dWrapper minGetter, 270 | FunctionalInterfaces.Vector3dWrapper maxGetter) { 271 | return wrapper( 272 | object, 273 | ignored -> minGetter.apply(object).x(), 274 | ignored -> minGetter.apply(object).y(), 275 | ignored -> minGetter.apply(object).z(), 276 | ignored -> maxGetter.apply(object).x(), 277 | ignored -> maxGetter.apply(object).y(), 278 | ignored -> maxGetter.apply(object).z() 279 | ); 280 | } 281 | 282 | /** 283 | * Creates a new immutable {@link Area3dRectangularPrism} instance. 284 | * @param minX the minimum x value 285 | * @param minY the minimum y value 286 | * @param minZ the minimum z value 287 | * @param maxX the maximum x value 288 | * @param maxY the maximum y value 289 | * @param maxZ the maximum z value 290 | * @return the new instance 291 | */ 292 | static Area3dRectangularPrism of(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { 293 | return new Area3dRectangularPrismImpl(minX, minY, minZ, maxX, maxY, maxZ); 294 | } 295 | 296 | @Override 297 | default double area() { 298 | return (maxX() - minX()) * (maxY() - minY()) * (maxZ() - minZ()); 299 | } 300 | } 301 | --------------------------------------------------------------------------------