Files
3DChess/app/src/main/java/chess/view/DDDrender/Camera.java
Persson-dev b33e333276
All checks were successful
Linux arm64 / Build (push) Successful in 38s
merge branch 3dunstable
2025-05-17 15:58:36 +02:00

87 lines
2.3 KiB
Java

package chess.view.DDDrender;
import org.joml.Matrix4f;
import org.joml.Vector2f;
import org.joml.Vector3f;
import org.joml.Vector4f;
public class Camera {
public static final float fov = 70.0f;
public static final float zNear = 0.01f;
public static final float zFar = 1000.0f;
private static final Vector3f up = new Vector3f(0.0f, -1.0f, 0.0f);
private static final Vector3f center = new Vector3f(0.0f, 0.0f, 0.0f);
private final float distance = 1.5f;
private final float camHeight = 1.5f;
private float aspectRatio;
private float angle;
private Vector3f pos;
public Camera() {
this.pos = new Vector3f(0.0f, camHeight, 0.0f);
setRotateAngle(0.0f);
}
public void move(float x, float y) {
this.pos.x += x;
this.pos.y += y;
}
public void setRotateAngle(float angle) {
this.angle = angle;
updatePostion();
}
private void updatePostion() {
final float finalX = (float) Math.sin(angle);
final float finalZ = (float) -Math.cos(angle);
this.pos.set(distance * finalX, this.pos.get(1), distance * finalZ);
}
public float getRotateAngle() {
return angle;
}
public Vector3f getPos() {
return pos;
}
public float getFov() {
return fov;
}
public void setAspectRatio(float aspectRatio) {
this.aspectRatio = aspectRatio;
}
public Matrix4f getPerspectiveMatrix() {
return new Matrix4f().perspective((float) (Math.toRadians(fov)), aspectRatio, zNear, zFar);
}
public Matrix4f getViewMatrix() {
return new Matrix4f().lookAt(pos, center, up);
}
public Vector2f getCursorWorldFloorPos(Vector2f screenPos, int windowWidth, int windowHeight) {
float relativeX = (screenPos.x / (float) windowWidth * 2.0f) - 1.0f;
float relativeY = 1.0f - (screenPos.y / (float) windowHeight * 2.0f);
Vector4f rayClip = new Vector4f(relativeX, relativeY, -1.0f, 1.0f);
Vector4f rayEye = getPerspectiveMatrix().invert().transform(rayClip);
rayEye = new Vector4f(rayEye.x, rayEye.y, -1.0f, 0.0f);
Vector4f rayWorld = getViewMatrix().invert().transform(rayEye);
float lambda = -this.pos.y / rayWorld.y;
return new Vector2f(lambda * rayWorld.x + this.pos.x, lambda *
rayWorld.z + this.pos.z);
}
}