»_

2013-04-13 16:51:38

Loading WebGL shaders from file

Share

Categories webgl shaders

Hi everyone.
I've been playing around with some webgl for some time now and from what's I've seen many people simply paste vertex and fragment shaders into html code. Of course if works but once you start creating a more complex project you might need to have this code stored in a specific files. After poking around with some samples and XMLHTTPREQUEST I came up with a small but robust solution:
 

getSource = function(path) {
    var n = null;
    var r = new XMLHttpRequest();
    r.open("GET", path, false);
    r.send(n);
    return (r.status === 200) ? r.responseText : null;
}

getShader = function(gl, type, path){
    var shader = gl.createShader(type);
    gl.shaderSource(shader, this.getSource(path));
    gl.compileShader(shader);

    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        alert(gl.getShaderInfoLog(shader));
        return null;
    }

    return shader;
}

// var gl = our gl instance for canvas element;

var fragmentShader = getShader(gl, gl.FRAGMENT_SHADER, 'path/to/shader/fs.glsl');
var vertexShader = getShader(gl, gl.VERTEX_SHADER, 'path/to/shader/vs.glsl');

shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);

// ... rest of your code

Hope this helps

No comments

Leave a comment

Array
(
    [type] => 32
    [message] => Module 'mssql' already loaded
    [file] => Unknown
    [line] => 0
)