lwjglgamedev / lwjglbook-leg

Source code of the chapters of the book 3D Game Development with LWJGL 3
https://ahbejarano.gitbook.io/lwjglgamedev/
Apache License 2.0
560 stars 202 forks source link

Suggestion: Shader optimization #83

Closed ayangd closed 4 years ago

ayangd commented 4 years ago

Hi! I've been reading your book and following the tutorials. They're very helpful!

After I followed along, I noticed that I need to use some if statement inside the shader program. I searched online for that and somebody tells that it's not a good idea to do that. The quote from this:

Having conditionals in shaders can often have a serious performance impact on the code. Compilers can sometimes find clever ways to optimize them away, but if your shader code really does have to branch and perform comparisons the speed can drop off significantly. Most of the time the GPU will simply perform the operations encoded by both branches and throw away one of the results. Some modern GPUs can actually branch properly, but doing this is often equally slow unless the branch contains a lot of code.

I wanted my mesh to can have either color or texture, so I found this. But then, I realized you made an if statement in the later chapters, which is why I wrote this.

lwjglgamedev commented 4 years ago

Thanks for your comments.

Branch performance impact on shaders is not so easy. It depends on many things, the concrete implementation of the hardware, the variables used for the condition, etc. Here you can find some opinions on this:

https://stackoverflow.com/questions/37827216/do-conditional-statements-slow-down-shaders

Having conditions on uniforms should not have a noticeable impact. In any case, I think that examples are more "readable" using these statements, so I prefer to leave them as they are. There are some other areas in the book that could be optimized too, but I prefer to stick with more compact samples. An don't forget that "premature optimization is the root of all evil" ;).

Best regards.