11/4/07

Read shader from file without stdlib

Over at Lighthouse there are some useful tutorials and some example code. One piece of code I've found all over is the "read a shader from a file" code. Unfortunately its not much use for size coders as it uses stdlib. Essentially it allows you to write shaders in a normal text file and load them as a string.So here I've done a conversion using win32 equivalent functions. It doesn't check error codes (wasted bytes) so be careful to pass in the right filename. I'm not sure this is the smallest way, its just a translation of Lighthouse code.

Essentially adding this code to your intro allows you to develop the shader without constant recompiles.
#include "windows.h"

char *textFileRead(char *fn) {

char *content=NULL;
DWORD dummy;

HANDLE fp = CreateFile (fn, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD count=SetFilePointer (fp, 0 ,NULL, FILE_END);
SetFilePointer (fp, 0 ,NULL, FILE_BEGIN);
content = (char *)GlobalAlloc(0,(SIZE_T)(count+1));
ReadFile(fp, (LPVOID)content, count, &dummy, NULL);
content[count] = '\0';
CloseHandle(fp);
return content;
}

6 comments:

  1. Anonymous5/11/07

    hi,
    the end of CreateFile() line is ot visible for me. could you fix it? thx

    ReplyDelete
  2. Hi there, I do apologise, I haven't figured out how to present code on this website very well yet. However, the end of the line should now be visible.

    ReplyDelete
  3. Anonymous6/11/07

    Wow... This blog rulez big time. :)

    ReplyDelete
  4. Anonymous7/11/07

    Shouldn't content[count+1] = '\0'; be content[count] = '\0'; instead?

    ReplyDelete
  5. Thanks for the comments Jimmi. I think you may be right about the code. I had a weird effect when using it too, so I'm going to check it out ASAP. Thanks very much.

    ReplyDelete
  6. Seems you were right Jimmi, thanks.

    ReplyDelete