WebGL: how to fetch/cache shaders efficiently?
I am currently developing a WebGL-based application, and I am having some trouble with shader storage…
I see in most examples that shaders are written in plaintext in the xHTML file itself. However this clutters the file and does not allow caching. Also, it's not convinient to edit and reuse them. Having one file per shader is the best for organization. I can still in开发者_运维技巧sert them, with PHP, in the generated output, but it increases the size of the pages and can't be efficiently cached.
Another solution is to fetch every shader with XmlHttpRequest, but I'm afraid the number of HTTP requests for a fresh page load (especially when you have dozens of shaders!) might quickly become a performance issue.
Finally, I've been thinking about dynamically putting all the shaders in a file, then loading it with a XmtHttpRequest. It's only one request, for one file that can be cached locally by the browser. Yet, my JS is not that good and I don't know how I should do it. I would build the file from the shaders in PHP, and extract them in Javascript.
But how ? I've been thinking about using XML or JSON to store headers in the big file, and I'd like help about the Javascript code to extract them. Thanks!
My PHP-generated shader file would look like this :
<vertex-shader id="shaderA">
…shader code…
</vertex-shader>
<fragment-shader id="shaderB">
…etc…
</fragment-shader>
Or :
{ "vertexshaderA": "…shader code…",
"fragmentshaderA": "…etc…" }
You can use the PHP JSON library. Read in all the shader files, then create an associative array out of them and use the json_encode
function to create a JSON object.
$arr = array ('vertexShaderA'=>code,'vertexShaderB'=>code);
echo json_encode($arr);
Then use XmlHttpRequest in JS to fetch the JSON object. Or use PHP to generate a JS file that sets a global (e.g. echo "Shaders =", json_encode($shaders)
) and include it using a <script> tag.
精彩评论