miércoles, 29 de enero de 2014

Stencil by Discard-ing pixels through a shader

Drawing alpha objects tends to be very expensive. If you want to draw
a lot of alpha objects to simulate grass or plants, it quickly becomes
TOO expensive, lowering dramatically your FPSs.
This happens because in order to render alpha objects, the renderer
has to sort them by distance first, you end up having to sort 300
objects.
There is another problem with alpha objects: when an object is very large,
for example a plane, it cannot be SORTED by distance correctly because
a vertex in the end of the plane would have another distance pass than
the object itself; you end up having artifacts, where a pixel that should
be behind another object, is rendered in front.
As a hobby game programmer i used to have this issues with the alpha objects
a lot, but did not know how to fix them, until, when I started working as
CTO in Hollow Games, i finally found the ultimate fix.
I came to the answer, because I kept thinking, that a plant, for example
is not REALLY an Alpha, but some sort of stencil, where the renderer
has got to either write the pixel or dont. There is a function in CG
(obviously there should be one in GLSL, GLSLES and HLSL as well, but
havent had to use them) called discard that does exactly that.
So I wrote a new shader (its an UberShader in my engine) that
when it reads the texture (tex2D) it checks if the alpha byte is less
than say 0.9, if it is so, the renderer should not write the pixel.
With this DISCARD-stencil technique, the renderer is not sorting
anything, and for objects like plants, it works like a charm. If your 
texture is in DDS format (honestly it should be) there is an option
for 1 bit alpha, instead of explicit alpha, that way, the texture
is lighter than an actual alpha, and 1 bit is all you need to decide
if to render or not to a pixel.
There are some other advantages to this technique, for example
if you are using deferred lightning, alphas are a problem, but
discard-stencils are not, they can be rendered as any other object.
Another advantage is that discarding is completely friendly with
bump mapping, which can seriously upgrade your plants, also, 
discarding tends to be neater.
Oh, by the way, most game programmers in the industry probably
knew about this, but me as a hobby game programmer did not
have a clue.


 Alphas instead of stencils, look dirty
 We can see here, how some grasses are not being rendered in the right order
 Stencils look much more clean
Stencils with bump in the leaves

Have a good one!

No hay comentarios:

Publicar un comentario