Loading GLSL non-asynchonously

Hi all,

I’m using a file ShaderLoader, which I believe loads up a whole directory of glsl, then you can apply these. However, I’m not currently waiting on this, hence when I use it my shaders are empty!

Hence I’ve love to know how I can upload a .glsl file more instantaneously. This is how i’m currently doing it:

var shaders = new ShaderLoader("shaders", "shaders");

// For title

shaders.load("global/vs-title", "title", "vertex");
shaders.load("global/fs-title", "title", "fragment");

loader = new Loader();
shaders.shaderSetLoaded = function () {
loader.onLoad();
};

console.log('shader-title', shaders);
console.log('shader vertex', shaders.vertexShaders);
console.log('shader vertex title', shaders.vertexShaders.title);

var titleMat = new THREE.ShaderMaterial({
uniforms: uniforms,
transparent: true,
vertexShader: shaders.vertexShaders.title,
fragmentShader: shaders.fragmentShaders.title

});

If you run this code, you’ll note from the console, shaders.vertextShaders.title is undefined when using console.log, but accessing the object directly does show it is present - assume this is due to the delay.

For full code, please checkout:

Downloading something from the network takes time, you can’t (or shouldn’t!) freeze the rest of your program while waiting for something to download. Browsers have an old feature to do this (synchronous XMLHTTPRequest) but it’s deprecated and the three.js loaders correctly avoid using it.

You have three options here:

  • A. Have your later code inside a callback, invoked when the resources are ready.
  • B. Move the shaders into your codebase, e.g. as multi-line strings.
  • C. Use something like Webpack’s asset modules to automatically embed the shaders in your project’s codebase at compile time.
1 Like