In another win for open-source the developers behind Natural Selection 2 have opened up the code they use to parse HLSL calls into OpenGL's GLSL.
It has been released under the MIT license, so do with it as you wish as long as the MIT license sticks around.
This is after the developers also opened up the original Natural Selection
QuoteHLSL Parser and GLSL code generator
This is the code we used in Natural Selection 2 to convert HLSL shader code to GLSL for use with OpenGL. The code is pulled from a larger codebase and has some dependencies which are not included, so the code will not compile as-is. These dependencies are all very basic though (array classes, memory allocators, etc.) so replacing them should be simple if you want to use this code.
The parser is designed to work with HLSL code written in the legacy Direct3D 9 style (e.g. D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY should be used with D3D11). The parser works with cbuffers for uniforms, so in addition to generating GLSL, there is a class provided for generating D3D9-compatible HLSL which doesn't support cbuffers. The GLSL code requires version 3.1 for support of uniform blocks. The parser is designed to catch all errors and generate "clean" GLSL which can then be compiled without any errors.
The HLSL parsing is done though a basic recursive descent parser coded by hand rather than using a parser generator. We believe makes the code easier to understand and work with.
To get consistent results from Direct3D and OpenGL, our engine renders in OpenGL "upside down". This is automatically added into the generated GLSL vertex shaders.
Although this code was written specifically for our use, we hope that it may be useful as an educational tool or a base for someone who wants to do something similar.
I hope some other developers find it useful, it is interesting to see more than just Valve doing things like this. Who knows maybe it could even help Valve themselves.
Who knows, maybe some helpful developers can peek at NS2's HLSL->GLSL code on github and improve the OpenGL performance as it is quite the hog.
For those that don't know, Valve also does something similair using their own open-source library called ToGL
. Although Valve's Source Engine 2 should be using OpenGL directly rather than some sort of translation layer.
It seems even Unreal Engine also uses something similar (seeing a pattern here!), I am sure it makes things easier, but performance wise it just isn't as good as calling OpenGL directly.