Skip to content

Instantly share code, notes, and snippets.

@zz85
Last active July 26, 2022 20:02
Show Gist options
  • Save zz85/8917654 to your computer and use it in GitHub Desktop.
Save zz85/8917654 to your computer and use it in GitHub Desktop.
AutoGen Three.js Shader Uniforms
// https://github.com/mrdoob/three.js/issues/4145
// based on https://github.com/unconed/ShaderGraph.js/blob/master/src/Snippet.js
var typeMaps = {
'float': 'f',
'vec2': 'v2',
'vec3': 'v3',
'vec4': 'v4',
'mat3': 'm3',
'mat4': 'm4',
'sampler2D': 't',
'samplerCube': 't',
}
var typeNatives = {
'v2': THREE.Vector2,
'v3': THREE.Vector3,
'm3': THREE.Matrix3,
'm4': THREE.Matrix4
}
function parseUniforms(code, uniforms) {
if (!uniforms) uniforms = {};
// Remove all comments and normalize newlines
code = code.replace(/\r\n?/g, '\n').replace(/\/\/[^\n]*\n/g, ' ').replace(/\/\*(.|\n)*?\*\//g, ' ');
var match_uniforms = /(?:^|;)\s*uniform\s+(([A-Za-z0-9]+)\s+([A-Za-z0-9_]+)\s*(?:\[([^\]]+)\])?)(?:$|(?=;))/g;
var match, type, name, array, shortType;
while (match = match_uniforms.exec(code)) {
type = match[2];
name = match[3];
array = match[4];
shortType = typeMaps[type];
if (!uniforms[name]) uniforms[name] = {};
uniforms[name].type = shortType + ( array ? 'v' : '' );
if (uniforms[name].value == undefined) // don't overwrite exisiting uniform values
uniforms[name].value = shortType in typeNatives ? new typeNatives[ shortType ] : 0;
};
return uniforms;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment