currently i am trying to implement a ray tracer with triangle mesh in WebGL 2. So far i am loading the data in a buffer texture and then i unpack them like this:
for (int i = 0; i < vertsCount; i += 3) {
a = texelFetch(uMeshData, ivec2(i, 0), 0);
b = texelFetchOffset(uMeshData, ivec2(i, 0), 0, ivec2(1, 0));
c = texelFetchOffset(uMeshData, ivec2(i, 0), 0, ivec2(2, 0));
bool isHit = hitTriangleSecond(R_.orig, R_.dir, a.xyz, b.xyz, c.xyz, uvt, triangleNormal, intersect, z);;
if (isHit) {
if (z<mindist && z > 0.001) {
//weHitsomething
}
}
}
You know where the problem lies. When i try to load a mesh with many triangles it gets too slow, especially when i add reflection level like 4 times, because i have to check with every triangle, every frame... so not optimal.
I have heard about the Bounding box technique and some tree storage data. But i do not know how to do it.
It would be nice if someone provided some information about that. And besides that.
I am thinking also of a second texture with some information about each mesh that i load, but texelfetch is not like arrays when you have index, so you know which objects are in this direction that ray hits.
So my question is how to check the "nearest" triangles in the ray direction.
Implementing a raytracer in WebGL is quite an advanced task. I would advise starting simple. For example, using a 3D texture and storing up to 4 triangle indexes in each of its cells/pixels. (You will have to raymarch through the texture until you hit a triangle.) Once you have a triangle index, you can look up the vertices in a second texture (called uMeshData in your code.)
You can build the 3D texture data in Javascript, during your initialization phase. (Later, you could probably implement this on the GPU by rendering the triangles onto the 3D texture's 2D slices, using the depth buffer to select the nearest triangle to each pixel.)
This will fail to produce the correct result if there are more than 4 triangles overlapping a 3D texture cell/pixel. It is also not very efficient (due to the redundancy of the fixed-step raymarching), but at least moves you in the right direction. Once you've accomplished that, you can try more advanced solutions (which will probably involve a tree, e.g. a bounding volume hierarchy.)