Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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');
share|improve this question
add comment

1 Answer 1

up vote 4 down vote accepted

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

share|improve this answer
    
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). –  MarkR Jan 1 '13 at 11:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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