Skip to content

Instantly share code, notes, and snippets.

@IceCreamYou
Created April 27, 2014 05:29
Show Gist options
  • Save IceCreamYou/11338221 to your computer and use it in GitHub Desktop.
Save IceCreamYou/11338221 to your computer and use it in GitHub Desktop.
A utility function to extract convenient multi-line strings with embedded variables from comments in function bodies. Particularly useful for inline GLSL shader code.
/**
* Extract a multiline string from a multiline comment inside a function.
*
* @param {Function} fn The function containing the string.
* @param {vars} A map of tokens to values to replace in the string.
*/
function textFromComment(fn, vars) {
var s = (fn + '').match(/^[\s\S]*?\/\*!?\s*([\s\S]+?)\s*\*\/$/m)[1];
if (typeof vars !== 'undefined') {
var keys = Object.keys(vars).sort(function(a, b) { return b.length - a.length; });
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i], val = vars[key];
s = s.split('$' + key).join(val);
}
}
return s;
}
/* Usage example */
textFromComment(fragmentShader, {
assignTextures: assign,
declareTextures: declare,
});
function fragmentShader() {
/*!
varying vec2 vUv;
varying vec3 vPosition;
$declareTextures
void main() {
vec4 color = texture2D( texture_0, vUv ); // base
$assignTextures
gl_FragColor = color;
}
*/
var z; // prevent UglifyJS from removing the above comment
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment