2013-10-10 46 views
1

我追求一種閃電般快速的java方法來檢查點是否在三角形內。性能檢查點是否在三角形內(3D)

我發現了一紙從卡斯帕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的?

在此先感謝!

+1

你問過之前你真的嘗試過嗎?如果你做了什麼你的結果? – Kevin

+0

@Kevin我不知道如何將C++代碼片段轉換爲java(whats up with return語句?),所以我需要向正確的方向微調。 – Wilco

+0

檢查此:http://stackoverflow.com/questions/2464902/determine-if-a-point-is-inside-a-triangle-formed-by-3-points-with-given-latitude – Araw

回答

1

你找到的代碼,如果正確的話,應該比你的代碼快得多。返回聲明

return ((in(z)& ~(in(x)|in(y))) & 0x80000000); 

只是一個檢查浮點數的符號位的棘手方法;如果我沒有完全錯誤,它就等於:

return z < 0 && x >= 0 && y >= 0; 

本文的內容應該證實這一點。剩下的我猜你可以轉換自己。

+0

非常感謝! – Wilco

相關問題