I still stuck.
I did this:
- When I store the vertices, I also store those as a triangle (in the same order). Something like this [ [VERT_1,VERT_2,VERT_3], [VERT_4,VERT_5,VERT_6], …]
- When I calculate the surface hit point, I also calculate the hit triangle’s index
- I send the currentlz hit triangle’s index to the vertex shader, and try to figure it out if the actual vertex (gl_ VertexID) is part of that triangle
But it does not work. As I read about gl_VertexIndex more and more, I got myself more confused as well. So what is gl_VertexID? If I have a cube (with unique vertices), it can be 0-23 (6*4) OR it can be 0-2 (as an index of the actual triangle)?
So, what I have is this:
- A hit point
- The object’s triangles in order
How can I then check in the vertex shader, if the actual vertex is in the hit triangle?
Hit point calculation:
Vector3f pos = gameObject.getTransform().getPosition();
Spheref spheref = new Spheref(pos.x, pos.y, pos.z, gameObject.getRadius());
if (Intersectionf.intersectRaySphere(cameraRay, spheref, nearFar) && nearFar.x < closestDistance) {
surfaceHitPoint = new Vector3f(Camera.main.getCamPosition()).add(Camera.main.getCameraDirection().mul(nearFar.x));
int triangleIndex = getTriangleIndex(surfaceHitPoint, gameObject.getMesh().getTriangles(), gameObject.getTransform());
}
Also, I draw this way:
GL31.glDrawElementsInstanced(GL_TRIANGLES, batch.getMesh().getIndices().length, GL_UNSIGNED_INT, 0, gameObjectsCount);
And here is how I check if I hit the triangle (maybe there is the problem):
private int getTriangleIndex(Vector3f surfaceHitPoint, List<List<Vector3f>> triangles, Transform transform) {
for (int i = 0; i < triangles.size(); i++) {
if (isInThisTriangle(surfaceHitPoint, triangles.get(i), transform)) {
return i;
}
}
return -1;
}
private boolean isInThisTriangle(Vector3f hitPoint, List<Vector3f> triangle, Transform transform) {
Vector3f a = new Vector3f(triangle.get(0));
Vector3f b = new Vector3f(triangle.get(1));
Vector3f c = new Vector3f(triangle.get(2));
transform.notifyDataChanged();
Vector4f p0 = new Vector4f(a.x, a.y, a.z, 1).mul(transform.getTransformationMatrix());
Vector4f p1 = new Vector4f(b.x, b.y, b.z, 1).mul(transform.getTransformationMatrix());
Vector4f p2 = new Vector4f(c.x, c.y, c.z, 1).mul(transform.getTransformationMatrix());
a.set(p0.x, p0.y, p0.z);
b.set(p1.x, p1.y, p1.z);
c.set(p2.x, p2.y, p2.z);
// 1. the unit normal of triange (A, B, P) - call it N1
// 2. the unit normal of triangle (B, C, P) - call it N2
// 3. the unit normal (C,A,P) called N3
Vector3f n1 = b.sub(a).cross(new Vector3f(hitPoint).sub(a)).normalize();
Vector3f n2 = c.sub(b).cross(new Vector3f(hitPoint).sub(b)).normalize();
Vector3f n3 = a.sub(c).cross(new Vector3f(hitPoint).sub(c)).normalize();
float res1 = new Vector3f(n1).dot(n2);
float res2 = new Vector3f(n2).dot(n3);
if (res1 > 0.99 && res2 > 0.99) {
return true;
}
return false;
}