我正在寻求一种闪电般快速的java方法来检查一个点是否在三角形内。
我在Kasper Fauerby的论文中找到了以下c ++代码:
typedef unsigned int uint32;
#define in(a) ((uint32&) a)
bool checkPointInTriangle(const VECTOR& point, const VECTOR& pa,const VECTOR& pb, const VECTOR& pc) {
VECTOR e10=pb-pa;
VECTOR e20=pc-pa;
float a = e10.dot(e10);
float b = e10.dot(e20);
float c = e20.dot(e20);
float ac_bb=(a*c)-(b*b);
VECTOR vp(point.x-pa.x, point.y-pa.y, point.z-pa.z);
float d = vp.dot(e10);
float e = vp.dot(e20);
float x = (d*c)-(e*b);
float y = (e*a)-(d*b);
float z = x+y-ac_bb;
return (( in(z)& ~(in(x)|in(y)) ) & 0x80000000);
}
我想知道这个代码段是否可以转换为java,如果是,那么它是否会胜过我的Java代码:
public class Util {
public static boolean checkPointInTriangle(Vector p1, Vector p2, Vector p3, Vector point) {
float angles = 0;
Vector v1 = Vector.min(point, p1); v1.normalize();
Vector v2 = Vector.min(point, p2); v2.normalize();
Vector v3 = Vector.min(point, p3); v3.normalize();
angles += Math.acos(Vector.dot(v1, v2));
angles += Math.acos(Vector.dot(v2, v3));
angles += Math.acos(Vector.dot(v3, v1));
return (Math.abs(angles - 2*Math.PI) <= 0.005);
}
public static void main(String [] args) {
Vector p1 = new Vector(4.5f, 0, 0);
Vector p2 = new Vector(0, -9f, 0);
Vector p3 = new Vector(0, 0, 4.5f);
Vector point = new Vector(2, -4, 0.5f);
System.out.println(checkPointInTriangle(p1, p2, p3, point));
}
}
和Vector类:
public class Vector {
public float x, y, z;
public Vector(float x, float y, float z) {
this.x = x; this.y = y; this.z = z;
}
public float length() {
return (float) Math.sqrt(x*x + y*y + z*z);
}
public void normalize() {
float l = length(); x /= l; y /= l; z /= l;
}
public static float dot(Vector one, Vector two) {
return one.x*two.x + one.y*two.y + one.z*two.z;
}
public static Vector min(Vector one, Vector two) {
return new Vector(one.x-two.x, one.y-two.y, one.z-two.z);
}
}
还是有更快的Java方法吗?
提前致谢!
答案 0 :(得分:1)
你找到的代码,如果正确,应该比你得到的代码快得多。退货声明
return (( in(z)& ~(in(x)|in(y)) ) & 0x80000000);
只是检查浮点数的符号位的一种棘手的方法;如果我没有完全错,那相当于:
return z < 0 && x >= 0 && y >= 0;
该文的内容应该证实这一点。剩下的我猜你可以改变自己。