2
\$\begingroup\$

I'm ramping up on WebGL and was wondering what is the best way to specify my vertex and fragment shaders.

Looking at some tutorials, the shaders are embedded directly in the HTML. (And referenced via an ID.) For example:

<script id="shader_1-fs" type="x-shader/x-fragment"> 
  precision highp float;
  void main(void) {
    // ... 
  }
</script> 

<script id="shader_1-vs" type="x-shader/x-vertex"> 
  attribute vec3 aVertexPosition;

  uniform mat4 uMVMatrix;
  // ...

My question is, is it possible to have my shaders referenced in a separate file? (Ideally as plain text.) I presume this is straight forward in JavaScript. Is there essentially a way to do this:

var shaderText = LoadRemoteFileOnSever('/shaders/shader_1.txt');
\$\endgroup\$
4
\$\begingroup\$

Yes, it's simple. You can just make an AJAX request to the file, and pass the code to WebGL's shaderSource function.

\$\endgroup\$
  • \$\begingroup\$ Yes. Note that if you use XMLHttpRequest asynchronously, then you'll need to wait until the data are loaded before calling .shaderSource. A game with lots of assets probably needs to do this with lots of images and other things as well, so you can combine them all into the same code which waits for multiple load events to complete. That's what I did (with images and sounds, not shaders). \$\endgroup\$ – MarkR Jan 1 '13 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.