Stripping comments from Shader bytecodes

January 15, 2009 @ 21:37 | In CodeGems, Programming | 1 Comment | twitter rss digg

In DirectX, when compiling a shader with D3DXCompileShader() a buffer containing the shader bytecodes is received. Apart from the bytecodes, extra content like debug and symbol table information is embedded. That extra information is added in form of comments that probably can be eliminated because you are already processing it at compile-time and it is not needed at run-time when loading the shader.

If you can do without that information the following code will help you to save a few bytes, even halving the size of the byte-code in the best cases.

Although not documented in the DirectX SDK, this CodeGem is not an undocumented hack. The Direct3D shader code format is documented in the MSDN, so it probaly won’t change in future revision of DirectX v9.0 (if there is going to be any more…)

D3DPtr<ID3DXBuffer> StripComments(const D3DPtr<ID3DXBuffer>& code)
{
    // Calculates the new size (without comments)
    int* codeData = static_cast<int*>(code->GetBufferPointer());
    unsigned int sizeInWords = code->GetBufferSize() / 4;
    unsigned int strippedSizeInWords = sizeInWords;
 
    for (unsigned int i = 0; i < sizeInWords; i++)
    {
        if ((codeData[i] & 0xffff) == D3DSIO_COMMENT)
        {
            int commentSize = codeData[i] >> 16;
            strippedSizeInWords -= 1 + commentSize;
            i += commentSize;
        }
    }
 
    // Creates a new buffer with the original code but omitting the comments
    D3DPtr<ID3DXBuffer> strippedCode;
    V(D3DXCreateBuffer(strippedSizeInWords * 4, strippedCode.GetPtrForInit()));
 
    int* strippedCodeData = static_cast<int*>(strippedCode->GetBufferPointer());
    size_t offset = 0;
 
    for (unsigned int i = 0; i < sizeInWords; i++)
    {
        if ((codeData[i] & 0xffff) == D3DSIO_COMMENT)
        {
            int commentSize = codeData[i] >> 16;
            i += commentSize;
        }
        else
        {
            strippedCodeData[offset++] = codeData[i];
        }
    }
 
    return strippedCode;
}



  1. We strip all of our shaders of comments & debug information on 360 and PS3, but not on DX as it hasn’t been an issue there. But this could save a bit of memory and I/O so should give it a try.

    Thanks for the post!



    Comment by repi
    January 16, 2009 @ 0:43 #


Thu, 24 Apr 2014 03:14:09 +0000 / 27 queries. 1.332 seconds / 2 Users Online

gentoo link wordpress link apache link PHP link

Theme modified from Pool theme. Valid XHTML and CSS