For a project i need to find out triangles that are directly seen by the camera / user. Triangles that are occluded by other triangles should be ignored. There may be 200 thousand triangles in a model, so raycasting on a CPU is no possibility due to performance. Is there something build in to unity or opengl that can do this? If not how would you approach this problem? Many 3d editing software use techniques, e. g. to select or slice only triangles that are visible.
-
\$\begingroup\$ Can you help us understand what you're using this for? There may be simpler or more complicated solutions depending on the ultimate application. \$\endgroup\$– DMGregory ♦Commented May 15, 2021 at 17:16
-
\$\begingroup\$ That you for your comment. The project is a very simple 3d modeling tool, where the user can select vertices with a rectangular box. All vertices should then be selected that are visible and inside the box. \$\endgroup\$– Marion PilooCommented May 15, 2021 at 17:41
1 Answer
You could use a rendering pass that writes "triangle IDs" to an offscreen framebuffer instead of rendering colors. Then you can read the pixels from the offscreen framebuffer and get the IDs of all visible triangles. That means you need to extend your vertex data to contain such triangle IDs, create a 32-bit-per-pixel framebuffer, and write a simple fragment shader that only writes the triangle IDs into the framebuffer (and discards color information etc). Depth-testing must of course be enabled.
Note that this solution might miss very small triangles that don't even occupy a single pixel. It also won't work properly with triangle strips (you'll need "3-vertices-per-triangle" vertex buffers instead).
-
\$\begingroup\$ Okay this is a pretty good idea! The mesh is already has 3 vertices per triangle. On the cpu I will then iterate over each pixel of the framebuffer i guess. I think the very small triangles are a trade off to deal with or maybe it is possible with compute shaders? Thank you for your answer! \$\endgroup\$ Commented May 15, 2021 at 19:40
-
\$\begingroup\$ I don't think you can handle the "triangle smaller than a pixel" case without spending a lot of computation time on them, sadly. What you can do, however, is to post-process the results and also select all triangles that are completely surrounded by visible triangles, for example. Another work-around would be to increase the resolution for this visibility-test rendering pass. A combination of both will probably give the best results. \$\endgroup\$ Commented May 15, 2021 at 19:53