So I want to write a system where, you can put any and everything you want in a scene. Then you can place a bounding box of some sort to denote the area in which a player can move. Then it goes through and tests whether or not a face is visible from that denoted area, and if it isn’t, then it will delete the face.
The purpose of this is to automatically delete all back faces in a scene.
How could this be done? Short of raytracing from every pixel in the camera. Is there any way through a post process shader that it could detect which faces are viewable?
There’s no need to involve shaders at all, and in fact considering “pixels” at all would be the worst way to go.
Let’s start by assuming a single viewing angle.
If the model has normals, this is easy. Just use yourCamera.transform.InverseTransformDirection(faceNormal). Now look at the Z value. If the Z value is positive, it’s facing away from the camera. (You may want to check if Z > 0.25 or something slightly higher, as Z=0.01 could be mostly sideways that still gets rendered from an angle) If all three of a face’s normals (keeping in mind that a face is a triangle that is a reference to three Vector3’s), then boom! gone.
If the model doesn’t have normals, you’ll have to calculate one. If needed I can dig up the formula for this, but IIRC, given 3 points, it involves the Vector3.Dot product of (c-a, b-a).
Now, you want to check this from every space within a bounding box, you’ll want to have the camera look all four directions, and for each face, check if its position is within the view frustum (or close). If it’s in the view frustum and the normal is positive, it’s gone.
HOWEVER, you probably shouldn’t actually do this (assuming your goal is performance improvements). Removing <50% of the faces of all the meshes in the scene is going to do very little to boost performance. Most of the time spent rendering a mesh comes from two things: 1) overhead, and 2) fillrate. Back-facing triangles are contributing to neither of these things. For all the trouble you’ll go to to implement your own backface culling, I bet you’ll see no discernible performance increase at all.
1 Like
I also wanted to delete faces that never get seen because they are occluded by other faces. So just testing for facing direction wouldn’t be sufficient.
And the reason for me wanting to do this isn’t actually a performance boost, it’s rather a memory and workflow boost. The memory boost primarily having to do with lightmaps. In a lot of scenes that get constructed, I think easily over half the lightmaps get put to things that never get seen. Which means, accurately deleting all faces that never get seen could double the resolution of your lightmaps with the same memory footprint.