id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
8,800
greggman/twgl.js
src/programs.js
loadShader
function loadShader(gl, shaderSource, shaderType, opt_errorCallback) { const errFn = opt_errorCallback || error; // Create the shader object const shader = gl.createShader(shaderType); // Remove the first end of line because WebGL 2.0 requires // #version 300 es // as the first line. No whitespace allowed before that line // so // // <script> // #version 300 es // </script> // // Has one line before it which is invalid according to GLSL ES 3.00 // let lineOffset = 0; if (spaceRE.test(shaderSource)) { lineOffset = 1; shaderSource = shaderSource.replace(spaceRE, ''); } // Load the shader source gl.shaderSource(shader, shaderSource); // Compile the shader gl.compileShader(shader); // Check the compile status const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { // Something went wrong during compilation; get the error const lastError = gl.getShaderInfoLog(shader); errFn(addLineNumbers(shaderSource, lineOffset) + "\n*** Error compiling shader: " + lastError); gl.deleteShader(shader); return null; } return shader; }
javascript
function loadShader(gl, shaderSource, shaderType, opt_errorCallback) { const errFn = opt_errorCallback || error; // Create the shader object const shader = gl.createShader(shaderType); // Remove the first end of line because WebGL 2.0 requires // #version 300 es // as the first line. No whitespace allowed before that line // so // // <script> // #version 300 es // </script> // // Has one line before it which is invalid according to GLSL ES 3.00 // let lineOffset = 0; if (spaceRE.test(shaderSource)) { lineOffset = 1; shaderSource = shaderSource.replace(spaceRE, ''); } // Load the shader source gl.shaderSource(shader, shaderSource); // Compile the shader gl.compileShader(shader); // Check the compile status const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { // Something went wrong during compilation; get the error const lastError = gl.getShaderInfoLog(shader); errFn(addLineNumbers(shaderSource, lineOffset) + "\n*** Error compiling shader: " + lastError); gl.deleteShader(shader); return null; } return shader; }
[ "function", "loadShader", "(", "gl", ",", "shaderSource", ",", "shaderType", ",", "opt_errorCallback", ")", "{", "const", "errFn", "=", "opt_errorCallback", "||", "error", ";", "// Create the shader object", "const", "shader", "=", "gl", ".", "createShader", "(", "shaderType", ")", ";", "// Remove the first end of line because WebGL 2.0 requires", "// #version 300 es", "// as the first line. No whitespace allowed before that line", "// so", "//", "// <script>", "// #version 300 es", "// </script>", "//", "// Has one line before it which is invalid according to GLSL ES 3.00", "//", "let", "lineOffset", "=", "0", ";", "if", "(", "spaceRE", ".", "test", "(", "shaderSource", ")", ")", "{", "lineOffset", "=", "1", ";", "shaderSource", "=", "shaderSource", ".", "replace", "(", "spaceRE", ",", "''", ")", ";", "}", "// Load the shader source", "gl", ".", "shaderSource", "(", "shader", ",", "shaderSource", ")", ";", "// Compile the shader", "gl", ".", "compileShader", "(", "shader", ")", ";", "// Check the compile status", "const", "compiled", "=", "gl", ".", "getShaderParameter", "(", "shader", ",", "gl", ".", "COMPILE_STATUS", ")", ";", "if", "(", "!", "compiled", ")", "{", "// Something went wrong during compilation; get the error", "const", "lastError", "=", "gl", ".", "getShaderInfoLog", "(", "shader", ")", ";", "errFn", "(", "addLineNumbers", "(", "shaderSource", ",", "lineOffset", ")", "+", "\"\\n*** Error compiling shader: \"", "+", "lastError", ")", ";", "gl", ".", "deleteShader", "(", "shader", ")", ";", "return", "null", ";", "}", "return", "shader", ";", "}" ]
Loads a shader. @param {WebGLRenderingContext} gl The WebGLRenderingContext to use. @param {string} shaderSource The shader source. @param {number} shaderType The type of shader. @param {module:twgl.ErrorCallback} opt_errorCallback callback for errors. @return {WebGLShader} The created shader. @private
[ "Loads", "a", "shader", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L477-L516
8,801
greggman/twgl.js
src/programs.js
createUniformSetters
function createUniformSetters(gl, program) { let textureUnit = 0; /** * Creates a setter for a uniform of the given program with it's * location embedded in the setter. * @param {WebGLProgram} program * @param {WebGLUniformInfo} uniformInfo * @returns {function} the created setter. */ function createUniformSetter(program, uniformInfo) { const location = gl.getUniformLocation(program, uniformInfo.name); const isArray = (uniformInfo.size > 1 && uniformInfo.name.substr(-3) === "[0]"); const type = uniformInfo.type; const typeInfo = typeMap[type]; if (!typeInfo) { throw ("unknown type: 0x" + type.toString(16)); // we should never get here. } let setter; if (typeInfo.bindPoint) { // it's a sampler const unit = textureUnit; textureUnit += uniformInfo.size; if (isArray) { setter = typeInfo.arraySetter(gl, type, unit, location, uniformInfo.size); } else { setter = typeInfo.setter(gl, type, unit, location, uniformInfo.size); } } else { if (typeInfo.arraySetter && isArray) { setter = typeInfo.arraySetter(gl, location); } else { setter = typeInfo.setter(gl, location); } } setter.location = location; return setter; } const uniformSetters = { }; const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); for (let ii = 0; ii < numUniforms; ++ii) { const uniformInfo = gl.getActiveUniform(program, ii); if (isBuiltIn(uniformInfo)) { continue; } let name = uniformInfo.name; // remove the array suffix. if (name.substr(-3) === "[0]") { name = name.substr(0, name.length - 3); } const setter = createUniformSetter(program, uniformInfo); uniformSetters[name] = setter; } return uniformSetters; }
javascript
function createUniformSetters(gl, program) { let textureUnit = 0; /** * Creates a setter for a uniform of the given program with it's * location embedded in the setter. * @param {WebGLProgram} program * @param {WebGLUniformInfo} uniformInfo * @returns {function} the created setter. */ function createUniformSetter(program, uniformInfo) { const location = gl.getUniformLocation(program, uniformInfo.name); const isArray = (uniformInfo.size > 1 && uniformInfo.name.substr(-3) === "[0]"); const type = uniformInfo.type; const typeInfo = typeMap[type]; if (!typeInfo) { throw ("unknown type: 0x" + type.toString(16)); // we should never get here. } let setter; if (typeInfo.bindPoint) { // it's a sampler const unit = textureUnit; textureUnit += uniformInfo.size; if (isArray) { setter = typeInfo.arraySetter(gl, type, unit, location, uniformInfo.size); } else { setter = typeInfo.setter(gl, type, unit, location, uniformInfo.size); } } else { if (typeInfo.arraySetter && isArray) { setter = typeInfo.arraySetter(gl, location); } else { setter = typeInfo.setter(gl, location); } } setter.location = location; return setter; } const uniformSetters = { }; const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); for (let ii = 0; ii < numUniforms; ++ii) { const uniformInfo = gl.getActiveUniform(program, ii); if (isBuiltIn(uniformInfo)) { continue; } let name = uniformInfo.name; // remove the array suffix. if (name.substr(-3) === "[0]") { name = name.substr(0, name.length - 3); } const setter = createUniformSetter(program, uniformInfo); uniformSetters[name] = setter; } return uniformSetters; }
[ "function", "createUniformSetters", "(", "gl", ",", "program", ")", "{", "let", "textureUnit", "=", "0", ";", "/**\n * Creates a setter for a uniform of the given program with it's\n * location embedded in the setter.\n * @param {WebGLProgram} program\n * @param {WebGLUniformInfo} uniformInfo\n * @returns {function} the created setter.\n */", "function", "createUniformSetter", "(", "program", ",", "uniformInfo", ")", "{", "const", "location", "=", "gl", ".", "getUniformLocation", "(", "program", ",", "uniformInfo", ".", "name", ")", ";", "const", "isArray", "=", "(", "uniformInfo", ".", "size", ">", "1", "&&", "uniformInfo", ".", "name", ".", "substr", "(", "-", "3", ")", "===", "\"[0]\"", ")", ";", "const", "type", "=", "uniformInfo", ".", "type", ";", "const", "typeInfo", "=", "typeMap", "[", "type", "]", ";", "if", "(", "!", "typeInfo", ")", "{", "throw", "(", "\"unknown type: 0x\"", "+", "type", ".", "toString", "(", "16", ")", ")", ";", "// we should never get here.", "}", "let", "setter", ";", "if", "(", "typeInfo", ".", "bindPoint", ")", "{", "// it's a sampler", "const", "unit", "=", "textureUnit", ";", "textureUnit", "+=", "uniformInfo", ".", "size", ";", "if", "(", "isArray", ")", "{", "setter", "=", "typeInfo", ".", "arraySetter", "(", "gl", ",", "type", ",", "unit", ",", "location", ",", "uniformInfo", ".", "size", ")", ";", "}", "else", "{", "setter", "=", "typeInfo", ".", "setter", "(", "gl", ",", "type", ",", "unit", ",", "location", ",", "uniformInfo", ".", "size", ")", ";", "}", "}", "else", "{", "if", "(", "typeInfo", ".", "arraySetter", "&&", "isArray", ")", "{", "setter", "=", "typeInfo", ".", "arraySetter", "(", "gl", ",", "location", ")", ";", "}", "else", "{", "setter", "=", "typeInfo", ".", "setter", "(", "gl", ",", "location", ")", ";", "}", "}", "setter", ".", "location", "=", "location", ";", "return", "setter", ";", "}", "const", "uniformSetters", "=", "{", "}", ";", "const", "numUniforms", "=", "gl", ".", "getProgramParameter", "(", "program", ",", "gl", ".", "ACTIVE_UNIFORMS", ")", ";", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "numUniforms", ";", "++", "ii", ")", "{", "const", "uniformInfo", "=", "gl", ".", "getActiveUniform", "(", "program", ",", "ii", ")", ";", "if", "(", "isBuiltIn", "(", "uniformInfo", ")", ")", "{", "continue", ";", "}", "let", "name", "=", "uniformInfo", ".", "name", ";", "// remove the array suffix.", "if", "(", "name", ".", "substr", "(", "-", "3", ")", "===", "\"[0]\"", ")", "{", "name", "=", "name", ".", "substr", "(", "0", ",", "name", ".", "length", "-", "3", ")", ";", "}", "const", "setter", "=", "createUniformSetter", "(", "program", ",", "uniformInfo", ")", ";", "uniformSetters", "[", "name", "]", "=", "setter", ";", "}", "return", "uniformSetters", ";", "}" ]
Creates setter functions for all uniforms of a shader program. @see {@link module:twgl.setUniforms} @param {WebGLProgram} program the program to create setters for. @returns {Object.<string, function>} an object with a setter by name for each uniform @memberOf module:twgl/programs
[ "Creates", "setter", "functions", "for", "all", "uniforms", "of", "a", "shader", "program", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L815-L871
8,802
greggman/twgl.js
src/programs.js
createUniformSetter
function createUniformSetter(program, uniformInfo) { const location = gl.getUniformLocation(program, uniformInfo.name); const isArray = (uniformInfo.size > 1 && uniformInfo.name.substr(-3) === "[0]"); const type = uniformInfo.type; const typeInfo = typeMap[type]; if (!typeInfo) { throw ("unknown type: 0x" + type.toString(16)); // we should never get here. } let setter; if (typeInfo.bindPoint) { // it's a sampler const unit = textureUnit; textureUnit += uniformInfo.size; if (isArray) { setter = typeInfo.arraySetter(gl, type, unit, location, uniformInfo.size); } else { setter = typeInfo.setter(gl, type, unit, location, uniformInfo.size); } } else { if (typeInfo.arraySetter && isArray) { setter = typeInfo.arraySetter(gl, location); } else { setter = typeInfo.setter(gl, location); } } setter.location = location; return setter; }
javascript
function createUniformSetter(program, uniformInfo) { const location = gl.getUniformLocation(program, uniformInfo.name); const isArray = (uniformInfo.size > 1 && uniformInfo.name.substr(-3) === "[0]"); const type = uniformInfo.type; const typeInfo = typeMap[type]; if (!typeInfo) { throw ("unknown type: 0x" + type.toString(16)); // we should never get here. } let setter; if (typeInfo.bindPoint) { // it's a sampler const unit = textureUnit; textureUnit += uniformInfo.size; if (isArray) { setter = typeInfo.arraySetter(gl, type, unit, location, uniformInfo.size); } else { setter = typeInfo.setter(gl, type, unit, location, uniformInfo.size); } } else { if (typeInfo.arraySetter && isArray) { setter = typeInfo.arraySetter(gl, location); } else { setter = typeInfo.setter(gl, location); } } setter.location = location; return setter; }
[ "function", "createUniformSetter", "(", "program", ",", "uniformInfo", ")", "{", "const", "location", "=", "gl", ".", "getUniformLocation", "(", "program", ",", "uniformInfo", ".", "name", ")", ";", "const", "isArray", "=", "(", "uniformInfo", ".", "size", ">", "1", "&&", "uniformInfo", ".", "name", ".", "substr", "(", "-", "3", ")", "===", "\"[0]\"", ")", ";", "const", "type", "=", "uniformInfo", ".", "type", ";", "const", "typeInfo", "=", "typeMap", "[", "type", "]", ";", "if", "(", "!", "typeInfo", ")", "{", "throw", "(", "\"unknown type: 0x\"", "+", "type", ".", "toString", "(", "16", ")", ")", ";", "// we should never get here.", "}", "let", "setter", ";", "if", "(", "typeInfo", ".", "bindPoint", ")", "{", "// it's a sampler", "const", "unit", "=", "textureUnit", ";", "textureUnit", "+=", "uniformInfo", ".", "size", ";", "if", "(", "isArray", ")", "{", "setter", "=", "typeInfo", ".", "arraySetter", "(", "gl", ",", "type", ",", "unit", ",", "location", ",", "uniformInfo", ".", "size", ")", ";", "}", "else", "{", "setter", "=", "typeInfo", ".", "setter", "(", "gl", ",", "type", ",", "unit", ",", "location", ",", "uniformInfo", ".", "size", ")", ";", "}", "}", "else", "{", "if", "(", "typeInfo", ".", "arraySetter", "&&", "isArray", ")", "{", "setter", "=", "typeInfo", ".", "arraySetter", "(", "gl", ",", "location", ")", ";", "}", "else", "{", "setter", "=", "typeInfo", ".", "setter", "(", "gl", ",", "location", ")", ";", "}", "}", "setter", ".", "location", "=", "location", ";", "return", "setter", ";", "}" ]
Creates a setter for a uniform of the given program with it's location embedded in the setter. @param {WebGLProgram} program @param {WebGLUniformInfo} uniformInfo @returns {function} the created setter.
[ "Creates", "a", "setter", "for", "a", "uniform", "of", "the", "given", "program", "with", "it", "s", "location", "embedded", "in", "the", "setter", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L825-L852
8,803
greggman/twgl.js
src/programs.js
bindTransformFeedbackInfo
function bindTransformFeedbackInfo(gl, transformFeedbackInfo, bufferInfo) { if (transformFeedbackInfo.transformFeedbackInfo) { transformFeedbackInfo = transformFeedbackInfo.transformFeedbackInfo; } if (bufferInfo.attribs) { bufferInfo = bufferInfo.attribs; } for (const name in bufferInfo) { const varying = transformFeedbackInfo[name]; if (varying) { const buf = bufferInfo[name]; if (buf.offset) { gl.bindBufferRange(gl.TRANSFORM_FEEDBACK_BUFFER, varying.index, buf.buffer, buf.offset, buf.size); } else { gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, varying.index, buf.buffer); } } } }
javascript
function bindTransformFeedbackInfo(gl, transformFeedbackInfo, bufferInfo) { if (transformFeedbackInfo.transformFeedbackInfo) { transformFeedbackInfo = transformFeedbackInfo.transformFeedbackInfo; } if (bufferInfo.attribs) { bufferInfo = bufferInfo.attribs; } for (const name in bufferInfo) { const varying = transformFeedbackInfo[name]; if (varying) { const buf = bufferInfo[name]; if (buf.offset) { gl.bindBufferRange(gl.TRANSFORM_FEEDBACK_BUFFER, varying.index, buf.buffer, buf.offset, buf.size); } else { gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, varying.index, buf.buffer); } } } }
[ "function", "bindTransformFeedbackInfo", "(", "gl", ",", "transformFeedbackInfo", ",", "bufferInfo", ")", "{", "if", "(", "transformFeedbackInfo", ".", "transformFeedbackInfo", ")", "{", "transformFeedbackInfo", "=", "transformFeedbackInfo", ".", "transformFeedbackInfo", ";", "}", "if", "(", "bufferInfo", ".", "attribs", ")", "{", "bufferInfo", "=", "bufferInfo", ".", "attribs", ";", "}", "for", "(", "const", "name", "in", "bufferInfo", ")", "{", "const", "varying", "=", "transformFeedbackInfo", "[", "name", "]", ";", "if", "(", "varying", ")", "{", "const", "buf", "=", "bufferInfo", "[", "name", "]", ";", "if", "(", "buf", ".", "offset", ")", "{", "gl", ".", "bindBufferRange", "(", "gl", ".", "TRANSFORM_FEEDBACK_BUFFER", ",", "varying", ".", "index", ",", "buf", ".", "buffer", ",", "buf", ".", "offset", ",", "buf", ".", "size", ")", ";", "}", "else", "{", "gl", ".", "bindBufferBase", "(", "gl", ".", "TRANSFORM_FEEDBACK_BUFFER", ",", "varying", ".", "index", ",", "buf", ".", "buffer", ")", ";", "}", "}", "}", "}" ]
Binds buffers for transform feedback. @param {WebGLRenderingContext} gl The WebGLRenderingContext to use. @param {(module:twgl.ProgramInfo|Object<string, module:twgl.TransformFeedbackInfo>)} transformFeedbackInfo A ProgramInfo or TransformFeedbackInfo. @param {(module:twgl.BufferInfo|Object<string, module:twgl.AttribInfo>)} [bufferInfo] A BufferInfo or set of AttribInfos. @memberOf module:twgl
[ "Binds", "buffers", "for", "transform", "feedback", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L910-L928
8,804
greggman/twgl.js
src/programs.js
createTransformFeedback
function createTransformFeedback(gl, programInfo, bufferInfo) { const tf = gl.createTransformFeedback(); gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, tf); gl.useProgram(programInfo.program); bindTransformFeedbackInfo(gl, programInfo, bufferInfo); gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null); return tf; }
javascript
function createTransformFeedback(gl, programInfo, bufferInfo) { const tf = gl.createTransformFeedback(); gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, tf); gl.useProgram(programInfo.program); bindTransformFeedbackInfo(gl, programInfo, bufferInfo); gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null); return tf; }
[ "function", "createTransformFeedback", "(", "gl", ",", "programInfo", ",", "bufferInfo", ")", "{", "const", "tf", "=", "gl", ".", "createTransformFeedback", "(", ")", ";", "gl", ".", "bindTransformFeedback", "(", "gl", ".", "TRANSFORM_FEEDBACK", ",", "tf", ")", ";", "gl", ".", "useProgram", "(", "programInfo", ".", "program", ")", ";", "bindTransformFeedbackInfo", "(", "gl", ",", "programInfo", ",", "bufferInfo", ")", ";", "gl", ".", "bindTransformFeedback", "(", "gl", ".", "TRANSFORM_FEEDBACK", ",", "null", ")", ";", "return", "tf", ";", "}" ]
Creates a transform feedback and sets the buffers @param {WebGLRenderingContext} gl The WebGLRenderingContext to use. @param {module:twgl.ProgramInfo} programInfo A ProgramInfo as returned from {@link module:twgl.createProgramInfo} @param {(module:twgl.BufferInfo|Object<string, module:twgl.AttribInfo>)} [bufferInfo] A BufferInfo or set of AttribInfos. @return {WebGLTransformFeedback} the created transform feedback @memberOf module:twgl
[ "Creates", "a", "transform", "feedback", "and", "sets", "the", "buffers" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L938-L945
8,805
greggman/twgl.js
src/programs.js
createUniformBlockSpecFromProgram
function createUniformBlockSpecFromProgram(gl, program) { const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); const uniformData = []; const uniformIndices = []; for (let ii = 0; ii < numUniforms; ++ii) { uniformIndices.push(ii); uniformData.push({}); const uniformInfo = gl.getActiveUniform(program, ii); if (isBuiltIn(uniformInfo)) { break; } // REMOVE [0]? uniformData[ii].name = uniformInfo.name; } [ [ "UNIFORM_TYPE", "type" ], [ "UNIFORM_SIZE", "size" ], // num elements [ "UNIFORM_BLOCK_INDEX", "blockNdx" ], [ "UNIFORM_OFFSET", "offset", ], ].forEach(function(pair) { const pname = pair[0]; const key = pair[1]; gl.getActiveUniforms(program, uniformIndices, gl[pname]).forEach(function(value, ndx) { uniformData[ndx][key] = value; }); }); const blockSpecs = {}; const numUniformBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS); for (let ii = 0; ii < numUniformBlocks; ++ii) { const name = gl.getActiveUniformBlockName(program, ii); const blockSpec = { index: ii, usedByVertexShader: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER), usedByFragmentShader: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER), size: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_DATA_SIZE), uniformIndices: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES), }; blockSpec.used = blockSpec.usedByVertexSahder || blockSpec.usedByFragmentShader; blockSpecs[name] = blockSpec; } return { blockSpecs: blockSpecs, uniformData: uniformData, }; }
javascript
function createUniformBlockSpecFromProgram(gl, program) { const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); const uniformData = []; const uniformIndices = []; for (let ii = 0; ii < numUniforms; ++ii) { uniformIndices.push(ii); uniformData.push({}); const uniformInfo = gl.getActiveUniform(program, ii); if (isBuiltIn(uniformInfo)) { break; } // REMOVE [0]? uniformData[ii].name = uniformInfo.name; } [ [ "UNIFORM_TYPE", "type" ], [ "UNIFORM_SIZE", "size" ], // num elements [ "UNIFORM_BLOCK_INDEX", "blockNdx" ], [ "UNIFORM_OFFSET", "offset", ], ].forEach(function(pair) { const pname = pair[0]; const key = pair[1]; gl.getActiveUniforms(program, uniformIndices, gl[pname]).forEach(function(value, ndx) { uniformData[ndx][key] = value; }); }); const blockSpecs = {}; const numUniformBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS); for (let ii = 0; ii < numUniformBlocks; ++ii) { const name = gl.getActiveUniformBlockName(program, ii); const blockSpec = { index: ii, usedByVertexShader: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER), usedByFragmentShader: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER), size: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_DATA_SIZE), uniformIndices: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES), }; blockSpec.used = blockSpec.usedByVertexSahder || blockSpec.usedByFragmentShader; blockSpecs[name] = blockSpec; } return { blockSpecs: blockSpecs, uniformData: uniformData, }; }
[ "function", "createUniformBlockSpecFromProgram", "(", "gl", ",", "program", ")", "{", "const", "numUniforms", "=", "gl", ".", "getProgramParameter", "(", "program", ",", "gl", ".", "ACTIVE_UNIFORMS", ")", ";", "const", "uniformData", "=", "[", "]", ";", "const", "uniformIndices", "=", "[", "]", ";", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "numUniforms", ";", "++", "ii", ")", "{", "uniformIndices", ".", "push", "(", "ii", ")", ";", "uniformData", ".", "push", "(", "{", "}", ")", ";", "const", "uniformInfo", "=", "gl", ".", "getActiveUniform", "(", "program", ",", "ii", ")", ";", "if", "(", "isBuiltIn", "(", "uniformInfo", ")", ")", "{", "break", ";", "}", "// REMOVE [0]?", "uniformData", "[", "ii", "]", ".", "name", "=", "uniformInfo", ".", "name", ";", "}", "[", "[", "\"UNIFORM_TYPE\"", ",", "\"type\"", "]", ",", "[", "\"UNIFORM_SIZE\"", ",", "\"size\"", "]", ",", "// num elements", "[", "\"UNIFORM_BLOCK_INDEX\"", ",", "\"blockNdx\"", "]", ",", "[", "\"UNIFORM_OFFSET\"", ",", "\"offset\"", ",", "]", ",", "]", ".", "forEach", "(", "function", "(", "pair", ")", "{", "const", "pname", "=", "pair", "[", "0", "]", ";", "const", "key", "=", "pair", "[", "1", "]", ";", "gl", ".", "getActiveUniforms", "(", "program", ",", "uniformIndices", ",", "gl", "[", "pname", "]", ")", ".", "forEach", "(", "function", "(", "value", ",", "ndx", ")", "{", "uniformData", "[", "ndx", "]", "[", "key", "]", "=", "value", ";", "}", ")", ";", "}", ")", ";", "const", "blockSpecs", "=", "{", "}", ";", "const", "numUniformBlocks", "=", "gl", ".", "getProgramParameter", "(", "program", ",", "gl", ".", "ACTIVE_UNIFORM_BLOCKS", ")", ";", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "numUniformBlocks", ";", "++", "ii", ")", "{", "const", "name", "=", "gl", ".", "getActiveUniformBlockName", "(", "program", ",", "ii", ")", ";", "const", "blockSpec", "=", "{", "index", ":", "ii", ",", "usedByVertexShader", ":", "gl", ".", "getActiveUniformBlockParameter", "(", "program", ",", "ii", ",", "gl", ".", "UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER", ")", ",", "usedByFragmentShader", ":", "gl", ".", "getActiveUniformBlockParameter", "(", "program", ",", "ii", ",", "gl", ".", "UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER", ")", ",", "size", ":", "gl", ".", "getActiveUniformBlockParameter", "(", "program", ",", "ii", ",", "gl", ".", "UNIFORM_BLOCK_DATA_SIZE", ")", ",", "uniformIndices", ":", "gl", ".", "getActiveUniformBlockParameter", "(", "program", ",", "ii", ",", "gl", ".", "UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES", ")", ",", "}", ";", "blockSpec", ".", "used", "=", "blockSpec", ".", "usedByVertexSahder", "||", "blockSpec", ".", "usedByFragmentShader", ";", "blockSpecs", "[", "name", "]", "=", "blockSpec", ";", "}", "return", "{", "blockSpecs", ":", "blockSpecs", ",", "uniformData", ":", "uniformData", ",", "}", ";", "}" ]
A `UniformBlockSpec` represents the data needed to create and bind UniformBlockObjects for a given program @typedef {Object} UniformBlockSpec @property {Object.<string, module:twgl.BlockSpec> blockSpecs The BlockSpec for each block by block name @property {UniformData[]} uniformData An array of data for each uniform by uniform index. @memberOf module:twgl Creates a UniformBlockSpec for the given program. A UniformBlockSpec represents the data needed to create and bind UniformBlockObjects @param {WebGL2RenderingContext} gl A WebGL2 Rendering Context @param {WebGLProgram} program A WebGLProgram for a successfully linked program @return {module:twgl.UniformBlockSpec} The created UniformBlockSpec @memberOf module:twgl/programs
[ "A", "UniformBlockSpec", "represents", "the", "data", "needed", "to", "create", "and", "bind", "UniformBlockObjects", "for", "a", "given", "program" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L991-L1040
8,806
greggman/twgl.js
src/programs.js
createUniformBlockInfoFromProgram
function createUniformBlockInfoFromProgram(gl, program, uniformBlockSpec, blockName) { const blockSpecs = uniformBlockSpec.blockSpecs; const uniformData = uniformBlockSpec.uniformData; const blockSpec = blockSpecs[blockName]; if (!blockSpec) { warn("no uniform block object named:", blockName); return { name: blockName, uniforms: {}, }; } const array = new ArrayBuffer(blockSpec.size); const buffer = gl.createBuffer(); const uniformBufferIndex = blockSpec.index; gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); gl.uniformBlockBinding(program, blockSpec.index, uniformBufferIndex); let prefix = blockName + "."; if (arraySuffixRE.test(prefix)) { prefix = prefix.replace(arraySuffixRE, "."); } const uniforms = {}; blockSpec.uniformIndices.forEach(function(uniformNdx) { const data = uniformData[uniformNdx]; const typeInfo = typeMap[data.type]; const Type = typeInfo.Type; const length = data.size * typeInfo.size; let name = data.name; if (name.substr(0, prefix.length) === prefix) { name = name.substr(prefix.length); } uniforms[name] = new Type(array, data.offset, length / Type.BYTES_PER_ELEMENT); }); return { name: blockName, array: array, asFloat: new Float32Array(array), // for debugging buffer: buffer, uniforms: uniforms, }; }
javascript
function createUniformBlockInfoFromProgram(gl, program, uniformBlockSpec, blockName) { const blockSpecs = uniformBlockSpec.blockSpecs; const uniformData = uniformBlockSpec.uniformData; const blockSpec = blockSpecs[blockName]; if (!blockSpec) { warn("no uniform block object named:", blockName); return { name: blockName, uniforms: {}, }; } const array = new ArrayBuffer(blockSpec.size); const buffer = gl.createBuffer(); const uniformBufferIndex = blockSpec.index; gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); gl.uniformBlockBinding(program, blockSpec.index, uniformBufferIndex); let prefix = blockName + "."; if (arraySuffixRE.test(prefix)) { prefix = prefix.replace(arraySuffixRE, "."); } const uniforms = {}; blockSpec.uniformIndices.forEach(function(uniformNdx) { const data = uniformData[uniformNdx]; const typeInfo = typeMap[data.type]; const Type = typeInfo.Type; const length = data.size * typeInfo.size; let name = data.name; if (name.substr(0, prefix.length) === prefix) { name = name.substr(prefix.length); } uniforms[name] = new Type(array, data.offset, length / Type.BYTES_PER_ELEMENT); }); return { name: blockName, array: array, asFloat: new Float32Array(array), // for debugging buffer: buffer, uniforms: uniforms, }; }
[ "function", "createUniformBlockInfoFromProgram", "(", "gl", ",", "program", ",", "uniformBlockSpec", ",", "blockName", ")", "{", "const", "blockSpecs", "=", "uniformBlockSpec", ".", "blockSpecs", ";", "const", "uniformData", "=", "uniformBlockSpec", ".", "uniformData", ";", "const", "blockSpec", "=", "blockSpecs", "[", "blockName", "]", ";", "if", "(", "!", "blockSpec", ")", "{", "warn", "(", "\"no uniform block object named:\"", ",", "blockName", ")", ";", "return", "{", "name", ":", "blockName", ",", "uniforms", ":", "{", "}", ",", "}", ";", "}", "const", "array", "=", "new", "ArrayBuffer", "(", "blockSpec", ".", "size", ")", ";", "const", "buffer", "=", "gl", ".", "createBuffer", "(", ")", ";", "const", "uniformBufferIndex", "=", "blockSpec", ".", "index", ";", "gl", ".", "bindBuffer", "(", "gl", ".", "UNIFORM_BUFFER", ",", "buffer", ")", ";", "gl", ".", "uniformBlockBinding", "(", "program", ",", "blockSpec", ".", "index", ",", "uniformBufferIndex", ")", ";", "let", "prefix", "=", "blockName", "+", "\".\"", ";", "if", "(", "arraySuffixRE", ".", "test", "(", "prefix", ")", ")", "{", "prefix", "=", "prefix", ".", "replace", "(", "arraySuffixRE", ",", "\".\"", ")", ";", "}", "const", "uniforms", "=", "{", "}", ";", "blockSpec", ".", "uniformIndices", ".", "forEach", "(", "function", "(", "uniformNdx", ")", "{", "const", "data", "=", "uniformData", "[", "uniformNdx", "]", ";", "const", "typeInfo", "=", "typeMap", "[", "data", ".", "type", "]", ";", "const", "Type", "=", "typeInfo", ".", "Type", ";", "const", "length", "=", "data", ".", "size", "*", "typeInfo", ".", "size", ";", "let", "name", "=", "data", ".", "name", ";", "if", "(", "name", ".", "substr", "(", "0", ",", "prefix", ".", "length", ")", "===", "prefix", ")", "{", "name", "=", "name", ".", "substr", "(", "prefix", ".", "length", ")", ";", "}", "uniforms", "[", "name", "]", "=", "new", "Type", "(", "array", ",", "data", ".", "offset", ",", "length", "/", "Type", ".", "BYTES_PER_ELEMENT", ")", ";", "}", ")", ";", "return", "{", "name", ":", "blockName", ",", "array", ":", "array", ",", "asFloat", ":", "new", "Float32Array", "(", "array", ")", ",", "// for debugging", "buffer", ":", "buffer", ",", "uniforms", ":", "uniforms", ",", "}", ";", "}" ]
Represents a UniformBlockObject including an ArrayBuffer with all the uniform values and a corresponding WebGLBuffer to hold those values on the GPU @typedef {Object} UniformBlockInfo @property {string} name The name of the block @property {ArrayBuffer} array The array buffer that contains the uniform values @property {Float32Array} asFloat A float view on the array buffer. This is useful inspecting the contents of the buffer in the debugger. @property {WebGLBuffer} buffer A WebGL buffer that will hold a copy of the uniform values for rendering. @property {number} [offset] offset into buffer @property {Object.<string, ArrayBufferView>} uniforms A uniform name to ArrayBufferView map. each Uniform has a correctly typed `ArrayBufferView` into array at the correct offset and length of that uniform. So for example a float uniform would have a 1 float `Float32Array` view. A single mat4 would have a 16 element `Float32Array` view. An ivec2 would have an `Int32Array` view, etc. @memberOf module:twgl Creates a `UniformBlockInfo` for the specified block Note: **If the blockName matches no existing blocks a warning is printed to the console and a dummy `UniformBlockInfo` is returned**. This is because when debugging GLSL it is common to comment out large portions of a shader or for example set the final output to a constant. When that happens blocks get optimized out. If this function did not create dummy blocks your code would crash when debugging. @param {WebGL2RenderingContext} gl A WebGL2RenderingContext @param {WebGLProgram} program A WebGLProgram @param {module:twgl.UniformBlockSpec} uinformBlockSpec. A UniformBlockSpec as returned from {@link module:twgl.createUniformBlockSpecFromProgram}. @param {string} blockName The name of the block. @return {module:twgl.UniformBlockInfo} The created UniformBlockInfo @memberOf module:twgl/programs
[ "Represents", "a", "UniformBlockObject", "including", "an", "ArrayBuffer", "with", "all", "the", "uniform", "values", "and", "a", "corresponding", "WebGLBuffer", "to", "hold", "those", "values", "on", "the", "GPU" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L1080-L1120
8,807
greggman/twgl.js
src/programs.js
createUniformBlockInfo
function createUniformBlockInfo(gl, programInfo, blockName) { return createUniformBlockInfoFromProgram(gl, programInfo.program, programInfo.uniformBlockSpec, blockName); }
javascript
function createUniformBlockInfo(gl, programInfo, blockName) { return createUniformBlockInfoFromProgram(gl, programInfo.program, programInfo.uniformBlockSpec, blockName); }
[ "function", "createUniformBlockInfo", "(", "gl", ",", "programInfo", ",", "blockName", ")", "{", "return", "createUniformBlockInfoFromProgram", "(", "gl", ",", "programInfo", ".", "program", ",", "programInfo", ".", "uniformBlockSpec", ",", "blockName", ")", ";", "}" ]
Creates a `UniformBlockInfo` for the specified block Note: **If the blockName matches no existing blocks a warning is printed to the console and a dummy `UniformBlockInfo` is returned**. This is because when debugging GLSL it is common to comment out large portions of a shader or for example set the final output to a constant. When that happens blocks get optimized out. If this function did not create dummy blocks your code would crash when debugging. @param {WebGL2RenderingContext} gl A WebGL2RenderingContext @param {module:twgl.ProgramInfo} programInfo a `ProgramInfo` as returned from {@link module:twgl.createProgramInfo} @param {string} blockName The name of the block. @return {module:twgl.UniformBlockInfo} The created UniformBlockInfo @memberOf module:twgl/programs
[ "Creates", "a", "UniformBlockInfo", "for", "the", "specified", "block" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L1138-L1140
8,808
greggman/twgl.js
src/programs.js
bindUniformBlock
function bindUniformBlock(gl, programInfo, uniformBlockInfo) { const uniformBlockSpec = programInfo.uniformBlockSpec || programInfo; const blockSpec = uniformBlockSpec.blockSpecs[uniformBlockInfo.name]; if (blockSpec) { const bufferBindIndex = blockSpec.index; gl.bindBufferRange(gl.UNIFORM_BUFFER, bufferBindIndex, uniformBlockInfo.buffer, uniformBlockInfo.offset || 0, uniformBlockInfo.array.byteLength); return true; } return false; }
javascript
function bindUniformBlock(gl, programInfo, uniformBlockInfo) { const uniformBlockSpec = programInfo.uniformBlockSpec || programInfo; const blockSpec = uniformBlockSpec.blockSpecs[uniformBlockInfo.name]; if (blockSpec) { const bufferBindIndex = blockSpec.index; gl.bindBufferRange(gl.UNIFORM_BUFFER, bufferBindIndex, uniformBlockInfo.buffer, uniformBlockInfo.offset || 0, uniformBlockInfo.array.byteLength); return true; } return false; }
[ "function", "bindUniformBlock", "(", "gl", ",", "programInfo", ",", "uniformBlockInfo", ")", "{", "const", "uniformBlockSpec", "=", "programInfo", ".", "uniformBlockSpec", "||", "programInfo", ";", "const", "blockSpec", "=", "uniformBlockSpec", ".", "blockSpecs", "[", "uniformBlockInfo", ".", "name", "]", ";", "if", "(", "blockSpec", ")", "{", "const", "bufferBindIndex", "=", "blockSpec", ".", "index", ";", "gl", ".", "bindBufferRange", "(", "gl", ".", "UNIFORM_BUFFER", ",", "bufferBindIndex", ",", "uniformBlockInfo", ".", "buffer", ",", "uniformBlockInfo", ".", "offset", "||", "0", ",", "uniformBlockInfo", ".", "array", ".", "byteLength", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Binds a unform block to the matching uniform block point. Matches by blocks by name so blocks must have the same name not just the same structure. If you have changed any values and you upload the valus into the corresponding WebGLBuffer call {@link module:twgl.setUniformBlock} instead. @param {WebGL2RenderingContext} gl A WebGL 2 rendering context. @param {(module:twgl.ProgramInfo|module:twgl.UniformBlockSpec)} programInfo a `ProgramInfo` as returned from {@link module:twgl.createProgramInfo} or or `UniformBlockSpec` as returned from {@link module:twgl.createUniformBlockSpecFromProgram}. @param {module:twgl.UniformBlockInfo} uniformBlockInfo a `UniformBlockInfo` as returned from {@link module:twgl.createUniformBlockInfo}. @return {bool} true if buffer was bound. If the programInfo has no block with the same block name no buffer is bound. @memberOf module:twgl/programs
[ "Binds", "a", "unform", "block", "to", "the", "matching", "uniform", "block", "point", ".", "Matches", "by", "blocks", "by", "name", "so", "blocks", "must", "have", "the", "same", "name", "not", "just", "the", "same", "structure", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L1160-L1169
8,809
greggman/twgl.js
src/programs.js
setUniformBlock
function setUniformBlock(gl, programInfo, uniformBlockInfo) { if (bindUniformBlock(gl, programInfo, uniformBlockInfo)) { gl.bufferData(gl.UNIFORM_BUFFER, uniformBlockInfo.array, gl.DYNAMIC_DRAW); } }
javascript
function setUniformBlock(gl, programInfo, uniformBlockInfo) { if (bindUniformBlock(gl, programInfo, uniformBlockInfo)) { gl.bufferData(gl.UNIFORM_BUFFER, uniformBlockInfo.array, gl.DYNAMIC_DRAW); } }
[ "function", "setUniformBlock", "(", "gl", ",", "programInfo", ",", "uniformBlockInfo", ")", "{", "if", "(", "bindUniformBlock", "(", "gl", ",", "programInfo", ",", "uniformBlockInfo", ")", ")", "{", "gl", ".", "bufferData", "(", "gl", ".", "UNIFORM_BUFFER", ",", "uniformBlockInfo", ".", "array", ",", "gl", ".", "DYNAMIC_DRAW", ")", ";", "}", "}" ]
Uploads the current uniform values to the corresponding WebGLBuffer and binds that buffer to the program's corresponding bind point for the uniform block object. If you haven't changed any values and you only need to bind the uniform block object call {@link module:twgl.bindUniformBlock} instead. @param {WebGL2RenderingContext} gl A WebGL 2 rendering context. @param {(module:twgl.ProgramInfo|module:twgl.UniformBlockSpec)} programInfo a `ProgramInfo` as returned from {@link module:twgl.createProgramInfo} or or `UniformBlockSpec` as returned from {@link module:twgl.createUniformBlockSpecFromProgram}. @param {module:twgl.UniformBlockInfo} uniformBlockInfo a `UniformBlockInfo` as returned from {@link module:twgl.createUniformBlockInfo}. @memberOf module:twgl/programs
[ "Uploads", "the", "current", "uniform", "values", "to", "the", "corresponding", "WebGLBuffer", "and", "binds", "that", "buffer", "to", "the", "program", "s", "corresponding", "bind", "point", "for", "the", "uniform", "block", "object", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L1186-L1190
8,810
greggman/twgl.js
src/programs.js
setBlockUniforms
function setBlockUniforms(uniformBlockInfo, values) { const uniforms = uniformBlockInfo.uniforms; for (const name in values) { const array = uniforms[name]; if (array) { const value = values[name]; if (value.length) { array.set(value); } else { array[0] = value; } } } }
javascript
function setBlockUniforms(uniformBlockInfo, values) { const uniforms = uniformBlockInfo.uniforms; for (const name in values) { const array = uniforms[name]; if (array) { const value = values[name]; if (value.length) { array.set(value); } else { array[0] = value; } } } }
[ "function", "setBlockUniforms", "(", "uniformBlockInfo", ",", "values", ")", "{", "const", "uniforms", "=", "uniformBlockInfo", ".", "uniforms", ";", "for", "(", "const", "name", "in", "values", ")", "{", "const", "array", "=", "uniforms", "[", "name", "]", ";", "if", "(", "array", ")", "{", "const", "value", "=", "values", "[", "name", "]", ";", "if", "(", "value", ".", "length", ")", "{", "array", ".", "set", "(", "value", ")", ";", "}", "else", "{", "array", "[", "0", "]", "=", "value", ";", "}", "}", "}", "}" ]
Sets values of a uniform block object @param {module:twgl.UniformBlockInfo} uniformBlockInfo A UniformBlockInfo as returned by {@link module:twgl.createUniformBlockInfo}. @param {Object.<string, ?>} values A uniform name to value map where the value is correct for the given type of uniform. So for example given a block like uniform SomeBlock { float someFloat; vec2 someVec2; vec3 someVec3Array[2]; int someInt; } You can set the values of the uniform block with twgl.setBlockUniforms(someBlockInfo, { someFloat: 12.3, someVec2: [1, 2], someVec3Array: [1, 2, 3, 4, 5, 6], someInt: 5, } Arrays can be JavaScript arrays or typed arrays Any name that doesn't match will be ignored @memberOf module:twgl/programs
[ "Sets", "values", "of", "a", "uniform", "block", "object" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L1220-L1233
8,811
greggman/twgl.js
src/programs.js
createProgramInfo
function createProgramInfo( gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) { const progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback); let good = true; shaderSources = shaderSources.map(function(source) { // Lets assume if there is no \n it's an id if (source.indexOf("\n") < 0) { const script = getElementById(source); if (!script) { progOptions.errorCallback("no element with id: " + source); good = false; } else { source = script.text; } } return source; }); if (!good) { return null; } const program = createProgramFromSources(gl, shaderSources, progOptions); if (!program) { return null; } return createProgramInfoFromProgram(gl, program); }
javascript
function createProgramInfo( gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) { const progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback); let good = true; shaderSources = shaderSources.map(function(source) { // Lets assume if there is no \n it's an id if (source.indexOf("\n") < 0) { const script = getElementById(source); if (!script) { progOptions.errorCallback("no element with id: " + source); good = false; } else { source = script.text; } } return source; }); if (!good) { return null; } const program = createProgramFromSources(gl, shaderSources, progOptions); if (!program) { return null; } return createProgramInfoFromProgram(gl, program); }
[ "function", "createProgramInfo", "(", "gl", ",", "shaderSources", ",", "opt_attribs", ",", "opt_locations", ",", "opt_errorCallback", ")", "{", "const", "progOptions", "=", "getProgramOptions", "(", "opt_attribs", ",", "opt_locations", ",", "opt_errorCallback", ")", ";", "let", "good", "=", "true", ";", "shaderSources", "=", "shaderSources", ".", "map", "(", "function", "(", "source", ")", "{", "// Lets assume if there is no \\n it's an id", "if", "(", "source", ".", "indexOf", "(", "\"\\n\"", ")", "<", "0", ")", "{", "const", "script", "=", "getElementById", "(", "source", ")", ";", "if", "(", "!", "script", ")", "{", "progOptions", ".", "errorCallback", "(", "\"no element with id: \"", "+", "source", ")", ";", "good", "=", "false", ";", "}", "else", "{", "source", "=", "script", ".", "text", ";", "}", "}", "return", "source", ";", "}", ")", ";", "if", "(", "!", "good", ")", "{", "return", "null", ";", "}", "const", "program", "=", "createProgramFromSources", "(", "gl", ",", "shaderSources", ",", "progOptions", ")", ";", "if", "(", "!", "program", ")", "{", "return", "null", ";", "}", "return", "createProgramInfoFromProgram", "(", "gl", ",", "program", ")", ";", "}" ]
Creates a ProgramInfo from 2 sources. A ProgramInfo contains programInfo = { program: WebGLProgram, uniformSetters: object of setters as returned from createUniformSetters, attribSetters: object of setters as returned from createAttribSetters, } NOTE: There are 4 signatures for this function twgl.createProgramInfo(gl, [vs, fs], options); twgl.createProgramInfo(gl, [vs, fs], opt_errFunc); twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_errFunc); twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc); @param {WebGLRenderingContext} gl The WebGLRenderingContext to use. @param {string[]} shaderSources Array of sources for the shaders or ids. The first is assumed to be the vertex shader, the second the fragment shader. @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback. @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console on error. If you want something else pass an callback. It's passed an error message. @return {module:twgl.ProgramInfo?} The created ProgramInfo or null if it failed to link or compile @memberOf module:twgl/programs
[ "Creates", "a", "ProgramInfo", "from", "2", "sources", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/programs.js#L1584-L1609
8,812
greggman/twgl.js
src/textures.js
canGenerateMipmap
function canGenerateMipmap(gl, width, height, internalFormat /*, type */) { if (!utils.isWebGL2(gl)) { return isPowerOf2(width) && isPowerOf2(height); } const info = textureInternalFormatInfo[internalFormat]; if (!info) { throw "unknown internal format"; } return info.colorRenderable && info.textureFilterable; }
javascript
function canGenerateMipmap(gl, width, height, internalFormat /*, type */) { if (!utils.isWebGL2(gl)) { return isPowerOf2(width) && isPowerOf2(height); } const info = textureInternalFormatInfo[internalFormat]; if (!info) { throw "unknown internal format"; } return info.colorRenderable && info.textureFilterable; }
[ "function", "canGenerateMipmap", "(", "gl", ",", "width", ",", "height", ",", "internalFormat", "/*, type */", ")", "{", "if", "(", "!", "utils", ".", "isWebGL2", "(", "gl", ")", ")", "{", "return", "isPowerOf2", "(", "width", ")", "&&", "isPowerOf2", "(", "height", ")", ";", "}", "const", "info", "=", "textureInternalFormatInfo", "[", "internalFormat", "]", ";", "if", "(", "!", "info", ")", "{", "throw", "\"unknown internal format\"", ";", "}", "return", "info", ".", "colorRenderable", "&&", "info", ".", "textureFilterable", ";", "}" ]
Gets whether or not we can generate mips for the given internal format. @param {number} internalFormat The internalFormat parameter from texImage2D etc.. @param {number} type The type parameter for texImage2D etc.. @return {boolean} true if we can generate mips @memberOf module:twgl/textures
[ "Gets", "whether", "or", "not", "we", "can", "generate", "mips", "for", "the", "given", "internal", "format", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L348-L357
8,813
greggman/twgl.js
src/textures.js
getTextureTypeForArrayType
function getTextureTypeForArrayType(gl, src, defaultType) { if (isArrayBuffer(src)) { return typedArrays.getGLTypeForTypedArray(src); } return defaultType || gl.UNSIGNED_BYTE; }
javascript
function getTextureTypeForArrayType(gl, src, defaultType) { if (isArrayBuffer(src)) { return typedArrays.getGLTypeForTypedArray(src); } return defaultType || gl.UNSIGNED_BYTE; }
[ "function", "getTextureTypeForArrayType", "(", "gl", ",", "src", ",", "defaultType", ")", "{", "if", "(", "isArrayBuffer", "(", "src", ")", ")", "{", "return", "typedArrays", ".", "getGLTypeForTypedArray", "(", "src", ")", ";", "}", "return", "defaultType", "||", "gl", ".", "UNSIGNED_BYTE", ";", "}" ]
Gets the texture type for a given array type. @param {WebGLRenderingContext} gl the WebGLRenderingContext @return {number} the gl texture type @private
[ "Gets", "the", "texture", "type", "for", "a", "given", "array", "type", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L394-L399
8,814
greggman/twgl.js
src/textures.js
savePackState
function savePackState(gl, options) { if (options.colorspaceConversion !== undefined) { lastPackState.colorspaceConversion = gl.getParameter(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL); gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, options.colorspaceConversion); } if (options.premultiplyAlpha !== undefined) { lastPackState.premultiplyAlpha = gl.getParameter(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, options.premultiplyAlpha); } if (options.flipY !== undefined) { lastPackState.flipY = gl.getParameter(gl.UNPACK_FLIP_Y_WEBGL); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, options.flipY); } }
javascript
function savePackState(gl, options) { if (options.colorspaceConversion !== undefined) { lastPackState.colorspaceConversion = gl.getParameter(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL); gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, options.colorspaceConversion); } if (options.premultiplyAlpha !== undefined) { lastPackState.premultiplyAlpha = gl.getParameter(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, options.premultiplyAlpha); } if (options.flipY !== undefined) { lastPackState.flipY = gl.getParameter(gl.UNPACK_FLIP_Y_WEBGL); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, options.flipY); } }
[ "function", "savePackState", "(", "gl", ",", "options", ")", "{", "if", "(", "options", ".", "colorspaceConversion", "!==", "undefined", ")", "{", "lastPackState", ".", "colorspaceConversion", "=", "gl", ".", "getParameter", "(", "gl", ".", "UNPACK_COLORSPACE_CONVERSION_WEBGL", ")", ";", "gl", ".", "pixelStorei", "(", "gl", ".", "UNPACK_COLORSPACE_CONVERSION_WEBGL", ",", "options", ".", "colorspaceConversion", ")", ";", "}", "if", "(", "options", ".", "premultiplyAlpha", "!==", "undefined", ")", "{", "lastPackState", ".", "premultiplyAlpha", "=", "gl", ".", "getParameter", "(", "gl", ".", "UNPACK_PREMULTIPLY_ALPHA_WEBGL", ")", ";", "gl", ".", "pixelStorei", "(", "gl", ".", "UNPACK_PREMULTIPLY_ALPHA_WEBGL", ",", "options", ".", "premultiplyAlpha", ")", ";", "}", "if", "(", "options", ".", "flipY", "!==", "undefined", ")", "{", "lastPackState", ".", "flipY", "=", "gl", ".", "getParameter", "(", "gl", ".", "UNPACK_FLIP_Y_WEBGL", ")", ";", "gl", ".", "pixelStorei", "(", "gl", ".", "UNPACK_FLIP_Y_WEBGL", ",", "options", ".", "flipY", ")", ";", "}", "}" ]
Saves any packing state that will be set based on the options. @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set. @param {WebGLRenderingContext} gl the WebGLRenderingContext @private
[ "Saves", "any", "packing", "state", "that", "will", "be", "set", "based", "on", "the", "options", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L574-L587
8,815
greggman/twgl.js
src/textures.js
restorePackState
function restorePackState(gl, options) { if (options.colorspaceConversion !== undefined) { gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, lastPackState.colorspaceConversion); } if (options.premultiplyAlpha !== undefined) { gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, lastPackState.premultiplyAlpha); } if (options.flipY !== undefined) { gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, lastPackState.flipY); } }
javascript
function restorePackState(gl, options) { if (options.colorspaceConversion !== undefined) { gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, lastPackState.colorspaceConversion); } if (options.premultiplyAlpha !== undefined) { gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, lastPackState.premultiplyAlpha); } if (options.flipY !== undefined) { gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, lastPackState.flipY); } }
[ "function", "restorePackState", "(", "gl", ",", "options", ")", "{", "if", "(", "options", ".", "colorspaceConversion", "!==", "undefined", ")", "{", "gl", ".", "pixelStorei", "(", "gl", ".", "UNPACK_COLORSPACE_CONVERSION_WEBGL", ",", "lastPackState", ".", "colorspaceConversion", ")", ";", "}", "if", "(", "options", ".", "premultiplyAlpha", "!==", "undefined", ")", "{", "gl", ".", "pixelStorei", "(", "gl", ".", "UNPACK_PREMULTIPLY_ALPHA_WEBGL", ",", "lastPackState", ".", "premultiplyAlpha", ")", ";", "}", "if", "(", "options", ".", "flipY", "!==", "undefined", ")", "{", "gl", ".", "pixelStorei", "(", "gl", ".", "UNPACK_FLIP_Y_WEBGL", ",", "lastPackState", ".", "flipY", ")", ";", "}", "}" ]
Restores any packing state that was set based on the options. @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set. @param {WebGLRenderingContext} gl the WebGLRenderingContext @private
[ "Restores", "any", "packing", "state", "that", "was", "set", "based", "on", "the", "options", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L595-L605
8,816
greggman/twgl.js
src/textures.js
saveSkipState
function saveSkipState(gl) { lastPackState.unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT); if (utils.isWebGL2(gl)) { lastPackState.unpackRowLength = gl.getParameter(gl.UNPACK_ROW_LENGTH); lastPackState.unpackImageHeight = gl.getParameter(gl.UNPACK_IMAGE_HEIGHT); lastPackState.unpackSkipPixels = gl.getParameter(gl.UNPACK_SKIP_PIXELS); lastPackState.unpackSkipRows = gl.getParameter(gl.UNPACK_SKIP_ROWS); lastPackState.unpackSkipImages = gl.getParameter(gl.UNPACK_SKIP_IMAGES); } }
javascript
function saveSkipState(gl) { lastPackState.unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT); if (utils.isWebGL2(gl)) { lastPackState.unpackRowLength = gl.getParameter(gl.UNPACK_ROW_LENGTH); lastPackState.unpackImageHeight = gl.getParameter(gl.UNPACK_IMAGE_HEIGHT); lastPackState.unpackSkipPixels = gl.getParameter(gl.UNPACK_SKIP_PIXELS); lastPackState.unpackSkipRows = gl.getParameter(gl.UNPACK_SKIP_ROWS); lastPackState.unpackSkipImages = gl.getParameter(gl.UNPACK_SKIP_IMAGES); } }
[ "function", "saveSkipState", "(", "gl", ")", "{", "lastPackState", ".", "unpackAlignment", "=", "gl", ".", "getParameter", "(", "gl", ".", "UNPACK_ALIGNMENT", ")", ";", "if", "(", "utils", ".", "isWebGL2", "(", "gl", ")", ")", "{", "lastPackState", ".", "unpackRowLength", "=", "gl", ".", "getParameter", "(", "gl", ".", "UNPACK_ROW_LENGTH", ")", ";", "lastPackState", ".", "unpackImageHeight", "=", "gl", ".", "getParameter", "(", "gl", ".", "UNPACK_IMAGE_HEIGHT", ")", ";", "lastPackState", ".", "unpackSkipPixels", "=", "gl", ".", "getParameter", "(", "gl", ".", "UNPACK_SKIP_PIXELS", ")", ";", "lastPackState", ".", "unpackSkipRows", "=", "gl", ".", "getParameter", "(", "gl", ".", "UNPACK_SKIP_ROWS", ")", ";", "lastPackState", ".", "unpackSkipImages", "=", "gl", ".", "getParameter", "(", "gl", ".", "UNPACK_SKIP_IMAGES", ")", ";", "}", "}" ]
Saves state related to data size @param {WebGLRenderingContext} gl the WebGLRenderingContext @private
[ "Saves", "state", "related", "to", "data", "size" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L612-L621
8,817
greggman/twgl.js
src/textures.js
setTextureSamplerParameters
function setTextureSamplerParameters(gl, target, parameteriFn, options) { if (options.minMag) { parameteriFn.call(gl, target, gl.TEXTURE_MIN_FILTER, options.minMag); parameteriFn.call(gl, target, gl.TEXTURE_MAG_FILTER, options.minMag); } if (options.min) { parameteriFn.call(gl, target, gl.TEXTURE_MIN_FILTER, options.min); } if (options.mag) { parameteriFn.call(gl, target, gl.TEXTURE_MAG_FILTER, options.mag); } if (options.wrap) { parameteriFn.call(gl, target, gl.TEXTURE_WRAP_S, options.wrap); parameteriFn.call(gl, target, gl.TEXTURE_WRAP_T, options.wrap); if (target === gl.TEXTURE_3D || helper.isSampler(gl, target)) { parameteriFn.call(gl, target, gl.TEXTURE_WRAP_R, options.wrap); } } if (options.wrapR) { parameteriFn.call(gl, target, gl.TEXTURE_WRAP_R, options.wrapR); } if (options.wrapS) { parameteriFn.call(gl, target, gl.TEXTURE_WRAP_S, options.wrapS); } if (options.wrapT) { parameteriFn.call(gl, target, gl.TEXTURE_WRAP_T, options.wrapT); } if (options.minLod) { parameteriFn.call(gl, target, gl.TEXTURE_MIN_LOD, options.minLod); } if (options.maxLod) { parameteriFn.call(gl, target, gl.TEXTURE_MAX_LOD, options.maxLod); } if (options.baseLevel) { parameteriFn.call(gl, target, gl.TEXTURE_BASE_LEVEL, options.baseLevel); } if (options.maxLevel) { parameteriFn.call(gl, target, gl.TEXTURE_MAX_LEVEL, options.maxLevel); } }
javascript
function setTextureSamplerParameters(gl, target, parameteriFn, options) { if (options.minMag) { parameteriFn.call(gl, target, gl.TEXTURE_MIN_FILTER, options.minMag); parameteriFn.call(gl, target, gl.TEXTURE_MAG_FILTER, options.minMag); } if (options.min) { parameteriFn.call(gl, target, gl.TEXTURE_MIN_FILTER, options.min); } if (options.mag) { parameteriFn.call(gl, target, gl.TEXTURE_MAG_FILTER, options.mag); } if (options.wrap) { parameteriFn.call(gl, target, gl.TEXTURE_WRAP_S, options.wrap); parameteriFn.call(gl, target, gl.TEXTURE_WRAP_T, options.wrap); if (target === gl.TEXTURE_3D || helper.isSampler(gl, target)) { parameteriFn.call(gl, target, gl.TEXTURE_WRAP_R, options.wrap); } } if (options.wrapR) { parameteriFn.call(gl, target, gl.TEXTURE_WRAP_R, options.wrapR); } if (options.wrapS) { parameteriFn.call(gl, target, gl.TEXTURE_WRAP_S, options.wrapS); } if (options.wrapT) { parameteriFn.call(gl, target, gl.TEXTURE_WRAP_T, options.wrapT); } if (options.minLod) { parameteriFn.call(gl, target, gl.TEXTURE_MIN_LOD, options.minLod); } if (options.maxLod) { parameteriFn.call(gl, target, gl.TEXTURE_MAX_LOD, options.maxLod); } if (options.baseLevel) { parameteriFn.call(gl, target, gl.TEXTURE_BASE_LEVEL, options.baseLevel); } if (options.maxLevel) { parameteriFn.call(gl, target, gl.TEXTURE_MAX_LEVEL, options.maxLevel); } }
[ "function", "setTextureSamplerParameters", "(", "gl", ",", "target", ",", "parameteriFn", ",", "options", ")", "{", "if", "(", "options", ".", "minMag", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_MIN_FILTER", ",", "options", ".", "minMag", ")", ";", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_MAG_FILTER", ",", "options", ".", "minMag", ")", ";", "}", "if", "(", "options", ".", "min", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_MIN_FILTER", ",", "options", ".", "min", ")", ";", "}", "if", "(", "options", ".", "mag", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_MAG_FILTER", ",", "options", ".", "mag", ")", ";", "}", "if", "(", "options", ".", "wrap", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_WRAP_S", ",", "options", ".", "wrap", ")", ";", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_WRAP_T", ",", "options", ".", "wrap", ")", ";", "if", "(", "target", "===", "gl", ".", "TEXTURE_3D", "||", "helper", ".", "isSampler", "(", "gl", ",", "target", ")", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_WRAP_R", ",", "options", ".", "wrap", ")", ";", "}", "}", "if", "(", "options", ".", "wrapR", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_WRAP_R", ",", "options", ".", "wrapR", ")", ";", "}", "if", "(", "options", ".", "wrapS", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_WRAP_S", ",", "options", ".", "wrapS", ")", ";", "}", "if", "(", "options", ".", "wrapT", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_WRAP_T", ",", "options", ".", "wrapT", ")", ";", "}", "if", "(", "options", ".", "minLod", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_MIN_LOD", ",", "options", ".", "minLod", ")", ";", "}", "if", "(", "options", ".", "maxLod", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_MAX_LOD", ",", "options", ".", "maxLod", ")", ";", "}", "if", "(", "options", ".", "baseLevel", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_BASE_LEVEL", ",", "options", ".", "baseLevel", ")", ";", "}", "if", "(", "options", ".", "maxLevel", ")", "{", "parameteriFn", ".", "call", "(", "gl", ",", "target", ",", "gl", ".", "TEXTURE_MAX_LEVEL", ",", "options", ".", "maxLevel", ")", ";", "}", "}" ]
Sets the parameters of a texture or sampler @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {number|WebGLSampler} target texture target or sampler @param {function()} parameteriFn texParamteri or samplerParameteri fn @param {WebGLTexture} tex the WebGLTexture to set parameters for @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture. @private
[ "Sets", "the", "parameters", "of", "a", "texture", "or", "sampler" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L650-L689
8,818
greggman/twgl.js
src/textures.js
setTextureParameters
function setTextureParameters(gl, tex, options) { const target = options.target || gl.TEXTURE_2D; gl.bindTexture(target, tex); setTextureSamplerParameters(gl, target, gl.texParameteri, options); }
javascript
function setTextureParameters(gl, tex, options) { const target = options.target || gl.TEXTURE_2D; gl.bindTexture(target, tex); setTextureSamplerParameters(gl, target, gl.texParameteri, options); }
[ "function", "setTextureParameters", "(", "gl", ",", "tex", ",", "options", ")", "{", "const", "target", "=", "options", ".", "target", "||", "gl", ".", "TEXTURE_2D", ";", "gl", ".", "bindTexture", "(", "target", ",", "tex", ")", ";", "setTextureSamplerParameters", "(", "gl", ",", "target", ",", "gl", ".", "texParameteri", ",", "options", ")", ";", "}" ]
Sets the texture parameters of a texture. @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {WebGLTexture} tex the WebGLTexture to set parameters for @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture. @memberOf module:twgl/textures
[ "Sets", "the", "texture", "parameters", "of", "a", "texture", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L699-L703
8,819
greggman/twgl.js
src/textures.js
setSamplerParameters
function setSamplerParameters(gl, sampler, options) { setTextureSamplerParameters(gl, sampler, gl.samplerParameteri, options); }
javascript
function setSamplerParameters(gl, sampler, options) { setTextureSamplerParameters(gl, sampler, gl.samplerParameteri, options); }
[ "function", "setSamplerParameters", "(", "gl", ",", "sampler", ",", "options", ")", "{", "setTextureSamplerParameters", "(", "gl", ",", "sampler", ",", "gl", ".", "samplerParameteri", ",", "options", ")", ";", "}" ]
Sets the sampler parameters of a sampler. @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {WebGLSampler} sampler the WebGLSampler to set parameters for @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set. @memberOf module:twgl/textures
[ "Sets", "the", "sampler", "parameters", "of", "a", "sampler", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L712-L714
8,820
greggman/twgl.js
src/textures.js
createSampler
function createSampler(gl, options) { const sampler = gl.createSampler(); setSamplerParameters(gl, sampler, options); return sampler; }
javascript
function createSampler(gl, options) { const sampler = gl.createSampler(); setSamplerParameters(gl, sampler, options); return sampler; }
[ "function", "createSampler", "(", "gl", ",", "options", ")", "{", "const", "sampler", "=", "gl", ".", "createSampler", "(", ")", ";", "setSamplerParameters", "(", "gl", ",", "sampler", ",", "options", ")", ";", "return", "sampler", ";", "}" ]
Creates a new sampler object and sets parameters. Example: const sampler = twgl.createSampler(gl, { minMag: gl.NEAREST, // sets both TEXTURE_MIN_FILTER and TEXTURE_MAG_FILTER wrap: gl.CLAMP_TO_NEAREST, // sets both TEXTURE_WRAP_S and TEXTURE_WRAP_T and TEXTURE_WRAP_R }); @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {Object.<string,module:twgl.TextureOptions>} options A object of TextureOptions one per sampler. @return {Object.<string,WebGLSampler>} the created samplers by name @private
[ "Creates", "a", "new", "sampler", "object", "and", "sets", "parameters", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L731-L735
8,821
greggman/twgl.js
src/textures.js
createSamplers
function createSamplers(gl, samplerOptions) { const samplers = {}; Object.keys(samplerOptions).forEach(function(name) { samplers[name] = createSampler(gl, samplerOptions[name]); }); return samplers; }
javascript
function createSamplers(gl, samplerOptions) { const samplers = {}; Object.keys(samplerOptions).forEach(function(name) { samplers[name] = createSampler(gl, samplerOptions[name]); }); return samplers; }
[ "function", "createSamplers", "(", "gl", ",", "samplerOptions", ")", "{", "const", "samplers", "=", "{", "}", ";", "Object", ".", "keys", "(", "samplerOptions", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "samplers", "[", "name", "]", "=", "createSampler", "(", "gl", ",", "samplerOptions", "[", "name", "]", ")", ";", "}", ")", ";", "return", "samplers", ";", "}" ]
Creates a multiple sampler objects and sets parameters on each. Example: const samplers = twgl.createSamplers(gl, { nearest: { minMag: gl.NEAREST, }, nearestClampS: { minMag: gl.NEAREST, wrapS: gl.CLAMP_TO_NEAREST, }, linear: { minMag: gl.LINEAR, }, nearestClamp: { minMag: gl.NEAREST, wrap: gl.CLAMP_TO_EDGE, }, linearClamp: { minMag: gl.LINEAR, wrap: gl.CLAMP_TO_EDGE, }, linearClampT: { minMag: gl.LINEAR, wrapT: gl.CLAMP_TO_EDGE, }, }); @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set on the sampler @private
[ "Creates", "a", "multiple", "sampler", "objects", "and", "sets", "parameters", "on", "each", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L771-L777
8,822
greggman/twgl.js
src/textures.js
make1Pixel
function make1Pixel(color) { color = color || defaults.textureColor; if (isArrayBuffer(color)) { return color; } return new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]); }
javascript
function make1Pixel(color) { color = color || defaults.textureColor; if (isArrayBuffer(color)) { return color; } return new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]); }
[ "function", "make1Pixel", "(", "color", ")", "{", "color", "=", "color", "||", "defaults", ".", "textureColor", ";", "if", "(", "isArrayBuffer", "(", "color", ")", ")", "{", "return", "color", ";", "}", "return", "new", "Uint8Array", "(", "[", "color", "[", "0", "]", "*", "255", ",", "color", "[", "1", "]", "*", "255", ",", "color", "[", "2", "]", "*", "255", ",", "color", "[", "3", "]", "*", "255", "]", ")", ";", "}" ]
Makes a 1x1 pixel If no color is passed in uses the default color which can be set by calling `setDefaultTextureColor`. @param {(number[]|ArrayBufferView)} [color] The color using 0-1 values @return {Uint8Array} Unit8Array with color. @private
[ "Makes", "a", "1x1", "pixel", "If", "no", "color", "is", "passed", "in", "uses", "the", "default", "color", "which", "can", "be", "set", "by", "calling", "setDefaultTextureColor", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L786-L792
8,823
greggman/twgl.js
src/textures.js
getCubeFaceOrder
function getCubeFaceOrder(gl, options) { options = options || {}; return options.cubeFaceOrder || [ gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, ]; }
javascript
function getCubeFaceOrder(gl, options) { options = options || {}; return options.cubeFaceOrder || [ gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, ]; }
[ "function", "getCubeFaceOrder", "(", "gl", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "return", "options", ".", "cubeFaceOrder", "||", "[", "gl", ".", "TEXTURE_CUBE_MAP_POSITIVE_X", ",", "gl", ".", "TEXTURE_CUBE_MAP_NEGATIVE_X", ",", "gl", ".", "TEXTURE_CUBE_MAP_POSITIVE_Y", ",", "gl", ".", "TEXTURE_CUBE_MAP_NEGATIVE_Y", ",", "gl", ".", "TEXTURE_CUBE_MAP_POSITIVE_Z", ",", "gl", ".", "TEXTURE_CUBE_MAP_NEGATIVE_Z", ",", "]", ";", "}" ]
Gets an array of cubemap face enums @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture. @return {number[]} cubemap face enums @private
[ "Gets", "an", "array", "of", "cubemap", "face", "enums" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L839-L849
8,824
greggman/twgl.js
src/textures.js
urlIsSameOrigin
function urlIsSameOrigin(url) { if (typeof document !== 'undefined') { // for IE really const a = document.createElement('a'); a.href = url; return a.hostname === location.hostname && a.port === location.port && a.protocol === location.protocol; } else { const localOrigin = (new URL(location.href)).origin; const urlOrigin = (new URL(url, location.href)).origin; return urlOrigin === localOrigin; } }
javascript
function urlIsSameOrigin(url) { if (typeof document !== 'undefined') { // for IE really const a = document.createElement('a'); a.href = url; return a.hostname === location.hostname && a.port === location.port && a.protocol === location.protocol; } else { const localOrigin = (new URL(location.href)).origin; const urlOrigin = (new URL(url, location.href)).origin; return urlOrigin === localOrigin; } }
[ "function", "urlIsSameOrigin", "(", "url", ")", "{", "if", "(", "typeof", "document", "!==", "'undefined'", ")", "{", "// for IE really", "const", "a", "=", "document", ".", "createElement", "(", "'a'", ")", ";", "a", ".", "href", "=", "url", ";", "return", "a", ".", "hostname", "===", "location", ".", "hostname", "&&", "a", ".", "port", "===", "location", ".", "port", "&&", "a", ".", "protocol", "===", "location", ".", "protocol", ";", "}", "else", "{", "const", "localOrigin", "=", "(", "new", "URL", "(", "location", ".", "href", ")", ")", ".", "origin", ";", "const", "urlOrigin", "=", "(", "new", "URL", "(", "url", ",", "location", ".", "href", ")", ")", ".", "origin", ";", "return", "urlOrigin", "===", "localOrigin", ";", "}", "}" ]
Checks whether the url's origin is the same so that we can set the `crossOrigin` @param {string} url url to image @returns {boolean} true if the window's origin is the same as image's url @private
[ "Checks", "whether", "the", "url", "s", "origin", "is", "the", "same", "so", "that", "we", "can", "set", "the", "crossOrigin" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L1018-L1031
8,825
greggman/twgl.js
src/textures.js
loadImage
function loadImage(url, crossOrigin, callback) { callback = callback || noop; let img; crossOrigin = crossOrigin !== undefined ? crossOrigin : defaults.crossOrigin; crossOrigin = setToAnonymousIfUndefinedAndURLIsNotSameOrigin(url, crossOrigin); if (typeof Image !== 'undefined') { img = new Image(); if (crossOrigin !== undefined) { img.crossOrigin = crossOrigin; } const clearEventHandlers = function clearEventHandlers() { img.removeEventListener('error', onError); // eslint-disable-line img.removeEventListener('load', onLoad); // eslint-disable-line img = null; }; const onError = function onError() { const msg = "couldn't load image: " + url; helper.error(msg); callback(msg, img); clearEventHandlers(); }; const onLoad = function onLoad() { callback(null, img); clearEventHandlers(); }; img.addEventListener('error', onError); img.addEventListener('load', onLoad); img.src = url; return img; } else if (typeof ImageBitmap !== 'undefined') { let err; let bm; const cb = function cb() { callback(err, bm); }; const options = {}; if (crossOrigin) { options.mode = 'cors'; // TODO: not sure how to translate image.crossOrigin } fetch(url, options).then(function(response) { if (!response.ok) { throw response; } return response.blob(); }).then(function(blob) { return createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none', }); }).then(function(bitmap) { // not sure if this works. We don't want // to catch the user's error. So, call // the callback in a timeout so we're // not in this scope inside the promise. bm = bitmap; setTimeout(cb); }).catch(function(e) { err = e; setTimeout(cb); }); img = null; } return img; }
javascript
function loadImage(url, crossOrigin, callback) { callback = callback || noop; let img; crossOrigin = crossOrigin !== undefined ? crossOrigin : defaults.crossOrigin; crossOrigin = setToAnonymousIfUndefinedAndURLIsNotSameOrigin(url, crossOrigin); if (typeof Image !== 'undefined') { img = new Image(); if (crossOrigin !== undefined) { img.crossOrigin = crossOrigin; } const clearEventHandlers = function clearEventHandlers() { img.removeEventListener('error', onError); // eslint-disable-line img.removeEventListener('load', onLoad); // eslint-disable-line img = null; }; const onError = function onError() { const msg = "couldn't load image: " + url; helper.error(msg); callback(msg, img); clearEventHandlers(); }; const onLoad = function onLoad() { callback(null, img); clearEventHandlers(); }; img.addEventListener('error', onError); img.addEventListener('load', onLoad); img.src = url; return img; } else if (typeof ImageBitmap !== 'undefined') { let err; let bm; const cb = function cb() { callback(err, bm); }; const options = {}; if (crossOrigin) { options.mode = 'cors'; // TODO: not sure how to translate image.crossOrigin } fetch(url, options).then(function(response) { if (!response.ok) { throw response; } return response.blob(); }).then(function(blob) { return createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none', }); }).then(function(bitmap) { // not sure if this works. We don't want // to catch the user's error. So, call // the callback in a timeout so we're // not in this scope inside the promise. bm = bitmap; setTimeout(cb); }).catch(function(e) { err = e; setTimeout(cb); }); img = null; } return img; }
[ "function", "loadImage", "(", "url", ",", "crossOrigin", ",", "callback", ")", "{", "callback", "=", "callback", "||", "noop", ";", "let", "img", ";", "crossOrigin", "=", "crossOrigin", "!==", "undefined", "?", "crossOrigin", ":", "defaults", ".", "crossOrigin", ";", "crossOrigin", "=", "setToAnonymousIfUndefinedAndURLIsNotSameOrigin", "(", "url", ",", "crossOrigin", ")", ";", "if", "(", "typeof", "Image", "!==", "'undefined'", ")", "{", "img", "=", "new", "Image", "(", ")", ";", "if", "(", "crossOrigin", "!==", "undefined", ")", "{", "img", ".", "crossOrigin", "=", "crossOrigin", ";", "}", "const", "clearEventHandlers", "=", "function", "clearEventHandlers", "(", ")", "{", "img", ".", "removeEventListener", "(", "'error'", ",", "onError", ")", ";", "// eslint-disable-line", "img", ".", "removeEventListener", "(", "'load'", ",", "onLoad", ")", ";", "// eslint-disable-line", "img", "=", "null", ";", "}", ";", "const", "onError", "=", "function", "onError", "(", ")", "{", "const", "msg", "=", "\"couldn't load image: \"", "+", "url", ";", "helper", ".", "error", "(", "msg", ")", ";", "callback", "(", "msg", ",", "img", ")", ";", "clearEventHandlers", "(", ")", ";", "}", ";", "const", "onLoad", "=", "function", "onLoad", "(", ")", "{", "callback", "(", "null", ",", "img", ")", ";", "clearEventHandlers", "(", ")", ";", "}", ";", "img", ".", "addEventListener", "(", "'error'", ",", "onError", ")", ";", "img", ".", "addEventListener", "(", "'load'", ",", "onLoad", ")", ";", "img", ".", "src", "=", "url", ";", "return", "img", ";", "}", "else", "if", "(", "typeof", "ImageBitmap", "!==", "'undefined'", ")", "{", "let", "err", ";", "let", "bm", ";", "const", "cb", "=", "function", "cb", "(", ")", "{", "callback", "(", "err", ",", "bm", ")", ";", "}", ";", "const", "options", "=", "{", "}", ";", "if", "(", "crossOrigin", ")", "{", "options", ".", "mode", "=", "'cors'", ";", "// TODO: not sure how to translate image.crossOrigin", "}", "fetch", "(", "url", ",", "options", ")", ".", "then", "(", "function", "(", "response", ")", "{", "if", "(", "!", "response", ".", "ok", ")", "{", "throw", "response", ";", "}", "return", "response", ".", "blob", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "blob", ")", "{", "return", "createImageBitmap", "(", "blob", ",", "{", "premultiplyAlpha", ":", "'none'", ",", "colorSpaceConversion", ":", "'none'", ",", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "bitmap", ")", "{", "// not sure if this works. We don't want", "// to catch the user's error. So, call", "// the callback in a timeout so we're", "// not in this scope inside the promise.", "bm", "=", "bitmap", ";", "setTimeout", "(", "cb", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "err", "=", "e", ";", "setTimeout", "(", "cb", ")", ";", "}", ")", ";", "img", "=", "null", ";", "}", "return", "img", ";", "}" ]
Loads an image @param {string} url url to image @param {string} crossOrigin @param {function(err, img)} [callback] a callback that's passed an error and the image. The error will be non-null if there was an error @return {HTMLImageElement} the image being loaded. @private
[ "Loads", "an", "image" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L1048-L1116
8,826
greggman/twgl.js
src/textures.js
isTexImageSource
function isTexImageSource(obj) { return (typeof ImageBitmap !== 'undefined' && obj instanceof ImageBitmap) || (typeof ImageData !== 'undefined' && obj instanceof ImageData) || (typeof HTMLElement !== 'undefined' && obj instanceof HTMLElement); }
javascript
function isTexImageSource(obj) { return (typeof ImageBitmap !== 'undefined' && obj instanceof ImageBitmap) || (typeof ImageData !== 'undefined' && obj instanceof ImageData) || (typeof HTMLElement !== 'undefined' && obj instanceof HTMLElement); }
[ "function", "isTexImageSource", "(", "obj", ")", "{", "return", "(", "typeof", "ImageBitmap", "!==", "'undefined'", "&&", "obj", "instanceof", "ImageBitmap", ")", "||", "(", "typeof", "ImageData", "!==", "'undefined'", "&&", "obj", "instanceof", "ImageData", ")", "||", "(", "typeof", "HTMLElement", "!==", "'undefined'", "&&", "obj", "instanceof", "HTMLElement", ")", ";", "}" ]
check if object is a TexImageSource @param {Object} obj Object to test @return {boolean} true if object is a TexImageSource @private
[ "check", "if", "object", "is", "a", "TexImageSource" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L1125-L1129
8,827
greggman/twgl.js
src/textures.js
loadAndUseImage
function loadAndUseImage(obj, crossOrigin, callback) { if (isTexImageSource(obj)) { setTimeout(function() { callback(null, obj); }); return obj; } return loadImage(obj, crossOrigin, callback); }
javascript
function loadAndUseImage(obj, crossOrigin, callback) { if (isTexImageSource(obj)) { setTimeout(function() { callback(null, obj); }); return obj; } return loadImage(obj, crossOrigin, callback); }
[ "function", "loadAndUseImage", "(", "obj", ",", "crossOrigin", ",", "callback", ")", "{", "if", "(", "isTexImageSource", "(", "obj", ")", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "callback", "(", "null", ",", "obj", ")", ";", "}", ")", ";", "return", "obj", ";", "}", "return", "loadImage", "(", "obj", ",", "crossOrigin", ",", "callback", ")", ";", "}" ]
if obj is an TexImageSource then just uses it otherwise if obj is a string then load it first. @param {string|TexImageSource} obj @param {string} crossOrigin @param {function(err, img)} [callback] a callback that's passed an error and the image. The error will be non-null if there was an error @private
[ "if", "obj", "is", "an", "TexImageSource", "then", "just", "uses", "it", "otherwise", "if", "obj", "is", "a", "string", "then", "load", "it", "first", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L1142-L1151
8,828
greggman/twgl.js
src/textures.js
loadTextureFromUrl
function loadTextureFromUrl(gl, tex, options, callback) { callback = callback || noop; options = options || defaults.textureOptions; setTextureTo1PixelColor(gl, tex, options); // Because it's async we need to copy the options. options = Object.assign({}, options); const img = loadAndUseImage(options.src, options.crossOrigin, function(err, img) { if (err) { callback(err, tex, img); } else { setTextureFromElement(gl, tex, img, options); callback(null, tex, img); } }); return img; }
javascript
function loadTextureFromUrl(gl, tex, options, callback) { callback = callback || noop; options = options || defaults.textureOptions; setTextureTo1PixelColor(gl, tex, options); // Because it's async we need to copy the options. options = Object.assign({}, options); const img = loadAndUseImage(options.src, options.crossOrigin, function(err, img) { if (err) { callback(err, tex, img); } else { setTextureFromElement(gl, tex, img, options); callback(null, tex, img); } }); return img; }
[ "function", "loadTextureFromUrl", "(", "gl", ",", "tex", ",", "options", ",", "callback", ")", "{", "callback", "=", "callback", "||", "noop", ";", "options", "=", "options", "||", "defaults", ".", "textureOptions", ";", "setTextureTo1PixelColor", "(", "gl", ",", "tex", ",", "options", ")", ";", "// Because it's async we need to copy the options.", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "const", "img", "=", "loadAndUseImage", "(", "options", ".", "src", ",", "options", ".", "crossOrigin", ",", "function", "(", "err", ",", "img", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ",", "tex", ",", "img", ")", ";", "}", "else", "{", "setTextureFromElement", "(", "gl", ",", "tex", ",", "img", ",", "options", ")", ";", "callback", "(", "null", ",", "tex", ",", "img", ")", ";", "}", "}", ")", ";", "return", "img", ";", "}" ]
A callback for when an image finished downloading and been uploaded into a texture @callback ThreeDReadyCallback @param {*} err If truthy there was an error. @param {WebGLTexture} tex the texture. @param {HTMLImageElement[]} imgs the images for each slice. @memberOf module:twgl Loads a texture from an image from a Url as specified in `options.src` If `options.color !== false` will set the texture to a 1x1 pixel color so that the texture is immediately useable. It will be updated with the contents of the image once the image has finished downloading. Filtering options will be set as approriate for image unless `options.auto === false`. @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {WebGLTexture} tex the WebGLTexture to set parameters for @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set. @param {module:twgl.TextureReadyCallback} [callback] A function to be called when the image has finished loading. err will be non null if there was an error. @return {HTMLImageElement} the image being downloaded. @memberOf module:twgl/textures
[ "A", "callback", "for", "when", "an", "image", "finished", "downloading", "and", "been", "uploaded", "into", "a", "texture" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L1244-L1259
8,829
greggman/twgl.js
src/textures.js
setEmptyTexture
function setEmptyTexture(gl, tex, options) { const target = options.target || gl.TEXTURE_2D; gl.bindTexture(target, tex); const level = options.level || 0; const internalFormat = options.internalFormat || options.format || gl.RGBA; const formatType = getFormatAndTypeForInternalFormat(internalFormat); const format = options.format || formatType.format; const type = options.type || formatType.type; savePackState(gl, options); if (target === gl.TEXTURE_CUBE_MAP) { for (let ii = 0; ii < 6; ++ii) { gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, options.width, options.height, 0, format, type, null); } } else if (target === gl.TEXTURE_3D) { gl.texImage3D(target, level, internalFormat, options.width, options.height, options.depth, 0, format, type, null); } else { gl.texImage2D(target, level, internalFormat, options.width, options.height, 0, format, type, null); } restorePackState(gl, options); }
javascript
function setEmptyTexture(gl, tex, options) { const target = options.target || gl.TEXTURE_2D; gl.bindTexture(target, tex); const level = options.level || 0; const internalFormat = options.internalFormat || options.format || gl.RGBA; const formatType = getFormatAndTypeForInternalFormat(internalFormat); const format = options.format || formatType.format; const type = options.type || formatType.type; savePackState(gl, options); if (target === gl.TEXTURE_CUBE_MAP) { for (let ii = 0; ii < 6; ++ii) { gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, options.width, options.height, 0, format, type, null); } } else if (target === gl.TEXTURE_3D) { gl.texImage3D(target, level, internalFormat, options.width, options.height, options.depth, 0, format, type, null); } else { gl.texImage2D(target, level, internalFormat, options.width, options.height, 0, format, type, null); } restorePackState(gl, options); }
[ "function", "setEmptyTexture", "(", "gl", ",", "tex", ",", "options", ")", "{", "const", "target", "=", "options", ".", "target", "||", "gl", ".", "TEXTURE_2D", ";", "gl", ".", "bindTexture", "(", "target", ",", "tex", ")", ";", "const", "level", "=", "options", ".", "level", "||", "0", ";", "const", "internalFormat", "=", "options", ".", "internalFormat", "||", "options", ".", "format", "||", "gl", ".", "RGBA", ";", "const", "formatType", "=", "getFormatAndTypeForInternalFormat", "(", "internalFormat", ")", ";", "const", "format", "=", "options", ".", "format", "||", "formatType", ".", "format", ";", "const", "type", "=", "options", ".", "type", "||", "formatType", ".", "type", ";", "savePackState", "(", "gl", ",", "options", ")", ";", "if", "(", "target", "===", "gl", ".", "TEXTURE_CUBE_MAP", ")", "{", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "6", ";", "++", "ii", ")", "{", "gl", ".", "texImage2D", "(", "gl", ".", "TEXTURE_CUBE_MAP_POSITIVE_X", "+", "ii", ",", "level", ",", "internalFormat", ",", "options", ".", "width", ",", "options", ".", "height", ",", "0", ",", "format", ",", "type", ",", "null", ")", ";", "}", "}", "else", "if", "(", "target", "===", "gl", ".", "TEXTURE_3D", ")", "{", "gl", ".", "texImage3D", "(", "target", ",", "level", ",", "internalFormat", ",", "options", ".", "width", ",", "options", ".", "height", ",", "options", ".", "depth", ",", "0", ",", "format", ",", "type", ",", "null", ")", ";", "}", "else", "{", "gl", ".", "texImage2D", "(", "target", ",", "level", ",", "internalFormat", ",", "options", ".", "width", ",", "options", ".", "height", ",", "0", ",", "format", ",", "type", ",", "null", ")", ";", "}", "restorePackState", "(", "gl", ",", "options", ")", ";", "}" ]
Sets a texture with no contents of a certain size. In other words calls `gl.texImage2D` with `null`. You must set `options.width` and `options.height`. @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {WebGLTexture} tex the WebGLTexture to set parameters for @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set. @memberOf module:twgl/textures
[ "Sets", "a", "texture", "with", "no", "contents", "of", "a", "certain", "size", ".", "In", "other", "words", "calls", "gl", ".", "texImage2D", "with", "null", ".", "You", "must", "set", "options", ".", "width", "and", "options", ".", "height", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L1530-L1549
8,830
greggman/twgl.js
src/textures.js
createTexture
function createTexture(gl, options, callback) { callback = callback || noop; options = options || defaults.textureOptions; const tex = gl.createTexture(); const target = options.target || gl.TEXTURE_2D; let width = options.width || 1; let height = options.height || 1; const internalFormat = options.internalFormat || gl.RGBA; const formatType = getFormatAndTypeForInternalFormat(internalFormat); let type = options.type || formatType.type; gl.bindTexture(target, tex); if (target === gl.TEXTURE_CUBE_MAP) { // this should have been the default for CUBEMAPS :( gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); } let src = options.src; if (src) { if (typeof src === "function") { src = src(gl, options); } if (typeof (src) === "string") { loadTextureFromUrl(gl, tex, options, callback); } else if (isArrayBuffer(src) || (Array.isArray(src) && ( typeof src[0] === 'number' || Array.isArray(src[0]) || isArrayBuffer(src[0])) ) ) { const dimensions = setTextureFromArray(gl, tex, src, options); width = dimensions.width; height = dimensions.height; type = dimensions.type; } else if (Array.isArray(src) && (typeof (src[0]) === 'string' || isTexImageSource(src[0]))) { if (target === gl.TEXTURE_CUBE_MAP) { loadCubemapFromUrls(gl, tex, options, callback); } else { loadSlicesFromUrls(gl, tex, options, callback); } } else if (isTexImageSource(src)) { setTextureFromElement(gl, tex, src, options); width = src.width; height = src.height; } else { throw "unsupported src type"; } } else { setEmptyTexture(gl, tex, options); } if (shouldAutomaticallySetTextureFilteringForSize(options)) { setTextureFilteringForSize(gl, tex, options, width, height, internalFormat, type); } setTextureParameters(gl, tex, options); return tex; }
javascript
function createTexture(gl, options, callback) { callback = callback || noop; options = options || defaults.textureOptions; const tex = gl.createTexture(); const target = options.target || gl.TEXTURE_2D; let width = options.width || 1; let height = options.height || 1; const internalFormat = options.internalFormat || gl.RGBA; const formatType = getFormatAndTypeForInternalFormat(internalFormat); let type = options.type || formatType.type; gl.bindTexture(target, tex); if (target === gl.TEXTURE_CUBE_MAP) { // this should have been the default for CUBEMAPS :( gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); } let src = options.src; if (src) { if (typeof src === "function") { src = src(gl, options); } if (typeof (src) === "string") { loadTextureFromUrl(gl, tex, options, callback); } else if (isArrayBuffer(src) || (Array.isArray(src) && ( typeof src[0] === 'number' || Array.isArray(src[0]) || isArrayBuffer(src[0])) ) ) { const dimensions = setTextureFromArray(gl, tex, src, options); width = dimensions.width; height = dimensions.height; type = dimensions.type; } else if (Array.isArray(src) && (typeof (src[0]) === 'string' || isTexImageSource(src[0]))) { if (target === gl.TEXTURE_CUBE_MAP) { loadCubemapFromUrls(gl, tex, options, callback); } else { loadSlicesFromUrls(gl, tex, options, callback); } } else if (isTexImageSource(src)) { setTextureFromElement(gl, tex, src, options); width = src.width; height = src.height; } else { throw "unsupported src type"; } } else { setEmptyTexture(gl, tex, options); } if (shouldAutomaticallySetTextureFilteringForSize(options)) { setTextureFilteringForSize(gl, tex, options, width, height, internalFormat, type); } setTextureParameters(gl, tex, options); return tex; }
[ "function", "createTexture", "(", "gl", ",", "options", ",", "callback", ")", "{", "callback", "=", "callback", "||", "noop", ";", "options", "=", "options", "||", "defaults", ".", "textureOptions", ";", "const", "tex", "=", "gl", ".", "createTexture", "(", ")", ";", "const", "target", "=", "options", ".", "target", "||", "gl", ".", "TEXTURE_2D", ";", "let", "width", "=", "options", ".", "width", "||", "1", ";", "let", "height", "=", "options", ".", "height", "||", "1", ";", "const", "internalFormat", "=", "options", ".", "internalFormat", "||", "gl", ".", "RGBA", ";", "const", "formatType", "=", "getFormatAndTypeForInternalFormat", "(", "internalFormat", ")", ";", "let", "type", "=", "options", ".", "type", "||", "formatType", ".", "type", ";", "gl", ".", "bindTexture", "(", "target", ",", "tex", ")", ";", "if", "(", "target", "===", "gl", ".", "TEXTURE_CUBE_MAP", ")", "{", "// this should have been the default for CUBEMAPS :(", "gl", ".", "texParameteri", "(", "target", ",", "gl", ".", "TEXTURE_WRAP_S", ",", "gl", ".", "CLAMP_TO_EDGE", ")", ";", "gl", ".", "texParameteri", "(", "target", ",", "gl", ".", "TEXTURE_WRAP_T", ",", "gl", ".", "CLAMP_TO_EDGE", ")", ";", "}", "let", "src", "=", "options", ".", "src", ";", "if", "(", "src", ")", "{", "if", "(", "typeof", "src", "===", "\"function\"", ")", "{", "src", "=", "src", "(", "gl", ",", "options", ")", ";", "}", "if", "(", "typeof", "(", "src", ")", "===", "\"string\"", ")", "{", "loadTextureFromUrl", "(", "gl", ",", "tex", ",", "options", ",", "callback", ")", ";", "}", "else", "if", "(", "isArrayBuffer", "(", "src", ")", "||", "(", "Array", ".", "isArray", "(", "src", ")", "&&", "(", "typeof", "src", "[", "0", "]", "===", "'number'", "||", "Array", ".", "isArray", "(", "src", "[", "0", "]", ")", "||", "isArrayBuffer", "(", "src", "[", "0", "]", ")", ")", ")", ")", "{", "const", "dimensions", "=", "setTextureFromArray", "(", "gl", ",", "tex", ",", "src", ",", "options", ")", ";", "width", "=", "dimensions", ".", "width", ";", "height", "=", "dimensions", ".", "height", ";", "type", "=", "dimensions", ".", "type", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "src", ")", "&&", "(", "typeof", "(", "src", "[", "0", "]", ")", "===", "'string'", "||", "isTexImageSource", "(", "src", "[", "0", "]", ")", ")", ")", "{", "if", "(", "target", "===", "gl", ".", "TEXTURE_CUBE_MAP", ")", "{", "loadCubemapFromUrls", "(", "gl", ",", "tex", ",", "options", ",", "callback", ")", ";", "}", "else", "{", "loadSlicesFromUrls", "(", "gl", ",", "tex", ",", "options", ",", "callback", ")", ";", "}", "}", "else", "if", "(", "isTexImageSource", "(", "src", ")", ")", "{", "setTextureFromElement", "(", "gl", ",", "tex", ",", "src", ",", "options", ")", ";", "width", "=", "src", ".", "width", ";", "height", "=", "src", ".", "height", ";", "}", "else", "{", "throw", "\"unsupported src type\"", ";", "}", "}", "else", "{", "setEmptyTexture", "(", "gl", ",", "tex", ",", "options", ")", ";", "}", "if", "(", "shouldAutomaticallySetTextureFilteringForSize", "(", "options", ")", ")", "{", "setTextureFilteringForSize", "(", "gl", ",", "tex", ",", "options", ",", "width", ",", "height", ",", "internalFormat", ",", "type", ")", ";", "}", "setTextureParameters", "(", "gl", ",", "tex", ",", "options", ")", ";", "return", "tex", ";", "}" ]
Creates a texture based on the options passed in. @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set. @param {module:twgl.TextureReadyCallback} [callback] A callback called when an image has been downloaded and uploaded to the texture. @return {WebGLTexture} the created texture. @memberOf module:twgl/textures
[ "Creates", "a", "texture", "based", "on", "the", "options", "passed", "in", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L1559-L1614
8,831
greggman/twgl.js
src/textures.js
resizeTexture
function resizeTexture(gl, tex, options, width, height) { width = width || options.width; height = height || options.height; const target = options.target || gl.TEXTURE_2D; gl.bindTexture(target, tex); const level = options.level || 0; const internalFormat = options.internalFormat || options.format || gl.RGBA; const formatType = getFormatAndTypeForInternalFormat(internalFormat); const format = options.format || formatType.format; let type; const src = options.src; if (!src) { type = options.type || formatType.type; } else if (isArrayBuffer(src) || (Array.isArray(src) && typeof (src[0]) === 'number')) { type = options.type || getTextureTypeForArrayType(gl, src, formatType.type); } else { type = options.type || formatType.type; } if (target === gl.TEXTURE_CUBE_MAP) { for (let ii = 0; ii < 6; ++ii) { gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, width, height, 0, format, type, null); } } else { gl.texImage2D(target, level, internalFormat, width, height, 0, format, type, null); } }
javascript
function resizeTexture(gl, tex, options, width, height) { width = width || options.width; height = height || options.height; const target = options.target || gl.TEXTURE_2D; gl.bindTexture(target, tex); const level = options.level || 0; const internalFormat = options.internalFormat || options.format || gl.RGBA; const formatType = getFormatAndTypeForInternalFormat(internalFormat); const format = options.format || formatType.format; let type; const src = options.src; if (!src) { type = options.type || formatType.type; } else if (isArrayBuffer(src) || (Array.isArray(src) && typeof (src[0]) === 'number')) { type = options.type || getTextureTypeForArrayType(gl, src, formatType.type); } else { type = options.type || formatType.type; } if (target === gl.TEXTURE_CUBE_MAP) { for (let ii = 0; ii < 6; ++ii) { gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, width, height, 0, format, type, null); } } else { gl.texImage2D(target, level, internalFormat, width, height, 0, format, type, null); } }
[ "function", "resizeTexture", "(", "gl", ",", "tex", ",", "options", ",", "width", ",", "height", ")", "{", "width", "=", "width", "||", "options", ".", "width", ";", "height", "=", "height", "||", "options", ".", "height", ";", "const", "target", "=", "options", ".", "target", "||", "gl", ".", "TEXTURE_2D", ";", "gl", ".", "bindTexture", "(", "target", ",", "tex", ")", ";", "const", "level", "=", "options", ".", "level", "||", "0", ";", "const", "internalFormat", "=", "options", ".", "internalFormat", "||", "options", ".", "format", "||", "gl", ".", "RGBA", ";", "const", "formatType", "=", "getFormatAndTypeForInternalFormat", "(", "internalFormat", ")", ";", "const", "format", "=", "options", ".", "format", "||", "formatType", ".", "format", ";", "let", "type", ";", "const", "src", "=", "options", ".", "src", ";", "if", "(", "!", "src", ")", "{", "type", "=", "options", ".", "type", "||", "formatType", ".", "type", ";", "}", "else", "if", "(", "isArrayBuffer", "(", "src", ")", "||", "(", "Array", ".", "isArray", "(", "src", ")", "&&", "typeof", "(", "src", "[", "0", "]", ")", "===", "'number'", ")", ")", "{", "type", "=", "options", ".", "type", "||", "getTextureTypeForArrayType", "(", "gl", ",", "src", ",", "formatType", ".", "type", ")", ";", "}", "else", "{", "type", "=", "options", ".", "type", "||", "formatType", ".", "type", ";", "}", "if", "(", "target", "===", "gl", ".", "TEXTURE_CUBE_MAP", ")", "{", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "6", ";", "++", "ii", ")", "{", "gl", ".", "texImage2D", "(", "gl", ".", "TEXTURE_CUBE_MAP_POSITIVE_X", "+", "ii", ",", "level", ",", "internalFormat", ",", "width", ",", "height", ",", "0", ",", "format", ",", "type", ",", "null", ")", ";", "}", "}", "else", "{", "gl", ".", "texImage2D", "(", "target", ",", "level", ",", "internalFormat", ",", "width", ",", "height", ",", "0", ",", "format", ",", "type", ",", "null", ")", ";", "}", "}" ]
Resizes a texture based on the options passed in. Note: This is not a generic resize anything function. It's mostly used by {@link module:twgl.resizeFramebufferInfo} It will use `options.src` if it exists to try to determine a `type` otherwise it will assume `gl.UNSIGNED_BYTE`. No data is provided for the texture. Texture parameters will be set accordingly @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {WebGLTexture} tex the texture to resize @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set. @param {number} [width] the new width. If not passed in will use `options.width` @param {number} [height] the new height. If not passed in will use `options.height` @memberOf module:twgl/textures
[ "Resizes", "a", "texture", "based", "on", "the", "options", "passed", "in", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L1632-L1657
8,832
greggman/twgl.js
src/textures.js
createTextures
function createTextures(gl, textureOptions, callback) { callback = callback || noop; let numDownloading = 0; const errors = []; const textures = {}; const images = {}; function callCallbackIfReady() { if (numDownloading === 0) { setTimeout(function() { callback(errors.length ? errors : undefined, textures, images); }, 0); } } Object.keys(textureOptions).forEach(function(name) { const options = textureOptions[name]; let onLoadFn; if (isAsyncSrc(options.src)) { onLoadFn = function(err, tex, img) { images[name] = img; --numDownloading; if (err) { errors.push(err); } callCallbackIfReady(); }; ++numDownloading; } textures[name] = createTexture(gl, options, onLoadFn); }); // queue the callback if there are no images to download. // We do this because if your code is structured to wait for // images to download but then you comment out all the async // images your code would break. callCallbackIfReady(); return textures; }
javascript
function createTextures(gl, textureOptions, callback) { callback = callback || noop; let numDownloading = 0; const errors = []; const textures = {}; const images = {}; function callCallbackIfReady() { if (numDownloading === 0) { setTimeout(function() { callback(errors.length ? errors : undefined, textures, images); }, 0); } } Object.keys(textureOptions).forEach(function(name) { const options = textureOptions[name]; let onLoadFn; if (isAsyncSrc(options.src)) { onLoadFn = function(err, tex, img) { images[name] = img; --numDownloading; if (err) { errors.push(err); } callCallbackIfReady(); }; ++numDownloading; } textures[name] = createTexture(gl, options, onLoadFn); }); // queue the callback if there are no images to download. // We do this because if your code is structured to wait for // images to download but then you comment out all the async // images your code would break. callCallbackIfReady(); return textures; }
[ "function", "createTextures", "(", "gl", ",", "textureOptions", ",", "callback", ")", "{", "callback", "=", "callback", "||", "noop", ";", "let", "numDownloading", "=", "0", ";", "const", "errors", "=", "[", "]", ";", "const", "textures", "=", "{", "}", ";", "const", "images", "=", "{", "}", ";", "function", "callCallbackIfReady", "(", ")", "{", "if", "(", "numDownloading", "===", "0", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "callback", "(", "errors", ".", "length", "?", "errors", ":", "undefined", ",", "textures", ",", "images", ")", ";", "}", ",", "0", ")", ";", "}", "}", "Object", ".", "keys", "(", "textureOptions", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "const", "options", "=", "textureOptions", "[", "name", "]", ";", "let", "onLoadFn", ";", "if", "(", "isAsyncSrc", "(", "options", ".", "src", ")", ")", "{", "onLoadFn", "=", "function", "(", "err", ",", "tex", ",", "img", ")", "{", "images", "[", "name", "]", "=", "img", ";", "--", "numDownloading", ";", "if", "(", "err", ")", "{", "errors", ".", "push", "(", "err", ")", ";", "}", "callCallbackIfReady", "(", ")", ";", "}", ";", "++", "numDownloading", ";", "}", "textures", "[", "name", "]", "=", "createTexture", "(", "gl", ",", "options", ",", "onLoadFn", ")", ";", "}", ")", ";", "// queue the callback if there are no images to download.", "// We do this because if your code is structured to wait for", "// images to download but then you comment out all the async", "// images your code would break.", "callCallbackIfReady", "(", ")", ";", "return", "textures", ";", "}" ]
Creates a bunch of textures based on the passed in options. Example: const textures = twgl.createTextures(gl, { // a power of 2 image hftIcon: { src: "images/hft-icon-16.png", mag: gl.NEAREST }, // a non-power of 2 image clover: { src: "images/clover.jpg" }, // From a canvas fromCanvas: { src: ctx.canvas }, // A cubemap from 6 images yokohama: { target: gl.TEXTURE_CUBE_MAP, src: [ 'images/yokohama/posx.jpg', 'images/yokohama/negx.jpg', 'images/yokohama/posy.jpg', 'images/yokohama/negy.jpg', 'images/yokohama/posz.jpg', 'images/yokohama/negz.jpg', ], }, // A cubemap from 1 image (can be 1x6, 2x3, 3x2, 6x1) goldengate: { target: gl.TEXTURE_CUBE_MAP, src: 'images/goldengate.jpg', }, // A 2x2 pixel texture from a JavaScript array checker: { mag: gl.NEAREST, min: gl.LINEAR, src: [ 255,255,255,255, 192,192,192,255, 192,192,192,255, 255,255,255,255, ], }, // a 1x2 pixel texture from a typed array. stripe: { mag: gl.NEAREST, min: gl.LINEAR, format: gl.LUMINANCE, src: new Uint8Array([ 255, 128, 255, 128, 255, 128, 255, 128, ]), width: 1, }, }); Now * `textures.hftIcon` will be a 2d texture * `textures.clover` will be a 2d texture * `textures.fromCanvas` will be a 2d texture * `textures.yohohama` will be a cubemap texture * `textures.goldengate` will be a cubemap texture * `textures.checker` will be a 2d texture * `textures.stripe` will be a 2d texture @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {Object.<string,module:twgl.TextureOptions>} options A object of TextureOptions one per texture. @param {module:twgl.TexturesReadyCallback} [callback] A callback called when all textures have been downloaded. @return {Object.<string,WebGLTexture>} the created textures by name @memberOf module:twgl/textures
[ "Creates", "a", "bunch", "of", "textures", "based", "on", "the", "passed", "in", "options", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/textures.js#L1747-L1786
8,833
greggman/twgl.js
src/framebuffers.js
resizeFramebufferInfo
function resizeFramebufferInfo(gl, framebufferInfo, attachments, width, height) { width = width || gl.drawingBufferWidth; height = height || gl.drawingBufferHeight; framebufferInfo.width = width; framebufferInfo.height = height; attachments = attachments || defaultAttachments; attachments.forEach(function(attachmentOptions, ndx) { const attachment = framebufferInfo.attachments[ndx]; const format = attachmentOptions.format; if (helper.isRenderbuffer(gl, attachment)) { gl.bindRenderbuffer(gl.RENDERBUFFER, attachment); gl.renderbufferStorage(gl.RENDERBUFFER, format, width, height); } else if (helper.isTexture(gl, attachment)) { textures.resizeTexture(gl, attachment, attachmentOptions, width, height); } else { throw "unknown attachment type"; } }); }
javascript
function resizeFramebufferInfo(gl, framebufferInfo, attachments, width, height) { width = width || gl.drawingBufferWidth; height = height || gl.drawingBufferHeight; framebufferInfo.width = width; framebufferInfo.height = height; attachments = attachments || defaultAttachments; attachments.forEach(function(attachmentOptions, ndx) { const attachment = framebufferInfo.attachments[ndx]; const format = attachmentOptions.format; if (helper.isRenderbuffer(gl, attachment)) { gl.bindRenderbuffer(gl.RENDERBUFFER, attachment); gl.renderbufferStorage(gl.RENDERBUFFER, format, width, height); } else if (helper.isTexture(gl, attachment)) { textures.resizeTexture(gl, attachment, attachmentOptions, width, height); } else { throw "unknown attachment type"; } }); }
[ "function", "resizeFramebufferInfo", "(", "gl", ",", "framebufferInfo", ",", "attachments", ",", "width", ",", "height", ")", "{", "width", "=", "width", "||", "gl", ".", "drawingBufferWidth", ";", "height", "=", "height", "||", "gl", ".", "drawingBufferHeight", ";", "framebufferInfo", ".", "width", "=", "width", ";", "framebufferInfo", ".", "height", "=", "height", ";", "attachments", "=", "attachments", "||", "defaultAttachments", ";", "attachments", ".", "forEach", "(", "function", "(", "attachmentOptions", ",", "ndx", ")", "{", "const", "attachment", "=", "framebufferInfo", ".", "attachments", "[", "ndx", "]", ";", "const", "format", "=", "attachmentOptions", ".", "format", ";", "if", "(", "helper", ".", "isRenderbuffer", "(", "gl", ",", "attachment", ")", ")", "{", "gl", ".", "bindRenderbuffer", "(", "gl", ".", "RENDERBUFFER", ",", "attachment", ")", ";", "gl", ".", "renderbufferStorage", "(", "gl", ".", "RENDERBUFFER", ",", "format", ",", "width", ",", "height", ")", ";", "}", "else", "if", "(", "helper", ".", "isTexture", "(", "gl", ",", "attachment", ")", ")", "{", "textures", ".", "resizeTexture", "(", "gl", ",", "attachment", ",", "attachmentOptions", ",", "width", ",", "height", ")", ";", "}", "else", "{", "throw", "\"unknown attachment type\"", ";", "}", "}", ")", ";", "}" ]
Resizes the attachments of a framebuffer. You need to pass in the same `attachments` as you passed in {@link module:twgl.createFramebufferInfo} because TWGL has no idea the format/type of each attachment. The simplest usage // create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer const fbi = twgl.createFramebufferInfo(gl); ... function render() { if (twgl.resizeCanvasToDisplaySize(gl.canvas)) { // resize the attachments twgl.resizeFramebufferInfo(gl, fbi); } More complex usage // create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer const attachments = [ { format: RGB565, mag: NEAREST }, { format: STENCIL_INDEX8 }, ] const fbi = twgl.createFramebufferInfo(gl, attachments); ... function render() { if (twgl.resizeCanvasToDisplaySize(gl.canvas)) { // resize the attachments to match twgl.resizeFramebufferInfo(gl, fbi, attachments); } @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {module:twgl.FramebufferInfo} framebufferInfo a framebufferInfo as returned from {@link module:twgl.createFramebufferInfo}. @param {module:twgl.AttachmentOptions[]} [attachments] the same attachments options as passed to {@link module:twgl.createFramebufferInfo}. @param {number} [width] the width for the attachments. Default = size of drawingBuffer @param {number} [height] the height for the attachments. Defautt = size of drawingBuffer @memberOf module:twgl/framebuffers
[ "Resizes", "the", "attachments", "of", "a", "framebuffer", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/framebuffers.js#L274-L292
8,834
greggman/twgl.js
src/framebuffers.js
bindFramebufferInfo
function bindFramebufferInfo(gl, framebufferInfo, target) { target = target || gl.FRAMEBUFFER; if (framebufferInfo) { gl.bindFramebuffer(target, framebufferInfo.framebuffer); gl.viewport(0, 0, framebufferInfo.width, framebufferInfo.height); } else { gl.bindFramebuffer(target, null); gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); } }
javascript
function bindFramebufferInfo(gl, framebufferInfo, target) { target = target || gl.FRAMEBUFFER; if (framebufferInfo) { gl.bindFramebuffer(target, framebufferInfo.framebuffer); gl.viewport(0, 0, framebufferInfo.width, framebufferInfo.height); } else { gl.bindFramebuffer(target, null); gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); } }
[ "function", "bindFramebufferInfo", "(", "gl", ",", "framebufferInfo", ",", "target", ")", "{", "target", "=", "target", "||", "gl", ".", "FRAMEBUFFER", ";", "if", "(", "framebufferInfo", ")", "{", "gl", ".", "bindFramebuffer", "(", "target", ",", "framebufferInfo", ".", "framebuffer", ")", ";", "gl", ".", "viewport", "(", "0", ",", "0", ",", "framebufferInfo", ".", "width", ",", "framebufferInfo", ".", "height", ")", ";", "}", "else", "{", "gl", ".", "bindFramebuffer", "(", "target", ",", "null", ")", ";", "gl", ".", "viewport", "(", "0", ",", "0", ",", "gl", ".", "drawingBufferWidth", ",", "gl", ".", "drawingBufferHeight", ")", ";", "}", "}" ]
Binds a framebuffer This function pretty much soley exists because I spent hours trying to figure out why something I wrote wasn't working only to realize I forget to set the viewport dimensions. My hope is this function will fix that. It is effectively the same as gl.bindFramebuffer(gl.FRAMEBUFFER, someFramebufferInfo.framebuffer); gl.viewport(0, 0, someFramebufferInfo.width, someFramebufferInfo.height); @param {WebGLRenderingContext} gl the WebGLRenderingContext @param {module:twgl.FramebufferInfo} [framebufferInfo] a framebufferInfo as returned from {@link module:twgl.createFramebufferInfo}. If not passed will bind the canvas. @param {number} [target] The target. If not passed `gl.FRAMEBUFFER` will be used. @memberOf module:twgl/framebuffers
[ "Binds", "a", "framebuffer" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/framebuffers.js#L314-L323
8,835
greggman/twgl.js
src/v3.js
create
function create(x, y, z) { const dst = new VecType(3); if (x) { dst[0] = x; } if (y) { dst[1] = y; } if (z) { dst[2] = z; } return dst; }
javascript
function create(x, y, z) { const dst = new VecType(3); if (x) { dst[0] = x; } if (y) { dst[1] = y; } if (z) { dst[2] = z; } return dst; }
[ "function", "create", "(", "x", ",", "y", ",", "z", ")", "{", "const", "dst", "=", "new", "VecType", "(", "3", ")", ";", "if", "(", "x", ")", "{", "dst", "[", "0", "]", "=", "x", ";", "}", "if", "(", "y", ")", "{", "dst", "[", "1", "]", "=", "y", ";", "}", "if", "(", "z", ")", "{", "dst", "[", "2", "]", "=", "z", ";", "}", "return", "dst", ";", "}" ]
Creates a vec3; may be called with x, y, z to set initial values. @return {module:twgl/v3.Vec3} the created vector @memberOf module:twgl/v3
[ "Creates", "a", "vec3", ";", "may", "be", "called", "with", "x", "y", "z", "to", "set", "initial", "values", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/v3.js#L74-L86
8,836
greggman/twgl.js
src/v3.js
add
function add(a, b, dst) { dst = dst || new VecType(3); dst[0] = a[0] + b[0]; dst[1] = a[1] + b[1]; dst[2] = a[2] + b[2]; return dst; }
javascript
function add(a, b, dst) { dst = dst || new VecType(3); dst[0] = a[0] + b[0]; dst[1] = a[1] + b[1]; dst[2] = a[2] + b[2]; return dst; }
[ "function", "add", "(", "a", ",", "b", ",", "dst", ")", "{", "dst", "=", "dst", "||", "new", "VecType", "(", "3", ")", ";", "dst", "[", "0", "]", "=", "a", "[", "0", "]", "+", "b", "[", "0", "]", ";", "dst", "[", "1", "]", "=", "a", "[", "1", "]", "+", "b", "[", "1", "]", ";", "dst", "[", "2", "]", "=", "a", "[", "2", "]", "+", "b", "[", "2", "]", ";", "return", "dst", ";", "}" ]
Adds two vectors; assumes a and b have the same dimension. @param {module:twgl/v3.Vec3} a Operand vector. @param {module:twgl/v3.Vec3} b Operand vector. @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.. @return {module:twgl/v3.Vec3} the created vector @memberOf module:twgl/v3
[ "Adds", "two", "vectors", ";", "assumes", "a", "and", "b", "have", "the", "same", "dimension", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/v3.js#L96-L104
8,837
greggman/twgl.js
src/v3.js
subtract
function subtract(a, b, dst) { dst = dst || new VecType(3); dst[0] = a[0] - b[0]; dst[1] = a[1] - b[1]; dst[2] = a[2] - b[2]; return dst; }
javascript
function subtract(a, b, dst) { dst = dst || new VecType(3); dst[0] = a[0] - b[0]; dst[1] = a[1] - b[1]; dst[2] = a[2] - b[2]; return dst; }
[ "function", "subtract", "(", "a", ",", "b", ",", "dst", ")", "{", "dst", "=", "dst", "||", "new", "VecType", "(", "3", ")", ";", "dst", "[", "0", "]", "=", "a", "[", "0", "]", "-", "b", "[", "0", "]", ";", "dst", "[", "1", "]", "=", "a", "[", "1", "]", "-", "b", "[", "1", "]", ";", "dst", "[", "2", "]", "=", "a", "[", "2", "]", "-", "b", "[", "2", "]", ";", "return", "dst", ";", "}" ]
Subtracts two vectors. @param {module:twgl/v3.Vec3} a Operand vector. @param {module:twgl/v3.Vec3} b Operand vector. @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.. @return {module:twgl/v3.Vec3} the created vector @memberOf module:twgl/v3
[ "Subtracts", "two", "vectors", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/v3.js#L114-L122
8,838
greggman/twgl.js
src/v3.js
mulScalar
function mulScalar(v, k, dst) { dst = dst || new VecType(3); dst[0] = v[0] * k; dst[1] = v[1] * k; dst[2] = v[2] * k; return dst; }
javascript
function mulScalar(v, k, dst) { dst = dst || new VecType(3); dst[0] = v[0] * k; dst[1] = v[1] * k; dst[2] = v[2] * k; return dst; }
[ "function", "mulScalar", "(", "v", ",", "k", ",", "dst", ")", "{", "dst", "=", "dst", "||", "new", "VecType", "(", "3", ")", ";", "dst", "[", "0", "]", "=", "v", "[", "0", "]", "*", "k", ";", "dst", "[", "1", "]", "=", "v", "[", "1", "]", "*", "k", ";", "dst", "[", "2", "]", "=", "v", "[", "2", "]", "*", "k", ";", "return", "dst", ";", "}" ]
Mutiplies a vector by a scalar. @param {module:twgl/v3.Vec3} v The vector. @param {number} k The scalar. @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.. @return {module:twgl/v3.Vec3} dst. @memberOf module:twgl/v3
[ "Mutiplies", "a", "vector", "by", "a", "scalar", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/v3.js#L214-L222
8,839
greggman/twgl.js
src/v3.js
divScalar
function divScalar(v, k, dst) { dst = dst || new VecType(3); dst[0] = v[0] / k; dst[1] = v[1] / k; dst[2] = v[2] / k; return dst; }
javascript
function divScalar(v, k, dst) { dst = dst || new VecType(3); dst[0] = v[0] / k; dst[1] = v[1] / k; dst[2] = v[2] / k; return dst; }
[ "function", "divScalar", "(", "v", ",", "k", ",", "dst", ")", "{", "dst", "=", "dst", "||", "new", "VecType", "(", "3", ")", ";", "dst", "[", "0", "]", "=", "v", "[", "0", "]", "/", "k", ";", "dst", "[", "1", "]", "=", "v", "[", "1", "]", "/", "k", ";", "dst", "[", "2", "]", "=", "v", "[", "2", "]", "/", "k", ";", "return", "dst", ";", "}" ]
Divides a vector by a scalar. @param {module:twgl/v3.Vec3} v The vector. @param {number} k The scalar. @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.. @return {module:twgl/v3.Vec3} dst. @memberOf module:twgl/v3
[ "Divides", "a", "vector", "by", "a", "scalar", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/v3.js#L232-L240
8,840
greggman/twgl.js
src/v3.js
cross
function cross(a, b, dst) { dst = dst || new VecType(3); const t1 = a[2] * b[0] - a[0] * b[2]; const t2 = a[0] * b[1] - a[1] * b[0]; dst[0] = a[1] * b[2] - a[2] * b[1]; dst[1] = t1; dst[2] = t2; return dst; }
javascript
function cross(a, b, dst) { dst = dst || new VecType(3); const t1 = a[2] * b[0] - a[0] * b[2]; const t2 = a[0] * b[1] - a[1] * b[0]; dst[0] = a[1] * b[2] - a[2] * b[1]; dst[1] = t1; dst[2] = t2; return dst; }
[ "function", "cross", "(", "a", ",", "b", ",", "dst", ")", "{", "dst", "=", "dst", "||", "new", "VecType", "(", "3", ")", ";", "const", "t1", "=", "a", "[", "2", "]", "*", "b", "[", "0", "]", "-", "a", "[", "0", "]", "*", "b", "[", "2", "]", ";", "const", "t2", "=", "a", "[", "0", "]", "*", "b", "[", "1", "]", "-", "a", "[", "1", "]", "*", "b", "[", "0", "]", ";", "dst", "[", "0", "]", "=", "a", "[", "1", "]", "*", "b", "[", "2", "]", "-", "a", "[", "2", "]", "*", "b", "[", "1", "]", ";", "dst", "[", "1", "]", "=", "t1", ";", "dst", "[", "2", "]", "=", "t2", ";", "return", "dst", ";", "}" ]
Computes the cross product of two vectors; assumes both vectors have three entries. @param {module:twgl/v3.Vec3} a Operand vector. @param {module:twgl/v3.Vec3} b Operand vector. @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.. @return {module:twgl/v3.Vec3} The vector a cross b. @memberOf module:twgl/v3
[ "Computes", "the", "cross", "product", "of", "two", "vectors", ";", "assumes", "both", "vectors", "have", "three", "entries", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/v3.js#L251-L261
8,841
greggman/twgl.js
src/v3.js
normalize
function normalize(a, dst) { dst = dst || new VecType(3); const lenSq = a[0] * a[0] + a[1] * a[1] + a[2] * a[2]; const len = Math.sqrt(lenSq); if (len > 0.00001) { dst[0] = a[0] / len; dst[1] = a[1] / len; dst[2] = a[2] / len; } else { dst[0] = 0; dst[1] = 0; dst[2] = 0; } return dst; }
javascript
function normalize(a, dst) { dst = dst || new VecType(3); const lenSq = a[0] * a[0] + a[1] * a[1] + a[2] * a[2]; const len = Math.sqrt(lenSq); if (len > 0.00001) { dst[0] = a[0] / len; dst[1] = a[1] / len; dst[2] = a[2] / len; } else { dst[0] = 0; dst[1] = 0; dst[2] = 0; } return dst; }
[ "function", "normalize", "(", "a", ",", "dst", ")", "{", "dst", "=", "dst", "||", "new", "VecType", "(", "3", ")", ";", "const", "lenSq", "=", "a", "[", "0", "]", "*", "a", "[", "0", "]", "+", "a", "[", "1", "]", "*", "a", "[", "1", "]", "+", "a", "[", "2", "]", "*", "a", "[", "2", "]", ";", "const", "len", "=", "Math", ".", "sqrt", "(", "lenSq", ")", ";", "if", "(", "len", ">", "0.00001", ")", "{", "dst", "[", "0", "]", "=", "a", "[", "0", "]", "/", "len", ";", "dst", "[", "1", "]", "=", "a", "[", "1", "]", "/", "len", ";", "dst", "[", "2", "]", "=", "a", "[", "2", "]", "/", "len", ";", "}", "else", "{", "dst", "[", "0", "]", "=", "0", ";", "dst", "[", "1", "]", "=", "0", ";", "dst", "[", "2", "]", "=", "0", ";", "}", "return", "dst", ";", "}" ]
Divides a vector by its Euclidean length and returns the quotient. @param {module:twgl/v3.Vec3} a The vector. @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.. @return {module:twgl/v3.Vec3} The normalized vector. @memberOf module:twgl/v3
[ "Divides", "a", "vector", "by", "its", "Euclidean", "length", "and", "returns", "the", "quotient", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/v3.js#L330-L346
8,842
greggman/twgl.js
src/v3.js
negate
function negate(v, dst) { dst = dst || new VecType(3); dst[0] = -v[0]; dst[1] = -v[1]; dst[2] = -v[2]; return dst; }
javascript
function negate(v, dst) { dst = dst || new VecType(3); dst[0] = -v[0]; dst[1] = -v[1]; dst[2] = -v[2]; return dst; }
[ "function", "negate", "(", "v", ",", "dst", ")", "{", "dst", "=", "dst", "||", "new", "VecType", "(", "3", ")", ";", "dst", "[", "0", "]", "=", "-", "v", "[", "0", "]", ";", "dst", "[", "1", "]", "=", "-", "v", "[", "1", "]", ";", "dst", "[", "2", "]", "=", "-", "v", "[", "2", "]", ";", "return", "dst", ";", "}" ]
Negates a vector. @param {module:twgl/v3.Vec3} v The vector. @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.. @return {module:twgl/v3.Vec3} -v. @memberOf module:twgl/v3
[ "Negates", "a", "vector", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/v3.js#L355-L363
8,843
greggman/twgl.js
src/v3.js
copy
function copy(v, dst) { dst = dst || new VecType(3); dst[0] = v[0]; dst[1] = v[1]; dst[2] = v[2]; return dst; }
javascript
function copy(v, dst) { dst = dst || new VecType(3); dst[0] = v[0]; dst[1] = v[1]; dst[2] = v[2]; return dst; }
[ "function", "copy", "(", "v", ",", "dst", ")", "{", "dst", "=", "dst", "||", "new", "VecType", "(", "3", ")", ";", "dst", "[", "0", "]", "=", "v", "[", "0", "]", ";", "dst", "[", "1", "]", "=", "v", "[", "1", "]", ";", "dst", "[", "2", "]", "=", "v", "[", "2", "]", ";", "return", "dst", ";", "}" ]
Copies a vector. @param {module:twgl/v3.Vec3} v The vector. @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.. @return {module:twgl/v3.Vec3} A copy of v. @memberOf module:twgl/v3
[ "Copies", "a", "vector", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/v3.js#L372-L380
8,844
greggman/twgl.js
src/primitives.js
deindexVertices
function deindexVertices(vertices) { const indices = vertices.indices; const newVertices = {}; const numElements = indices.length; function expandToUnindexed(channel) { const srcBuffer = vertices[channel]; const numComponents = srcBuffer.numComponents; const dstBuffer = createAugmentedTypedArray(numComponents, numElements, srcBuffer.constructor); for (let ii = 0; ii < numElements; ++ii) { const ndx = indices[ii]; const offset = ndx * numComponents; for (let jj = 0; jj < numComponents; ++jj) { dstBuffer.push(srcBuffer[offset + jj]); } } newVertices[channel] = dstBuffer; } Object.keys(vertices).filter(allButIndices).forEach(expandToUnindexed); return newVertices; }
javascript
function deindexVertices(vertices) { const indices = vertices.indices; const newVertices = {}; const numElements = indices.length; function expandToUnindexed(channel) { const srcBuffer = vertices[channel]; const numComponents = srcBuffer.numComponents; const dstBuffer = createAugmentedTypedArray(numComponents, numElements, srcBuffer.constructor); for (let ii = 0; ii < numElements; ++ii) { const ndx = indices[ii]; const offset = ndx * numComponents; for (let jj = 0; jj < numComponents; ++jj) { dstBuffer.push(srcBuffer[offset + jj]); } } newVertices[channel] = dstBuffer; } Object.keys(vertices).filter(allButIndices).forEach(expandToUnindexed); return newVertices; }
[ "function", "deindexVertices", "(", "vertices", ")", "{", "const", "indices", "=", "vertices", ".", "indices", ";", "const", "newVertices", "=", "{", "}", ";", "const", "numElements", "=", "indices", ".", "length", ";", "function", "expandToUnindexed", "(", "channel", ")", "{", "const", "srcBuffer", "=", "vertices", "[", "channel", "]", ";", "const", "numComponents", "=", "srcBuffer", ".", "numComponents", ";", "const", "dstBuffer", "=", "createAugmentedTypedArray", "(", "numComponents", ",", "numElements", ",", "srcBuffer", ".", "constructor", ")", ";", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "numElements", ";", "++", "ii", ")", "{", "const", "ndx", "=", "indices", "[", "ii", "]", ";", "const", "offset", "=", "ndx", "*", "numComponents", ";", "for", "(", "let", "jj", "=", "0", ";", "jj", "<", "numComponents", ";", "++", "jj", ")", "{", "dstBuffer", ".", "push", "(", "srcBuffer", "[", "offset", "+", "jj", "]", ")", ";", "}", "}", "newVertices", "[", "channel", "]", "=", "dstBuffer", ";", "}", "Object", ".", "keys", "(", "vertices", ")", ".", "filter", "(", "allButIndices", ")", ".", "forEach", "(", "expandToUnindexed", ")", ";", "return", "newVertices", ";", "}" ]
Given indexed vertices creates a new set of vertices unindexed by expanding the indexed vertices. @param {Object.<string, TypedArray>} vertices The indexed vertices to deindex @return {Object.<string, TypedArray>} The deindexed vertices @memberOf module:twgl/primitives
[ "Given", "indexed", "vertices", "creates", "a", "new", "set", "of", "vertices", "unindexed", "by", "expanding", "the", "indexed", "vertices", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L139-L161
8,845
greggman/twgl.js
src/primitives.js
flattenNormals
function flattenNormals(vertices) { if (vertices.indices) { throw "can't flatten normals of indexed vertices. deindex them first"; } const normals = vertices.normal; const numNormals = normals.length; for (let ii = 0; ii < numNormals; ii += 9) { // pull out the 3 normals for this triangle const nax = normals[ii + 0]; const nay = normals[ii + 1]; const naz = normals[ii + 2]; const nbx = normals[ii + 3]; const nby = normals[ii + 4]; const nbz = normals[ii + 5]; const ncx = normals[ii + 6]; const ncy = normals[ii + 7]; const ncz = normals[ii + 8]; // add them let nx = nax + nbx + ncx; let ny = nay + nby + ncy; let nz = naz + nbz + ncz; // normalize them const length = Math.sqrt(nx * nx + ny * ny + nz * nz); nx /= length; ny /= length; nz /= length; // copy them back in normals[ii + 0] = nx; normals[ii + 1] = ny; normals[ii + 2] = nz; normals[ii + 3] = nx; normals[ii + 4] = ny; normals[ii + 5] = nz; normals[ii + 6] = nx; normals[ii + 7] = ny; normals[ii + 8] = nz; } return vertices; }
javascript
function flattenNormals(vertices) { if (vertices.indices) { throw "can't flatten normals of indexed vertices. deindex them first"; } const normals = vertices.normal; const numNormals = normals.length; for (let ii = 0; ii < numNormals; ii += 9) { // pull out the 3 normals for this triangle const nax = normals[ii + 0]; const nay = normals[ii + 1]; const naz = normals[ii + 2]; const nbx = normals[ii + 3]; const nby = normals[ii + 4]; const nbz = normals[ii + 5]; const ncx = normals[ii + 6]; const ncy = normals[ii + 7]; const ncz = normals[ii + 8]; // add them let nx = nax + nbx + ncx; let ny = nay + nby + ncy; let nz = naz + nbz + ncz; // normalize them const length = Math.sqrt(nx * nx + ny * ny + nz * nz); nx /= length; ny /= length; nz /= length; // copy them back in normals[ii + 0] = nx; normals[ii + 1] = ny; normals[ii + 2] = nz; normals[ii + 3] = nx; normals[ii + 4] = ny; normals[ii + 5] = nz; normals[ii + 6] = nx; normals[ii + 7] = ny; normals[ii + 8] = nz; } return vertices; }
[ "function", "flattenNormals", "(", "vertices", ")", "{", "if", "(", "vertices", ".", "indices", ")", "{", "throw", "\"can't flatten normals of indexed vertices. deindex them first\"", ";", "}", "const", "normals", "=", "vertices", ".", "normal", ";", "const", "numNormals", "=", "normals", ".", "length", ";", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "numNormals", ";", "ii", "+=", "9", ")", "{", "// pull out the 3 normals for this triangle", "const", "nax", "=", "normals", "[", "ii", "+", "0", "]", ";", "const", "nay", "=", "normals", "[", "ii", "+", "1", "]", ";", "const", "naz", "=", "normals", "[", "ii", "+", "2", "]", ";", "const", "nbx", "=", "normals", "[", "ii", "+", "3", "]", ";", "const", "nby", "=", "normals", "[", "ii", "+", "4", "]", ";", "const", "nbz", "=", "normals", "[", "ii", "+", "5", "]", ";", "const", "ncx", "=", "normals", "[", "ii", "+", "6", "]", ";", "const", "ncy", "=", "normals", "[", "ii", "+", "7", "]", ";", "const", "ncz", "=", "normals", "[", "ii", "+", "8", "]", ";", "// add them", "let", "nx", "=", "nax", "+", "nbx", "+", "ncx", ";", "let", "ny", "=", "nay", "+", "nby", "+", "ncy", ";", "let", "nz", "=", "naz", "+", "nbz", "+", "ncz", ";", "// normalize them", "const", "length", "=", "Math", ".", "sqrt", "(", "nx", "*", "nx", "+", "ny", "*", "ny", "+", "nz", "*", "nz", ")", ";", "nx", "/=", "length", ";", "ny", "/=", "length", ";", "nz", "/=", "length", ";", "// copy them back in", "normals", "[", "ii", "+", "0", "]", "=", "nx", ";", "normals", "[", "ii", "+", "1", "]", "=", "ny", ";", "normals", "[", "ii", "+", "2", "]", "=", "nz", ";", "normals", "[", "ii", "+", "3", "]", "=", "nx", ";", "normals", "[", "ii", "+", "4", "]", "=", "ny", ";", "normals", "[", "ii", "+", "5", "]", "=", "nz", ";", "normals", "[", "ii", "+", "6", "]", "=", "nx", ";", "normals", "[", "ii", "+", "7", "]", "=", "ny", ";", "normals", "[", "ii", "+", "8", "]", "=", "nz", ";", "}", "return", "vertices", ";", "}" ]
flattens the normals of deindexed vertices in place. @param {Object.<string, TypedArray>} vertices The deindexed vertices who's normals to flatten @return {Object.<string, TypedArray>} The flattened vertices (same as was passed in) @memberOf module:twgl/primitives
[ "flattens", "the", "normals", "of", "deindexed", "vertices", "in", "place", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L169-L217
8,846
greggman/twgl.js
src/primitives.js
reorientNormals
function reorientNormals(array, matrix) { applyFuncToV3Array(array, m4.inverse(matrix), transformNormal); return array; }
javascript
function reorientNormals(array, matrix) { applyFuncToV3Array(array, m4.inverse(matrix), transformNormal); return array; }
[ "function", "reorientNormals", "(", "array", ",", "matrix", ")", "{", "applyFuncToV3Array", "(", "array", ",", "m4", ".", "inverse", "(", "matrix", ")", ",", "transformNormal", ")", ";", "return", "array", ";", "}" ]
Reorients normals by the inverse-transpose of the given matrix.. @param {(number[]|TypedArray)} array The array. Assumes value floats per element. @param {module:twgl/m4.Mat4} matrix A matrix to multiply by. @return {(number[]|TypedArray)} the same array that was passed in @memberOf module:twgl/primitives
[ "Reorients", "normals", "by", "the", "inverse", "-", "transpose", "of", "the", "given", "matrix", ".." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L263-L266
8,847
greggman/twgl.js
src/primitives.js
createXYQuadVertices
function createXYQuadVertices(size, xOffset, yOffset) { size = size || 2; xOffset = xOffset || 0; yOffset = yOffset || 0; size *= 0.5; return { position: { numComponents: 2, data: [ xOffset + -1 * size, yOffset + -1 * size, xOffset + 1 * size, yOffset + -1 * size, xOffset + -1 * size, yOffset + 1 * size, xOffset + 1 * size, yOffset + 1 * size, ], }, normal: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ], texcoord: [ 0, 0, 1, 0, 0, 1, 1, 1, ], indices: [ 0, 1, 2, 2, 1, 3 ], }; }
javascript
function createXYQuadVertices(size, xOffset, yOffset) { size = size || 2; xOffset = xOffset || 0; yOffset = yOffset || 0; size *= 0.5; return { position: { numComponents: 2, data: [ xOffset + -1 * size, yOffset + -1 * size, xOffset + 1 * size, yOffset + -1 * size, xOffset + -1 * size, yOffset + 1 * size, xOffset + 1 * size, yOffset + 1 * size, ], }, normal: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ], texcoord: [ 0, 0, 1, 0, 0, 1, 1, 1, ], indices: [ 0, 1, 2, 2, 1, 3 ], }; }
[ "function", "createXYQuadVertices", "(", "size", ",", "xOffset", ",", "yOffset", ")", "{", "size", "=", "size", "||", "2", ";", "xOffset", "=", "xOffset", "||", "0", ";", "yOffset", "=", "yOffset", "||", "0", ";", "size", "*=", "0.5", ";", "return", "{", "position", ":", "{", "numComponents", ":", "2", ",", "data", ":", "[", "xOffset", "+", "-", "1", "*", "size", ",", "yOffset", "+", "-", "1", "*", "size", ",", "xOffset", "+", "1", "*", "size", ",", "yOffset", "+", "-", "1", "*", "size", ",", "xOffset", "+", "-", "1", "*", "size", ",", "yOffset", "+", "1", "*", "size", ",", "xOffset", "+", "1", "*", "size", ",", "yOffset", "+", "1", "*", "size", ",", "]", ",", "}", ",", "normal", ":", "[", "0", ",", "0", ",", "1", ",", "0", ",", "0", ",", "1", ",", "0", ",", "0", ",", "1", ",", "0", ",", "0", ",", "1", ",", "]", ",", "texcoord", ":", "[", "0", ",", "0", ",", "1", ",", "0", ",", "0", ",", "1", ",", "1", ",", "1", ",", "]", ",", "indices", ":", "[", "0", ",", "1", ",", "2", ",", "2", ",", "1", ",", "3", "]", ",", "}", ";", "}" ]
Creates XY quad Buffers The default with no parameters will return a 2x2 quad with values from -1 to +1. If you want a unit quad with that goes from 0 to 1 you'd call it with twgl.primitives.createXYQuadBufferInfo(gl, 1, 0.5, 0.5); If you want a unit quad centered above 0,0 you'd call it with twgl.primitives.createXYQuadBufferInfo(gl, 1, 0, 0.5); @param {WebGLRenderingContext} gl The WebGLRenderingContext. @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1 @param {number} [xOffset] the amount to offset the quad in X @param {number} [yOffset] the amount to offset the quad in Y @return {module:twgl.BufferInfo} the created XY Quad buffers @memberOf module:twgl/primitives @function createXYQuadBuffers Creates XY quad vertices The default with no parameters will return a 2x2 quad with values from -1 to +1. If you want a unit quad with that goes from 0 to 1 you'd call it with twgl.primitives.createXYQuadVertices(1, 0.5, 0.5); If you want a unit quad centered above 0,0 you'd call it with twgl.primitives.createXYQuadVertices(1, 0, 0.5); @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1 @param {number} [xOffset] the amount to offset the quad in X @param {number} [yOffset] the amount to offset the quad in Y @return {Object.<string, TypedArray>} the created XY Quad vertices @memberOf module:twgl/primitives
[ "Creates", "XY", "quad", "Buffers" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L369-L398
8,848
greggman/twgl.js
src/primitives.js
createPlaneVertices
function createPlaneVertices( width, depth, subdivisionsWidth, subdivisionsDepth, matrix) { width = width || 1; depth = depth || 1; subdivisionsWidth = subdivisionsWidth || 1; subdivisionsDepth = subdivisionsDepth || 1; matrix = matrix || m4.identity(); const numVertices = (subdivisionsWidth + 1) * (subdivisionsDepth + 1); const positions = createAugmentedTypedArray(3, numVertices); const normals = createAugmentedTypedArray(3, numVertices); const texcoords = createAugmentedTypedArray(2, numVertices); for (let z = 0; z <= subdivisionsDepth; z++) { for (let x = 0; x <= subdivisionsWidth; x++) { const u = x / subdivisionsWidth; const v = z / subdivisionsDepth; positions.push( width * u - width * 0.5, 0, depth * v - depth * 0.5); normals.push(0, 1, 0); texcoords.push(u, v); } } const numVertsAcross = subdivisionsWidth + 1; const indices = createAugmentedTypedArray( 3, subdivisionsWidth * subdivisionsDepth * 2, Uint16Array); for (let z = 0; z < subdivisionsDepth; z++) { // eslint-disable-line for (let x = 0; x < subdivisionsWidth; x++) { // eslint-disable-line // Make triangle 1 of quad. indices.push( (z + 0) * numVertsAcross + x, (z + 1) * numVertsAcross + x, (z + 0) * numVertsAcross + x + 1); // Make triangle 2 of quad. indices.push( (z + 1) * numVertsAcross + x, (z + 1) * numVertsAcross + x + 1, (z + 0) * numVertsAcross + x + 1); } } const arrays = reorientVertices({ position: positions, normal: normals, texcoord: texcoords, indices: indices, }, matrix); return arrays; }
javascript
function createPlaneVertices( width, depth, subdivisionsWidth, subdivisionsDepth, matrix) { width = width || 1; depth = depth || 1; subdivisionsWidth = subdivisionsWidth || 1; subdivisionsDepth = subdivisionsDepth || 1; matrix = matrix || m4.identity(); const numVertices = (subdivisionsWidth + 1) * (subdivisionsDepth + 1); const positions = createAugmentedTypedArray(3, numVertices); const normals = createAugmentedTypedArray(3, numVertices); const texcoords = createAugmentedTypedArray(2, numVertices); for (let z = 0; z <= subdivisionsDepth; z++) { for (let x = 0; x <= subdivisionsWidth; x++) { const u = x / subdivisionsWidth; const v = z / subdivisionsDepth; positions.push( width * u - width * 0.5, 0, depth * v - depth * 0.5); normals.push(0, 1, 0); texcoords.push(u, v); } } const numVertsAcross = subdivisionsWidth + 1; const indices = createAugmentedTypedArray( 3, subdivisionsWidth * subdivisionsDepth * 2, Uint16Array); for (let z = 0; z < subdivisionsDepth; z++) { // eslint-disable-line for (let x = 0; x < subdivisionsWidth; x++) { // eslint-disable-line // Make triangle 1 of quad. indices.push( (z + 0) * numVertsAcross + x, (z + 1) * numVertsAcross + x, (z + 0) * numVertsAcross + x + 1); // Make triangle 2 of quad. indices.push( (z + 1) * numVertsAcross + x, (z + 1) * numVertsAcross + x + 1, (z + 0) * numVertsAcross + x + 1); } } const arrays = reorientVertices({ position: positions, normal: normals, texcoord: texcoords, indices: indices, }, matrix); return arrays; }
[ "function", "createPlaneVertices", "(", "width", ",", "depth", ",", "subdivisionsWidth", ",", "subdivisionsDepth", ",", "matrix", ")", "{", "width", "=", "width", "||", "1", ";", "depth", "=", "depth", "||", "1", ";", "subdivisionsWidth", "=", "subdivisionsWidth", "||", "1", ";", "subdivisionsDepth", "=", "subdivisionsDepth", "||", "1", ";", "matrix", "=", "matrix", "||", "m4", ".", "identity", "(", ")", ";", "const", "numVertices", "=", "(", "subdivisionsWidth", "+", "1", ")", "*", "(", "subdivisionsDepth", "+", "1", ")", ";", "const", "positions", "=", "createAugmentedTypedArray", "(", "3", ",", "numVertices", ")", ";", "const", "normals", "=", "createAugmentedTypedArray", "(", "3", ",", "numVertices", ")", ";", "const", "texcoords", "=", "createAugmentedTypedArray", "(", "2", ",", "numVertices", ")", ";", "for", "(", "let", "z", "=", "0", ";", "z", "<=", "subdivisionsDepth", ";", "z", "++", ")", "{", "for", "(", "let", "x", "=", "0", ";", "x", "<=", "subdivisionsWidth", ";", "x", "++", ")", "{", "const", "u", "=", "x", "/", "subdivisionsWidth", ";", "const", "v", "=", "z", "/", "subdivisionsDepth", ";", "positions", ".", "push", "(", "width", "*", "u", "-", "width", "*", "0.5", ",", "0", ",", "depth", "*", "v", "-", "depth", "*", "0.5", ")", ";", "normals", ".", "push", "(", "0", ",", "1", ",", "0", ")", ";", "texcoords", ".", "push", "(", "u", ",", "v", ")", ";", "}", "}", "const", "numVertsAcross", "=", "subdivisionsWidth", "+", "1", ";", "const", "indices", "=", "createAugmentedTypedArray", "(", "3", ",", "subdivisionsWidth", "*", "subdivisionsDepth", "*", "2", ",", "Uint16Array", ")", ";", "for", "(", "let", "z", "=", "0", ";", "z", "<", "subdivisionsDepth", ";", "z", "++", ")", "{", "// eslint-disable-line", "for", "(", "let", "x", "=", "0", ";", "x", "<", "subdivisionsWidth", ";", "x", "++", ")", "{", "// eslint-disable-line", "// Make triangle 1 of quad.", "indices", ".", "push", "(", "(", "z", "+", "0", ")", "*", "numVertsAcross", "+", "x", ",", "(", "z", "+", "1", ")", "*", "numVertsAcross", "+", "x", ",", "(", "z", "+", "0", ")", "*", "numVertsAcross", "+", "x", "+", "1", ")", ";", "// Make triangle 2 of quad.", "indices", ".", "push", "(", "(", "z", "+", "1", ")", "*", "numVertsAcross", "+", "x", ",", "(", "z", "+", "1", ")", "*", "numVertsAcross", "+", "x", "+", "1", ",", "(", "z", "+", "0", ")", "*", "numVertsAcross", "+", "x", "+", "1", ")", ";", "}", "}", "const", "arrays", "=", "reorientVertices", "(", "{", "position", ":", "positions", ",", "normal", ":", "normals", ",", "texcoord", ":", "texcoords", ",", "indices", ":", "indices", ",", "}", ",", "matrix", ")", ";", "return", "arrays", ";", "}" ]
Creates XZ plane buffers. The created plane has position, normal, and texcoord data @param {WebGLRenderingContext} gl The WebGLRenderingContext. @param {number} [width] Width of the plane. Default = 1 @param {number} [depth] Depth of the plane. Default = 1 @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1 @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1 @param {module:twgl/m4.Mat4} [matrix] A matrix by which to multiply all the vertices. @return {Object.<string, WebGLBuffer>} The created plane buffers. @memberOf module:twgl/primitives @function createPlaneBuffers Creates XZ plane vertices. The created plane has position, normal, and texcoord data @param {number} [width] Width of the plane. Default = 1 @param {number} [depth] Depth of the plane. Default = 1 @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1 @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1 @param {module:twgl/m4.Mat4} [matrix] A matrix by which to multiply all the vertices. @return {Object.<string, TypedArray>} The created plane vertices. @memberOf module:twgl/primitives
[ "Creates", "XZ", "plane", "buffers", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L445-L502
8,849
greggman/twgl.js
src/primitives.js
createSphereVertices
function createSphereVertices( radius, subdivisionsAxis, subdivisionsHeight, opt_startLatitudeInRadians, opt_endLatitudeInRadians, opt_startLongitudeInRadians, opt_endLongitudeInRadians) { if (subdivisionsAxis <= 0 || subdivisionsHeight <= 0) { throw Error('subdivisionAxis and subdivisionHeight must be > 0'); } opt_startLatitudeInRadians = opt_startLatitudeInRadians || 0; opt_endLatitudeInRadians = opt_endLatitudeInRadians || Math.PI; opt_startLongitudeInRadians = opt_startLongitudeInRadians || 0; opt_endLongitudeInRadians = opt_endLongitudeInRadians || (Math.PI * 2); const latRange = opt_endLatitudeInRadians - opt_startLatitudeInRadians; const longRange = opt_endLongitudeInRadians - opt_startLongitudeInRadians; // We are going to generate our sphere by iterating through its // spherical coordinates and generating 2 triangles for each quad on a // ring of the sphere. const numVertices = (subdivisionsAxis + 1) * (subdivisionsHeight + 1); const positions = createAugmentedTypedArray(3, numVertices); const normals = createAugmentedTypedArray(3, numVertices); const texcoords = createAugmentedTypedArray(2 , numVertices); // Generate the individual vertices in our vertex buffer. for (let y = 0; y <= subdivisionsHeight; y++) { for (let x = 0; x <= subdivisionsAxis; x++) { // Generate a vertex based on its spherical coordinates const u = x / subdivisionsAxis; const v = y / subdivisionsHeight; const theta = longRange * u + opt_startLongitudeInRadians; const phi = latRange * v + opt_startLatitudeInRadians; const sinTheta = Math.sin(theta); const cosTheta = Math.cos(theta); const sinPhi = Math.sin(phi); const cosPhi = Math.cos(phi); const ux = cosTheta * sinPhi; const uy = cosPhi; const uz = sinTheta * sinPhi; positions.push(radius * ux, radius * uy, radius * uz); normals.push(ux, uy, uz); texcoords.push(1 - u, v); } } const numVertsAround = subdivisionsAxis + 1; const indices = createAugmentedTypedArray(3, subdivisionsAxis * subdivisionsHeight * 2, Uint16Array); for (let x = 0; x < subdivisionsAxis; x++) { // eslint-disable-line for (let y = 0; y < subdivisionsHeight; y++) { // eslint-disable-line // Make triangle 1 of quad. indices.push( (y + 0) * numVertsAround + x, (y + 0) * numVertsAround + x + 1, (y + 1) * numVertsAround + x); // Make triangle 2 of quad. indices.push( (y + 1) * numVertsAround + x, (y + 0) * numVertsAround + x + 1, (y + 1) * numVertsAround + x + 1); } } return { position: positions, normal: normals, texcoord: texcoords, indices: indices, }; }
javascript
function createSphereVertices( radius, subdivisionsAxis, subdivisionsHeight, opt_startLatitudeInRadians, opt_endLatitudeInRadians, opt_startLongitudeInRadians, opt_endLongitudeInRadians) { if (subdivisionsAxis <= 0 || subdivisionsHeight <= 0) { throw Error('subdivisionAxis and subdivisionHeight must be > 0'); } opt_startLatitudeInRadians = opt_startLatitudeInRadians || 0; opt_endLatitudeInRadians = opt_endLatitudeInRadians || Math.PI; opt_startLongitudeInRadians = opt_startLongitudeInRadians || 0; opt_endLongitudeInRadians = opt_endLongitudeInRadians || (Math.PI * 2); const latRange = opt_endLatitudeInRadians - opt_startLatitudeInRadians; const longRange = opt_endLongitudeInRadians - opt_startLongitudeInRadians; // We are going to generate our sphere by iterating through its // spherical coordinates and generating 2 triangles for each quad on a // ring of the sphere. const numVertices = (subdivisionsAxis + 1) * (subdivisionsHeight + 1); const positions = createAugmentedTypedArray(3, numVertices); const normals = createAugmentedTypedArray(3, numVertices); const texcoords = createAugmentedTypedArray(2 , numVertices); // Generate the individual vertices in our vertex buffer. for (let y = 0; y <= subdivisionsHeight; y++) { for (let x = 0; x <= subdivisionsAxis; x++) { // Generate a vertex based on its spherical coordinates const u = x / subdivisionsAxis; const v = y / subdivisionsHeight; const theta = longRange * u + opt_startLongitudeInRadians; const phi = latRange * v + opt_startLatitudeInRadians; const sinTheta = Math.sin(theta); const cosTheta = Math.cos(theta); const sinPhi = Math.sin(phi); const cosPhi = Math.cos(phi); const ux = cosTheta * sinPhi; const uy = cosPhi; const uz = sinTheta * sinPhi; positions.push(radius * ux, radius * uy, radius * uz); normals.push(ux, uy, uz); texcoords.push(1 - u, v); } } const numVertsAround = subdivisionsAxis + 1; const indices = createAugmentedTypedArray(3, subdivisionsAxis * subdivisionsHeight * 2, Uint16Array); for (let x = 0; x < subdivisionsAxis; x++) { // eslint-disable-line for (let y = 0; y < subdivisionsHeight; y++) { // eslint-disable-line // Make triangle 1 of quad. indices.push( (y + 0) * numVertsAround + x, (y + 0) * numVertsAround + x + 1, (y + 1) * numVertsAround + x); // Make triangle 2 of quad. indices.push( (y + 1) * numVertsAround + x, (y + 0) * numVertsAround + x + 1, (y + 1) * numVertsAround + x + 1); } } return { position: positions, normal: normals, texcoord: texcoords, indices: indices, }; }
[ "function", "createSphereVertices", "(", "radius", ",", "subdivisionsAxis", ",", "subdivisionsHeight", ",", "opt_startLatitudeInRadians", ",", "opt_endLatitudeInRadians", ",", "opt_startLongitudeInRadians", ",", "opt_endLongitudeInRadians", ")", "{", "if", "(", "subdivisionsAxis", "<=", "0", "||", "subdivisionsHeight", "<=", "0", ")", "{", "throw", "Error", "(", "'subdivisionAxis and subdivisionHeight must be > 0'", ")", ";", "}", "opt_startLatitudeInRadians", "=", "opt_startLatitudeInRadians", "||", "0", ";", "opt_endLatitudeInRadians", "=", "opt_endLatitudeInRadians", "||", "Math", ".", "PI", ";", "opt_startLongitudeInRadians", "=", "opt_startLongitudeInRadians", "||", "0", ";", "opt_endLongitudeInRadians", "=", "opt_endLongitudeInRadians", "||", "(", "Math", ".", "PI", "*", "2", ")", ";", "const", "latRange", "=", "opt_endLatitudeInRadians", "-", "opt_startLatitudeInRadians", ";", "const", "longRange", "=", "opt_endLongitudeInRadians", "-", "opt_startLongitudeInRadians", ";", "// We are going to generate our sphere by iterating through its", "// spherical coordinates and generating 2 triangles for each quad on a", "// ring of the sphere.", "const", "numVertices", "=", "(", "subdivisionsAxis", "+", "1", ")", "*", "(", "subdivisionsHeight", "+", "1", ")", ";", "const", "positions", "=", "createAugmentedTypedArray", "(", "3", ",", "numVertices", ")", ";", "const", "normals", "=", "createAugmentedTypedArray", "(", "3", ",", "numVertices", ")", ";", "const", "texcoords", "=", "createAugmentedTypedArray", "(", "2", ",", "numVertices", ")", ";", "// Generate the individual vertices in our vertex buffer.", "for", "(", "let", "y", "=", "0", ";", "y", "<=", "subdivisionsHeight", ";", "y", "++", ")", "{", "for", "(", "let", "x", "=", "0", ";", "x", "<=", "subdivisionsAxis", ";", "x", "++", ")", "{", "// Generate a vertex based on its spherical coordinates", "const", "u", "=", "x", "/", "subdivisionsAxis", ";", "const", "v", "=", "y", "/", "subdivisionsHeight", ";", "const", "theta", "=", "longRange", "*", "u", "+", "opt_startLongitudeInRadians", ";", "const", "phi", "=", "latRange", "*", "v", "+", "opt_startLatitudeInRadians", ";", "const", "sinTheta", "=", "Math", ".", "sin", "(", "theta", ")", ";", "const", "cosTheta", "=", "Math", ".", "cos", "(", "theta", ")", ";", "const", "sinPhi", "=", "Math", ".", "sin", "(", "phi", ")", ";", "const", "cosPhi", "=", "Math", ".", "cos", "(", "phi", ")", ";", "const", "ux", "=", "cosTheta", "*", "sinPhi", ";", "const", "uy", "=", "cosPhi", ";", "const", "uz", "=", "sinTheta", "*", "sinPhi", ";", "positions", ".", "push", "(", "radius", "*", "ux", ",", "radius", "*", "uy", ",", "radius", "*", "uz", ")", ";", "normals", ".", "push", "(", "ux", ",", "uy", ",", "uz", ")", ";", "texcoords", ".", "push", "(", "1", "-", "u", ",", "v", ")", ";", "}", "}", "const", "numVertsAround", "=", "subdivisionsAxis", "+", "1", ";", "const", "indices", "=", "createAugmentedTypedArray", "(", "3", ",", "subdivisionsAxis", "*", "subdivisionsHeight", "*", "2", ",", "Uint16Array", ")", ";", "for", "(", "let", "x", "=", "0", ";", "x", "<", "subdivisionsAxis", ";", "x", "++", ")", "{", "// eslint-disable-line", "for", "(", "let", "y", "=", "0", ";", "y", "<", "subdivisionsHeight", ";", "y", "++", ")", "{", "// eslint-disable-line", "// Make triangle 1 of quad.", "indices", ".", "push", "(", "(", "y", "+", "0", ")", "*", "numVertsAround", "+", "x", ",", "(", "y", "+", "0", ")", "*", "numVertsAround", "+", "x", "+", "1", ",", "(", "y", "+", "1", ")", "*", "numVertsAround", "+", "x", ")", ";", "// Make triangle 2 of quad.", "indices", ".", "push", "(", "(", "y", "+", "1", ")", "*", "numVertsAround", "+", "x", ",", "(", "y", "+", "0", ")", "*", "numVertsAround", "+", "x", "+", "1", ",", "(", "y", "+", "1", ")", "*", "numVertsAround", "+", "x", "+", "1", ")", ";", "}", "}", "return", "{", "position", ":", "positions", ",", "normal", ":", "normals", ",", "texcoord", ":", "texcoords", ",", "indices", ":", "indices", ",", "}", ";", "}" ]
Creates sphere buffers. The created sphere has position, normal, and texcoord data @param {WebGLRenderingContext} gl The WebGLRenderingContext. @param {number} radius radius of the sphere. @param {number} subdivisionsAxis number of steps around the sphere. @param {number} subdivisionsHeight number of vertically on the sphere. @param {number} [opt_startLatitudeInRadians] where to start the top of the sphere. Default = 0. @param {number} [opt_endLatitudeInRadians] Where to end the bottom of the sphere. Default = Math.PI. @param {number} [opt_startLongitudeInRadians] where to start wrapping the sphere. Default = 0. @param {number} [opt_endLongitudeInRadians] where to end wrapping the sphere. Default = 2 * Math.PI. @return {Object.<string, WebGLBuffer>} The created sphere buffers. @memberOf module:twgl/primitives @function createSphereBuffers Creates sphere vertices. The created sphere has position, normal, and texcoord data @param {number} radius radius of the sphere. @param {number} subdivisionsAxis number of steps around the sphere. @param {number} subdivisionsHeight number of vertically on the sphere. @param {number} [opt_startLatitudeInRadians] where to start the top of the sphere. Default = 0. @param {number} [opt_endLatitudeInRadians] Where to end the bottom of the sphere. Default = Math.PI. @param {number} [opt_startLongitudeInRadians] where to start wrapping the sphere. Default = 0. @param {number} [opt_endLongitudeInRadians] where to end wrapping the sphere. Default = 2 * Math.PI. @return {Object.<string, TypedArray>} The created sphere vertices. @memberOf module:twgl/primitives
[ "Creates", "sphere", "buffers", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L567-L640
8,850
greggman/twgl.js
src/primitives.js
createCubeVertices
function createCubeVertices(size) { size = size || 1; const k = size / 2; const cornerVertices = [ [-k, -k, -k], [+k, -k, -k], [-k, +k, -k], [+k, +k, -k], [-k, -k, +k], [+k, -k, +k], [-k, +k, +k], [+k, +k, +k], ]; const faceNormals = [ [+1, +0, +0], [-1, +0, +0], [+0, +1, +0], [+0, -1, +0], [+0, +0, +1], [+0, +0, -1], ]; const uvCoords = [ [1, 0], [0, 0], [0, 1], [1, 1], ]; const numVertices = 6 * 4; const positions = createAugmentedTypedArray(3, numVertices); const normals = createAugmentedTypedArray(3, numVertices); const texcoords = createAugmentedTypedArray(2 , numVertices); const indices = createAugmentedTypedArray(3, 6 * 2, Uint16Array); for (let f = 0; f < 6; ++f) { const faceIndices = CUBE_FACE_INDICES[f]; for (let v = 0; v < 4; ++v) { const position = cornerVertices[faceIndices[v]]; const normal = faceNormals[f]; const uv = uvCoords[v]; // Each face needs all four vertices because the normals and texture // coordinates are not all the same. positions.push(position); normals.push(normal); texcoords.push(uv); } // Two triangles make a square face. const offset = 4 * f; indices.push(offset + 0, offset + 1, offset + 2); indices.push(offset + 0, offset + 2, offset + 3); } return { position: positions, normal: normals, texcoord: texcoords, indices: indices, }; }
javascript
function createCubeVertices(size) { size = size || 1; const k = size / 2; const cornerVertices = [ [-k, -k, -k], [+k, -k, -k], [-k, +k, -k], [+k, +k, -k], [-k, -k, +k], [+k, -k, +k], [-k, +k, +k], [+k, +k, +k], ]; const faceNormals = [ [+1, +0, +0], [-1, +0, +0], [+0, +1, +0], [+0, -1, +0], [+0, +0, +1], [+0, +0, -1], ]; const uvCoords = [ [1, 0], [0, 0], [0, 1], [1, 1], ]; const numVertices = 6 * 4; const positions = createAugmentedTypedArray(3, numVertices); const normals = createAugmentedTypedArray(3, numVertices); const texcoords = createAugmentedTypedArray(2 , numVertices); const indices = createAugmentedTypedArray(3, 6 * 2, Uint16Array); for (let f = 0; f < 6; ++f) { const faceIndices = CUBE_FACE_INDICES[f]; for (let v = 0; v < 4; ++v) { const position = cornerVertices[faceIndices[v]]; const normal = faceNormals[f]; const uv = uvCoords[v]; // Each face needs all four vertices because the normals and texture // coordinates are not all the same. positions.push(position); normals.push(normal); texcoords.push(uv); } // Two triangles make a square face. const offset = 4 * f; indices.push(offset + 0, offset + 1, offset + 2); indices.push(offset + 0, offset + 2, offset + 3); } return { position: positions, normal: normals, texcoord: texcoords, indices: indices, }; }
[ "function", "createCubeVertices", "(", "size", ")", "{", "size", "=", "size", "||", "1", ";", "const", "k", "=", "size", "/", "2", ";", "const", "cornerVertices", "=", "[", "[", "-", "k", ",", "-", "k", ",", "-", "k", "]", ",", "[", "+", "k", ",", "-", "k", ",", "-", "k", "]", ",", "[", "-", "k", ",", "+", "k", ",", "-", "k", "]", ",", "[", "+", "k", ",", "+", "k", ",", "-", "k", "]", ",", "[", "-", "k", ",", "-", "k", ",", "+", "k", "]", ",", "[", "+", "k", ",", "-", "k", ",", "+", "k", "]", ",", "[", "-", "k", ",", "+", "k", ",", "+", "k", "]", ",", "[", "+", "k", ",", "+", "k", ",", "+", "k", "]", ",", "]", ";", "const", "faceNormals", "=", "[", "[", "+", "1", ",", "+", "0", ",", "+", "0", "]", ",", "[", "-", "1", ",", "+", "0", ",", "+", "0", "]", ",", "[", "+", "0", ",", "+", "1", ",", "+", "0", "]", ",", "[", "+", "0", ",", "-", "1", ",", "+", "0", "]", ",", "[", "+", "0", ",", "+", "0", ",", "+", "1", "]", ",", "[", "+", "0", ",", "+", "0", ",", "-", "1", "]", ",", "]", ";", "const", "uvCoords", "=", "[", "[", "1", ",", "0", "]", ",", "[", "0", ",", "0", "]", ",", "[", "0", ",", "1", "]", ",", "[", "1", ",", "1", "]", ",", "]", ";", "const", "numVertices", "=", "6", "*", "4", ";", "const", "positions", "=", "createAugmentedTypedArray", "(", "3", ",", "numVertices", ")", ";", "const", "normals", "=", "createAugmentedTypedArray", "(", "3", ",", "numVertices", ")", ";", "const", "texcoords", "=", "createAugmentedTypedArray", "(", "2", ",", "numVertices", ")", ";", "const", "indices", "=", "createAugmentedTypedArray", "(", "3", ",", "6", "*", "2", ",", "Uint16Array", ")", ";", "for", "(", "let", "f", "=", "0", ";", "f", "<", "6", ";", "++", "f", ")", "{", "const", "faceIndices", "=", "CUBE_FACE_INDICES", "[", "f", "]", ";", "for", "(", "let", "v", "=", "0", ";", "v", "<", "4", ";", "++", "v", ")", "{", "const", "position", "=", "cornerVertices", "[", "faceIndices", "[", "v", "]", "]", ";", "const", "normal", "=", "faceNormals", "[", "f", "]", ";", "const", "uv", "=", "uvCoords", "[", "v", "]", ";", "// Each face needs all four vertices because the normals and texture", "// coordinates are not all the same.", "positions", ".", "push", "(", "position", ")", ";", "normals", ".", "push", "(", "normal", ")", ";", "texcoords", ".", "push", "(", "uv", ")", ";", "}", "// Two triangles make a square face.", "const", "offset", "=", "4", "*", "f", ";", "indices", ".", "push", "(", "offset", "+", "0", ",", "offset", "+", "1", ",", "offset", "+", "2", ")", ";", "indices", ".", "push", "(", "offset", "+", "0", ",", "offset", "+", "2", ",", "offset", "+", "3", ")", ";", "}", "return", "{", "position", ":", "positions", ",", "normal", ":", "normals", ",", "texcoord", ":", "texcoords", ",", "indices", ":", "indices", ",", "}", ";", "}" ]
Creates the buffers and indices for a cube. The cube is created around the origin. (-size / 2, size / 2). @param {WebGLRenderingContext} gl The WebGLRenderingContext. @param {number} [size] width, height and depth of the cube. @return {Object.<string, WebGLBuffer>} The created buffers. @memberOf module:twgl/primitives @function createCubeBuffers Creates the vertices and indices for a cube. The cube is created around the origin. (-size / 2, size / 2). @param {number} [size] width, height and depth of the cube. @return {Object.<string, TypedArray>} The created vertices. @memberOf module:twgl/primitives
[ "Creates", "the", "buffers", "and", "indices", "for", "a", "cube", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L689-L752
8,851
greggman/twgl.js
src/primitives.js
expandRLEData
function expandRLEData(rleData, padding) { padding = padding || []; const data = []; for (let ii = 0; ii < rleData.length; ii += 4) { const runLength = rleData[ii]; const element = rleData.slice(ii + 1, ii + 4); element.push.apply(element, padding); for (let jj = 0; jj < runLength; ++jj) { data.push.apply(data, element); } } return data; }
javascript
function expandRLEData(rleData, padding) { padding = padding || []; const data = []; for (let ii = 0; ii < rleData.length; ii += 4) { const runLength = rleData[ii]; const element = rleData.slice(ii + 1, ii + 4); element.push.apply(element, padding); for (let jj = 0; jj < runLength; ++jj) { data.push.apply(data, element); } } return data; }
[ "function", "expandRLEData", "(", "rleData", ",", "padding", ")", "{", "padding", "=", "padding", "||", "[", "]", ";", "const", "data", "=", "[", "]", ";", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "rleData", ".", "length", ";", "ii", "+=", "4", ")", "{", "const", "runLength", "=", "rleData", "[", "ii", "]", ";", "const", "element", "=", "rleData", ".", "slice", "(", "ii", "+", "1", ",", "ii", "+", "4", ")", ";", "element", ".", "push", ".", "apply", "(", "element", ",", "padding", ")", ";", "for", "(", "let", "jj", "=", "0", ";", "jj", "<", "runLength", ";", "++", "jj", ")", "{", "data", ".", "push", ".", "apply", "(", "data", ",", "element", ")", ";", "}", "}", "return", "data", ";", "}" ]
Expands RLE data @param {number[]} rleData data in format of run-length, x, y, z, run-length, x, y, z @param {number[]} [padding] value to add each entry with. @return {number[]} the expanded rleData @private
[ "Expands", "RLE", "data" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L913-L925
8,852
greggman/twgl.js
src/primitives.js
createCylinderVertices
function createCylinderVertices( radius, height, radialSubdivisions, verticalSubdivisions, topCap, bottomCap) { return createTruncatedConeVertices( radius, radius, height, radialSubdivisions, verticalSubdivisions, topCap, bottomCap); }
javascript
function createCylinderVertices( radius, height, radialSubdivisions, verticalSubdivisions, topCap, bottomCap) { return createTruncatedConeVertices( radius, radius, height, radialSubdivisions, verticalSubdivisions, topCap, bottomCap); }
[ "function", "createCylinderVertices", "(", "radius", ",", "height", ",", "radialSubdivisions", ",", "verticalSubdivisions", ",", "topCap", ",", "bottomCap", ")", "{", "return", "createTruncatedConeVertices", "(", "radius", ",", "radius", ",", "height", ",", "radialSubdivisions", ",", "verticalSubdivisions", ",", "topCap", ",", "bottomCap", ")", ";", "}" ]
Creates cylinder buffers. The cylinder will be created around the origin along the y-axis. @param {WebGLRenderingContext} gl The WebGLRenderingContext. @param {number} radius Radius of cylinder. @param {number} height Height of cylinder. @param {number} radialSubdivisions The number of subdivisions around the cylinder. @param {number} verticalSubdivisions The number of subdivisions down the cylinder. @param {boolean} [topCap] Create top cap. Default = true. @param {boolean} [bottomCap] Create bottom cap. Default = true. @return {Object.<string, WebGLBuffer>} The created buffers. @memberOf module:twgl/primitives @function createCylinderBuffers Creates cylinder vertices. The cylinder will be created around the origin along the y-axis. @param {number} radius Radius of cylinder. @param {number} height Height of cylinder. @param {number} radialSubdivisions The number of subdivisions around the cylinder. @param {number} verticalSubdivisions The number of subdivisions down the cylinder. @param {boolean} [topCap] Create top cap. Default = true. @param {boolean} [bottomCap] Create bottom cap. Default = true. @return {Object.<string, TypedArray>} The created vertices. @memberOf module:twgl/primitives
[ "Creates", "cylinder", "buffers", ".", "The", "cylinder", "will", "be", "created", "around", "the", "origin", "along", "the", "y", "-", "axis", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L1507-L1522
8,853
greggman/twgl.js
src/primitives.js
createTorusVertices
function createTorusVertices( radius, thickness, radialSubdivisions, bodySubdivisions, startAngle, endAngle) { if (radialSubdivisions < 3) { throw Error('radialSubdivisions must be 3 or greater'); } if (bodySubdivisions < 3) { throw Error('verticalSubdivisions must be 3 or greater'); } startAngle = startAngle || 0; endAngle = endAngle || Math.PI * 2; const range = endAngle - startAngle; const radialParts = radialSubdivisions + 1; const bodyParts = bodySubdivisions + 1; const numVertices = radialParts * bodyParts; const positions = createAugmentedTypedArray(3, numVertices); const normals = createAugmentedTypedArray(3, numVertices); const texcoords = createAugmentedTypedArray(2, numVertices); const indices = createAugmentedTypedArray(3, (radialSubdivisions) * (bodySubdivisions) * 2, Uint16Array); for (let slice = 0; slice < bodyParts; ++slice) { const v = slice / bodySubdivisions; const sliceAngle = v * Math.PI * 2; const sliceSin = Math.sin(sliceAngle); const ringRadius = radius + sliceSin * thickness; const ny = Math.cos(sliceAngle); const y = ny * thickness; for (let ring = 0; ring < radialParts; ++ring) { const u = ring / radialSubdivisions; const ringAngle = startAngle + u * range; const xSin = Math.sin(ringAngle); const zCos = Math.cos(ringAngle); const x = xSin * ringRadius; const z = zCos * ringRadius; const nx = xSin * sliceSin; const nz = zCos * sliceSin; positions.push(x, y, z); normals.push(nx, ny, nz); texcoords.push(u, 1 - v); } } for (let slice = 0; slice < bodySubdivisions; ++slice) { // eslint-disable-line for (let ring = 0; ring < radialSubdivisions; ++ring) { // eslint-disable-line const nextRingIndex = 1 + ring; const nextSliceIndex = 1 + slice; indices.push(radialParts * slice + ring, radialParts * nextSliceIndex + ring, radialParts * slice + nextRingIndex); indices.push(radialParts * nextSliceIndex + ring, radialParts * nextSliceIndex + nextRingIndex, radialParts * slice + nextRingIndex); } } return { position: positions, normal: normals, texcoord: texcoords, indices: indices, }; }
javascript
function createTorusVertices( radius, thickness, radialSubdivisions, bodySubdivisions, startAngle, endAngle) { if (radialSubdivisions < 3) { throw Error('radialSubdivisions must be 3 or greater'); } if (bodySubdivisions < 3) { throw Error('verticalSubdivisions must be 3 or greater'); } startAngle = startAngle || 0; endAngle = endAngle || Math.PI * 2; const range = endAngle - startAngle; const radialParts = radialSubdivisions + 1; const bodyParts = bodySubdivisions + 1; const numVertices = radialParts * bodyParts; const positions = createAugmentedTypedArray(3, numVertices); const normals = createAugmentedTypedArray(3, numVertices); const texcoords = createAugmentedTypedArray(2, numVertices); const indices = createAugmentedTypedArray(3, (radialSubdivisions) * (bodySubdivisions) * 2, Uint16Array); for (let slice = 0; slice < bodyParts; ++slice) { const v = slice / bodySubdivisions; const sliceAngle = v * Math.PI * 2; const sliceSin = Math.sin(sliceAngle); const ringRadius = radius + sliceSin * thickness; const ny = Math.cos(sliceAngle); const y = ny * thickness; for (let ring = 0; ring < radialParts; ++ring) { const u = ring / radialSubdivisions; const ringAngle = startAngle + u * range; const xSin = Math.sin(ringAngle); const zCos = Math.cos(ringAngle); const x = xSin * ringRadius; const z = zCos * ringRadius; const nx = xSin * sliceSin; const nz = zCos * sliceSin; positions.push(x, y, z); normals.push(nx, ny, nz); texcoords.push(u, 1 - v); } } for (let slice = 0; slice < bodySubdivisions; ++slice) { // eslint-disable-line for (let ring = 0; ring < radialSubdivisions; ++ring) { // eslint-disable-line const nextRingIndex = 1 + ring; const nextSliceIndex = 1 + slice; indices.push(radialParts * slice + ring, radialParts * nextSliceIndex + ring, radialParts * slice + nextRingIndex); indices.push(radialParts * nextSliceIndex + ring, radialParts * nextSliceIndex + nextRingIndex, radialParts * slice + nextRingIndex); } } return { position: positions, normal: normals, texcoord: texcoords, indices: indices, }; }
[ "function", "createTorusVertices", "(", "radius", ",", "thickness", ",", "radialSubdivisions", ",", "bodySubdivisions", ",", "startAngle", ",", "endAngle", ")", "{", "if", "(", "radialSubdivisions", "<", "3", ")", "{", "throw", "Error", "(", "'radialSubdivisions must be 3 or greater'", ")", ";", "}", "if", "(", "bodySubdivisions", "<", "3", ")", "{", "throw", "Error", "(", "'verticalSubdivisions must be 3 or greater'", ")", ";", "}", "startAngle", "=", "startAngle", "||", "0", ";", "endAngle", "=", "endAngle", "||", "Math", ".", "PI", "*", "2", ";", "const", "range", "=", "endAngle", "-", "startAngle", ";", "const", "radialParts", "=", "radialSubdivisions", "+", "1", ";", "const", "bodyParts", "=", "bodySubdivisions", "+", "1", ";", "const", "numVertices", "=", "radialParts", "*", "bodyParts", ";", "const", "positions", "=", "createAugmentedTypedArray", "(", "3", ",", "numVertices", ")", ";", "const", "normals", "=", "createAugmentedTypedArray", "(", "3", ",", "numVertices", ")", ";", "const", "texcoords", "=", "createAugmentedTypedArray", "(", "2", ",", "numVertices", ")", ";", "const", "indices", "=", "createAugmentedTypedArray", "(", "3", ",", "(", "radialSubdivisions", ")", "*", "(", "bodySubdivisions", ")", "*", "2", ",", "Uint16Array", ")", ";", "for", "(", "let", "slice", "=", "0", ";", "slice", "<", "bodyParts", ";", "++", "slice", ")", "{", "const", "v", "=", "slice", "/", "bodySubdivisions", ";", "const", "sliceAngle", "=", "v", "*", "Math", ".", "PI", "*", "2", ";", "const", "sliceSin", "=", "Math", ".", "sin", "(", "sliceAngle", ")", ";", "const", "ringRadius", "=", "radius", "+", "sliceSin", "*", "thickness", ";", "const", "ny", "=", "Math", ".", "cos", "(", "sliceAngle", ")", ";", "const", "y", "=", "ny", "*", "thickness", ";", "for", "(", "let", "ring", "=", "0", ";", "ring", "<", "radialParts", ";", "++", "ring", ")", "{", "const", "u", "=", "ring", "/", "radialSubdivisions", ";", "const", "ringAngle", "=", "startAngle", "+", "u", "*", "range", ";", "const", "xSin", "=", "Math", ".", "sin", "(", "ringAngle", ")", ";", "const", "zCos", "=", "Math", ".", "cos", "(", "ringAngle", ")", ";", "const", "x", "=", "xSin", "*", "ringRadius", ";", "const", "z", "=", "zCos", "*", "ringRadius", ";", "const", "nx", "=", "xSin", "*", "sliceSin", ";", "const", "nz", "=", "zCos", "*", "sliceSin", ";", "positions", ".", "push", "(", "x", ",", "y", ",", "z", ")", ";", "normals", ".", "push", "(", "nx", ",", "ny", ",", "nz", ")", ";", "texcoords", ".", "push", "(", "u", ",", "1", "-", "v", ")", ";", "}", "}", "for", "(", "let", "slice", "=", "0", ";", "slice", "<", "bodySubdivisions", ";", "++", "slice", ")", "{", "// eslint-disable-line", "for", "(", "let", "ring", "=", "0", ";", "ring", "<", "radialSubdivisions", ";", "++", "ring", ")", "{", "// eslint-disable-line", "const", "nextRingIndex", "=", "1", "+", "ring", ";", "const", "nextSliceIndex", "=", "1", "+", "slice", ";", "indices", ".", "push", "(", "radialParts", "*", "slice", "+", "ring", ",", "radialParts", "*", "nextSliceIndex", "+", "ring", ",", "radialParts", "*", "slice", "+", "nextRingIndex", ")", ";", "indices", ".", "push", "(", "radialParts", "*", "nextSliceIndex", "+", "ring", ",", "radialParts", "*", "nextSliceIndex", "+", "nextRingIndex", ",", "radialParts", "*", "slice", "+", "nextRingIndex", ")", ";", "}", "}", "return", "{", "position", ":", "positions", ",", "normal", ":", "normals", ",", "texcoord", ":", "texcoords", ",", "indices", ":", "indices", ",", "}", ";", "}" ]
Creates buffers for a torus @param {WebGLRenderingContext} gl The WebGLRenderingContext. @param {number} radius radius of center of torus circle. @param {number} thickness radius of torus ring. @param {number} radialSubdivisions The number of subdivisions around the torus. @param {number} bodySubdivisions The number of subdivisions around the body torus. @param {boolean} [startAngle] start angle in radians. Default = 0. @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2. @return {Object.<string, WebGLBuffer>} The created buffers. @memberOf module:twgl/primitives @function createTorusBuffers Creates vertices for a torus @param {number} radius radius of center of torus circle. @param {number} thickness radius of torus ring. @param {number} radialSubdivisions The number of subdivisions around the torus. @param {number} bodySubdivisions The number of subdivisions around the body torus. @param {boolean} [startAngle] start angle in radians. Default = 0. @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2. @return {Object.<string, TypedArray>} The created vertices. @memberOf module:twgl/primitives
[ "Creates", "buffers", "for", "a", "torus" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L1566-L1634
8,854
greggman/twgl.js
src/primitives.js
createDiscVertices
function createDiscVertices( radius, divisions, stacks, innerRadius, stackPower) { if (divisions < 3) { throw Error('divisions must be at least 3'); } stacks = stacks ? stacks : 1; stackPower = stackPower ? stackPower : 1; innerRadius = innerRadius ? innerRadius : 0; // Note: We don't share the center vertex because that would // mess up texture coordinates. const numVertices = (divisions + 1) * (stacks + 1); const positions = createAugmentedTypedArray(3, numVertices); const normals = createAugmentedTypedArray(3, numVertices); const texcoords = createAugmentedTypedArray(2, numVertices); const indices = createAugmentedTypedArray(3, stacks * divisions * 2, Uint16Array); let firstIndex = 0; const radiusSpan = radius - innerRadius; const pointsPerStack = divisions + 1; // Build the disk one stack at a time. for (let stack = 0; stack <= stacks; ++stack) { const stackRadius = innerRadius + radiusSpan * Math.pow(stack / stacks, stackPower); for (let i = 0; i <= divisions; ++i) { const theta = 2.0 * Math.PI * i / divisions; const x = stackRadius * Math.cos(theta); const z = stackRadius * Math.sin(theta); positions.push(x, 0, z); normals.push(0, 1, 0); texcoords.push(1 - (i / divisions), stack / stacks); if (stack > 0 && i !== divisions) { // a, b, c and d are the indices of the vertices of a quad. unless // the current stack is the one closest to the center, in which case // the vertices a and b connect to the center vertex. const a = firstIndex + (i + 1); const b = firstIndex + i; const c = firstIndex + i - pointsPerStack; const d = firstIndex + (i + 1) - pointsPerStack; // Make a quad of the vertices a, b, c, d. indices.push(a, b, c); indices.push(a, c, d); } } firstIndex += divisions + 1; } return { position: positions, normal: normals, texcoord: texcoords, indices: indices, }; }
javascript
function createDiscVertices( radius, divisions, stacks, innerRadius, stackPower) { if (divisions < 3) { throw Error('divisions must be at least 3'); } stacks = stacks ? stacks : 1; stackPower = stackPower ? stackPower : 1; innerRadius = innerRadius ? innerRadius : 0; // Note: We don't share the center vertex because that would // mess up texture coordinates. const numVertices = (divisions + 1) * (stacks + 1); const positions = createAugmentedTypedArray(3, numVertices); const normals = createAugmentedTypedArray(3, numVertices); const texcoords = createAugmentedTypedArray(2, numVertices); const indices = createAugmentedTypedArray(3, stacks * divisions * 2, Uint16Array); let firstIndex = 0; const radiusSpan = radius - innerRadius; const pointsPerStack = divisions + 1; // Build the disk one stack at a time. for (let stack = 0; stack <= stacks; ++stack) { const stackRadius = innerRadius + radiusSpan * Math.pow(stack / stacks, stackPower); for (let i = 0; i <= divisions; ++i) { const theta = 2.0 * Math.PI * i / divisions; const x = stackRadius * Math.cos(theta); const z = stackRadius * Math.sin(theta); positions.push(x, 0, z); normals.push(0, 1, 0); texcoords.push(1 - (i / divisions), stack / stacks); if (stack > 0 && i !== divisions) { // a, b, c and d are the indices of the vertices of a quad. unless // the current stack is the one closest to the center, in which case // the vertices a and b connect to the center vertex. const a = firstIndex + (i + 1); const b = firstIndex + i; const c = firstIndex + i - pointsPerStack; const d = firstIndex + (i + 1) - pointsPerStack; // Make a quad of the vertices a, b, c, d. indices.push(a, b, c); indices.push(a, c, d); } } firstIndex += divisions + 1; } return { position: positions, normal: normals, texcoord: texcoords, indices: indices, }; }
[ "function", "createDiscVertices", "(", "radius", ",", "divisions", ",", "stacks", ",", "innerRadius", ",", "stackPower", ")", "{", "if", "(", "divisions", "<", "3", ")", "{", "throw", "Error", "(", "'divisions must be at least 3'", ")", ";", "}", "stacks", "=", "stacks", "?", "stacks", ":", "1", ";", "stackPower", "=", "stackPower", "?", "stackPower", ":", "1", ";", "innerRadius", "=", "innerRadius", "?", "innerRadius", ":", "0", ";", "// Note: We don't share the center vertex because that would", "// mess up texture coordinates.", "const", "numVertices", "=", "(", "divisions", "+", "1", ")", "*", "(", "stacks", "+", "1", ")", ";", "const", "positions", "=", "createAugmentedTypedArray", "(", "3", ",", "numVertices", ")", ";", "const", "normals", "=", "createAugmentedTypedArray", "(", "3", ",", "numVertices", ")", ";", "const", "texcoords", "=", "createAugmentedTypedArray", "(", "2", ",", "numVertices", ")", ";", "const", "indices", "=", "createAugmentedTypedArray", "(", "3", ",", "stacks", "*", "divisions", "*", "2", ",", "Uint16Array", ")", ";", "let", "firstIndex", "=", "0", ";", "const", "radiusSpan", "=", "radius", "-", "innerRadius", ";", "const", "pointsPerStack", "=", "divisions", "+", "1", ";", "// Build the disk one stack at a time.", "for", "(", "let", "stack", "=", "0", ";", "stack", "<=", "stacks", ";", "++", "stack", ")", "{", "const", "stackRadius", "=", "innerRadius", "+", "radiusSpan", "*", "Math", ".", "pow", "(", "stack", "/", "stacks", ",", "stackPower", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<=", "divisions", ";", "++", "i", ")", "{", "const", "theta", "=", "2.0", "*", "Math", ".", "PI", "*", "i", "/", "divisions", ";", "const", "x", "=", "stackRadius", "*", "Math", ".", "cos", "(", "theta", ")", ";", "const", "z", "=", "stackRadius", "*", "Math", ".", "sin", "(", "theta", ")", ";", "positions", ".", "push", "(", "x", ",", "0", ",", "z", ")", ";", "normals", ".", "push", "(", "0", ",", "1", ",", "0", ")", ";", "texcoords", ".", "push", "(", "1", "-", "(", "i", "/", "divisions", ")", ",", "stack", "/", "stacks", ")", ";", "if", "(", "stack", ">", "0", "&&", "i", "!==", "divisions", ")", "{", "// a, b, c and d are the indices of the vertices of a quad. unless", "// the current stack is the one closest to the center, in which case", "// the vertices a and b connect to the center vertex.", "const", "a", "=", "firstIndex", "+", "(", "i", "+", "1", ")", ";", "const", "b", "=", "firstIndex", "+", "i", ";", "const", "c", "=", "firstIndex", "+", "i", "-", "pointsPerStack", ";", "const", "d", "=", "firstIndex", "+", "(", "i", "+", "1", ")", "-", "pointsPerStack", ";", "// Make a quad of the vertices a, b, c, d.", "indices", ".", "push", "(", "a", ",", "b", ",", "c", ")", ";", "indices", ".", "push", "(", "a", ",", "c", ",", "d", ")", ";", "}", "}", "firstIndex", "+=", "divisions", "+", "1", ";", "}", "return", "{", "position", ":", "positions", ",", "normal", ":", "normals", ",", "texcoord", ":", "texcoords", ",", "indices", ":", "indices", ",", "}", ";", "}" ]
Creates disc buffers. The disc will be in the xz plane, centered at the origin. When creating, at least 3 divisions, or pie pieces, need to be specified, otherwise the triangles making up the disc will be degenerate. You can also specify the number of radial pieces `stacks`. A value of 1 for stacks will give you a simple disc of pie pieces. If you want to create an annulus you can set `innerRadius` to a value > 0. Finally, `stackPower` allows you to have the widths increase or decrease as you move away from the center. This is particularly useful when using the disc as a ground plane with a fixed camera such that you don't need the resolution of small triangles near the perimeter. For example, a value of 2 will produce stacks whose ouside radius increases with the square of the stack index. A value of 1 will give uniform stacks. @param {WebGLRenderingContext} gl The WebGLRenderingContext. @param {number} radius Radius of the ground plane. @param {number} divisions Number of triangles in the ground plane (at least 3). @param {number} [stacks] Number of radial divisions (default=1). @param {number} [innerRadius] Default 0. @param {number} [stackPower] Power to raise stack size to for decreasing width. @return {Object.<string, WebGLBuffer>} The created buffers. @memberOf module:twgl/primitives @function createDiscBuffers Creates disc vertices. The disc will be in the xz plane, centered at the origin. When creating, at least 3 divisions, or pie pieces, need to be specified, otherwise the triangles making up the disc will be degenerate. You can also specify the number of radial pieces `stacks`. A value of 1 for stacks will give you a simple disc of pie pieces. If you want to create an annulus you can set `innerRadius` to a value > 0. Finally, `stackPower` allows you to have the widths increase or decrease as you move away from the center. This is particularly useful when using the disc as a ground plane with a fixed camera such that you don't need the resolution of small triangles near the perimeter. For example, a value of 2 will produce stacks whose ouside radius increases with the square of the stack index. A value of 1 will give uniform stacks. @param {number} radius Radius of the ground plane. @param {number} divisions Number of triangles in the ground plane (at least 3). @param {number} [stacks] Number of radial divisions (default=1). @param {number} [innerRadius] Default 0. @param {number} [stackPower] Power to raise stack size to for decreasing width. @return {Object.<string, TypedArray>} The created vertices. @memberOf module:twgl/primitives
[ "Creates", "disc", "buffers", ".", "The", "disc", "will", "be", "in", "the", "xz", "plane", "centered", "at", "the", "origin", ".", "When", "creating", "at", "least", "3", "divisions", "or", "pie", "pieces", "need", "to", "be", "specified", "otherwise", "the", "triangles", "making", "up", "the", "disc", "will", "be", "degenerate", ".", "You", "can", "also", "specify", "the", "number", "of", "radial", "pieces", "stacks", ".", "A", "value", "of", "1", "for", "stacks", "will", "give", "you", "a", "simple", "disc", "of", "pie", "pieces", ".", "If", "you", "want", "to", "create", "an", "annulus", "you", "can", "set", "innerRadius", "to", "a", "value", ">", "0", ".", "Finally", "stackPower", "allows", "you", "to", "have", "the", "widths", "increase", "or", "decrease", "as", "you", "move", "away", "from", "the", "center", ".", "This", "is", "particularly", "useful", "when", "using", "the", "disc", "as", "a", "ground", "plane", "with", "a", "fixed", "camera", "such", "that", "you", "don", "t", "need", "the", "resolution", "of", "small", "triangles", "near", "the", "perimeter", ".", "For", "example", "a", "value", "of", "2", "will", "produce", "stacks", "whose", "ouside", "radius", "increases", "with", "the", "square", "of", "the", "stack", "index", ".", "A", "value", "of", "1", "will", "give", "uniform", "stacks", "." ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L1718-L1781
8,855
greggman/twgl.js
src/primitives.js
createBufferFunc
function createBufferFunc(fn) { return function(gl) { const arrays = fn.apply(this, Array.prototype.slice.call(arguments, 1)); return attributes.createBuffersFromArrays(gl, arrays); }; }
javascript
function createBufferFunc(fn) { return function(gl) { const arrays = fn.apply(this, Array.prototype.slice.call(arguments, 1)); return attributes.createBuffersFromArrays(gl, arrays); }; }
[ "function", "createBufferFunc", "(", "fn", ")", "{", "return", "function", "(", "gl", ")", "{", "const", "arrays", "=", "fn", ".", "apply", "(", "this", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "return", "attributes", ".", "createBuffersFromArrays", "(", "gl", ",", "arrays", ")", ";", "}", ";", "}" ]
creates a function that calls fn to create vertices and then creates a buffers for them @private
[ "creates", "a", "function", "that", "calls", "fn", "to", "create", "vertices", "and", "then", "creates", "a", "buffers", "for", "them" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L1851-L1856
8,856
greggman/twgl.js
src/primitives.js
createBufferInfoFunc
function createBufferInfoFunc(fn) { return function(gl) { const arrays = fn.apply(null, Array.prototype.slice.call(arguments, 1)); return attributes.createBufferInfoFromArrays(gl, arrays); }; }
javascript
function createBufferInfoFunc(fn) { return function(gl) { const arrays = fn.apply(null, Array.prototype.slice.call(arguments, 1)); return attributes.createBufferInfoFromArrays(gl, arrays); }; }
[ "function", "createBufferInfoFunc", "(", "fn", ")", "{", "return", "function", "(", "gl", ")", "{", "const", "arrays", "=", "fn", ".", "apply", "(", "null", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "return", "attributes", ".", "createBufferInfoFromArrays", "(", "gl", ",", "arrays", ")", ";", "}", ";", "}" ]
creates a function that calls fn to create vertices and then creates a bufferInfo object for them @private
[ "creates", "a", "function", "that", "calls", "fn", "to", "create", "vertices", "and", "then", "creates", "a", "bufferInfo", "object", "for", "them" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L1863-L1868
8,857
greggman/twgl.js
src/primitives.js
copyElements
function copyElements(src, dst, dstNdx, offset) { offset = offset || 0; const length = src.length; for (let ii = 0; ii < length; ++ii) { dst[dstNdx + ii] = src[ii] + offset; } }
javascript
function copyElements(src, dst, dstNdx, offset) { offset = offset || 0; const length = src.length; for (let ii = 0; ii < length; ++ii) { dst[dstNdx + ii] = src[ii] + offset; } }
[ "function", "copyElements", "(", "src", ",", "dst", ",", "dstNdx", ",", "offset", ")", "{", "offset", "=", "offset", "||", "0", ";", "const", "length", "=", "src", ".", "length", ";", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "length", ";", "++", "ii", ")", "{", "dst", "[", "dstNdx", "+", "ii", "]", "=", "src", "[", "ii", "]", "+", "offset", ";", "}", "}" ]
Copy elements from one array to another @param {Array|TypedArray} src source array @param {Array|TypedArray} dst dest array @param {number} dstNdx index in dest to copy src @param {number} [offset] offset to add to copied values @private
[ "Copy", "elements", "from", "one", "array", "to", "another" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L1891-L1897
8,858
greggman/twgl.js
src/primitives.js
createArrayOfSameType
function createArrayOfSameType(srcArray, length) { const arraySrc = getArray(srcArray); const newArray = new arraySrc.constructor(length); let newArraySpec = newArray; // If it appears to have been augmented make new one augemented if (arraySrc.numComponents && arraySrc.numElements) { augmentTypedArray(newArray, arraySrc.numComponents); } // If it was a fullspec make new one a fullspec if (srcArray.data) { newArraySpec = { data: newArray, }; helper.copyNamedProperties(arraySpecPropertyNames, srcArray, newArraySpec); } return newArraySpec; }
javascript
function createArrayOfSameType(srcArray, length) { const arraySrc = getArray(srcArray); const newArray = new arraySrc.constructor(length); let newArraySpec = newArray; // If it appears to have been augmented make new one augemented if (arraySrc.numComponents && arraySrc.numElements) { augmentTypedArray(newArray, arraySrc.numComponents); } // If it was a fullspec make new one a fullspec if (srcArray.data) { newArraySpec = { data: newArray, }; helper.copyNamedProperties(arraySpecPropertyNames, srcArray, newArraySpec); } return newArraySpec; }
[ "function", "createArrayOfSameType", "(", "srcArray", ",", "length", ")", "{", "const", "arraySrc", "=", "getArray", "(", "srcArray", ")", ";", "const", "newArray", "=", "new", "arraySrc", ".", "constructor", "(", "length", ")", ";", "let", "newArraySpec", "=", "newArray", ";", "// If it appears to have been augmented make new one augemented", "if", "(", "arraySrc", ".", "numComponents", "&&", "arraySrc", ".", "numElements", ")", "{", "augmentTypedArray", "(", "newArray", ",", "arraySrc", ".", "numComponents", ")", ";", "}", "// If it was a fullspec make new one a fullspec", "if", "(", "srcArray", ".", "data", ")", "{", "newArraySpec", "=", "{", "data", ":", "newArray", ",", "}", ";", "helper", ".", "copyNamedProperties", "(", "arraySpecPropertyNames", ",", "srcArray", ",", "newArraySpec", ")", ";", "}", "return", "newArraySpec", ";", "}" ]
Creates an array of the same time @param {(number[]|ArrayBufferView|module:twgl.FullArraySpec)} srcArray array who's type to copy @param {number} length size of new array @return {(number[]|ArrayBufferView|module:twgl.FullArraySpec)} array with same type as srcArray @private
[ "Creates", "an", "array", "of", "the", "same", "time" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L1907-L1923
8,859
greggman/twgl.js
src/primitives.js
concatVertices
function concatVertices(arrayOfArrays) { const names = {}; let baseName; // get names of all arrays. // and numElements for each set of vertices for (let ii = 0; ii < arrayOfArrays.length; ++ii) { const arrays = arrayOfArrays[ii]; Object.keys(arrays).forEach(function(name) { // eslint-disable-line if (!names[name]) { names[name] = []; } if (!baseName && name !== 'indices') { baseName = name; } const arrayInfo = arrays[name]; const numComponents = getNumComponents(arrayInfo, name); const array = getArray(arrayInfo); const numElements = array.length / numComponents; names[name].push(numElements); }); } // compute length of combined array // and return one for reference function getLengthOfCombinedArrays(name) { let length = 0; let arraySpec; for (let ii = 0; ii < arrayOfArrays.length; ++ii) { const arrays = arrayOfArrays[ii]; const arrayInfo = arrays[name]; const array = getArray(arrayInfo); length += array.length; if (!arraySpec || arrayInfo.data) { arraySpec = arrayInfo; } } return { length: length, spec: arraySpec, }; } function copyArraysToNewArray(name, base, newArray) { let baseIndex = 0; let offset = 0; for (let ii = 0; ii < arrayOfArrays.length; ++ii) { const arrays = arrayOfArrays[ii]; const arrayInfo = arrays[name]; const array = getArray(arrayInfo); if (name === 'indices') { copyElements(array, newArray, offset, baseIndex); baseIndex += base[ii]; } else { copyElements(array, newArray, offset); } offset += array.length; } } const base = names[baseName]; const newArrays = {}; Object.keys(names).forEach(function(name) { const info = getLengthOfCombinedArrays(name); const newArraySpec = createArrayOfSameType(info.spec, info.length); copyArraysToNewArray(name, base, getArray(newArraySpec)); newArrays[name] = newArraySpec; }); return newArrays; }
javascript
function concatVertices(arrayOfArrays) { const names = {}; let baseName; // get names of all arrays. // and numElements for each set of vertices for (let ii = 0; ii < arrayOfArrays.length; ++ii) { const arrays = arrayOfArrays[ii]; Object.keys(arrays).forEach(function(name) { // eslint-disable-line if (!names[name]) { names[name] = []; } if (!baseName && name !== 'indices') { baseName = name; } const arrayInfo = arrays[name]; const numComponents = getNumComponents(arrayInfo, name); const array = getArray(arrayInfo); const numElements = array.length / numComponents; names[name].push(numElements); }); } // compute length of combined array // and return one for reference function getLengthOfCombinedArrays(name) { let length = 0; let arraySpec; for (let ii = 0; ii < arrayOfArrays.length; ++ii) { const arrays = arrayOfArrays[ii]; const arrayInfo = arrays[name]; const array = getArray(arrayInfo); length += array.length; if (!arraySpec || arrayInfo.data) { arraySpec = arrayInfo; } } return { length: length, spec: arraySpec, }; } function copyArraysToNewArray(name, base, newArray) { let baseIndex = 0; let offset = 0; for (let ii = 0; ii < arrayOfArrays.length; ++ii) { const arrays = arrayOfArrays[ii]; const arrayInfo = arrays[name]; const array = getArray(arrayInfo); if (name === 'indices') { copyElements(array, newArray, offset, baseIndex); baseIndex += base[ii]; } else { copyElements(array, newArray, offset); } offset += array.length; } } const base = names[baseName]; const newArrays = {}; Object.keys(names).forEach(function(name) { const info = getLengthOfCombinedArrays(name); const newArraySpec = createArrayOfSameType(info.spec, info.length); copyArraysToNewArray(name, base, getArray(newArraySpec)); newArrays[name] = newArraySpec; }); return newArrays; }
[ "function", "concatVertices", "(", "arrayOfArrays", ")", "{", "const", "names", "=", "{", "}", ";", "let", "baseName", ";", "// get names of all arrays.", "// and numElements for each set of vertices", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "arrayOfArrays", ".", "length", ";", "++", "ii", ")", "{", "const", "arrays", "=", "arrayOfArrays", "[", "ii", "]", ";", "Object", ".", "keys", "(", "arrays", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "// eslint-disable-line", "if", "(", "!", "names", "[", "name", "]", ")", "{", "names", "[", "name", "]", "=", "[", "]", ";", "}", "if", "(", "!", "baseName", "&&", "name", "!==", "'indices'", ")", "{", "baseName", "=", "name", ";", "}", "const", "arrayInfo", "=", "arrays", "[", "name", "]", ";", "const", "numComponents", "=", "getNumComponents", "(", "arrayInfo", ",", "name", ")", ";", "const", "array", "=", "getArray", "(", "arrayInfo", ")", ";", "const", "numElements", "=", "array", ".", "length", "/", "numComponents", ";", "names", "[", "name", "]", ".", "push", "(", "numElements", ")", ";", "}", ")", ";", "}", "// compute length of combined array", "// and return one for reference", "function", "getLengthOfCombinedArrays", "(", "name", ")", "{", "let", "length", "=", "0", ";", "let", "arraySpec", ";", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "arrayOfArrays", ".", "length", ";", "++", "ii", ")", "{", "const", "arrays", "=", "arrayOfArrays", "[", "ii", "]", ";", "const", "arrayInfo", "=", "arrays", "[", "name", "]", ";", "const", "array", "=", "getArray", "(", "arrayInfo", ")", ";", "length", "+=", "array", ".", "length", ";", "if", "(", "!", "arraySpec", "||", "arrayInfo", ".", "data", ")", "{", "arraySpec", "=", "arrayInfo", ";", "}", "}", "return", "{", "length", ":", "length", ",", "spec", ":", "arraySpec", ",", "}", ";", "}", "function", "copyArraysToNewArray", "(", "name", ",", "base", ",", "newArray", ")", "{", "let", "baseIndex", "=", "0", ";", "let", "offset", "=", "0", ";", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "arrayOfArrays", ".", "length", ";", "++", "ii", ")", "{", "const", "arrays", "=", "arrayOfArrays", "[", "ii", "]", ";", "const", "arrayInfo", "=", "arrays", "[", "name", "]", ";", "const", "array", "=", "getArray", "(", "arrayInfo", ")", ";", "if", "(", "name", "===", "'indices'", ")", "{", "copyElements", "(", "array", ",", "newArray", ",", "offset", ",", "baseIndex", ")", ";", "baseIndex", "+=", "base", "[", "ii", "]", ";", "}", "else", "{", "copyElements", "(", "array", ",", "newArray", ",", "offset", ")", ";", "}", "offset", "+=", "array", ".", "length", ";", "}", "}", "const", "base", "=", "names", "[", "baseName", "]", ";", "const", "newArrays", "=", "{", "}", ";", "Object", ".", "keys", "(", "names", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "const", "info", "=", "getLengthOfCombinedArrays", "(", "name", ")", ";", "const", "newArraySpec", "=", "createArrayOfSameType", "(", "info", ".", "spec", ",", "info", ".", "length", ")", ";", "copyArraysToNewArray", "(", "name", ",", "base", ",", "getArray", "(", "newArraySpec", ")", ")", ";", "newArrays", "[", "name", "]", "=", "newArraySpec", ";", "}", ")", ";", "return", "newArrays", ";", "}" ]
Concatinates sets of vertices Assumes the vertices match in composition. For example if one set of vertices has positions, normals, and indices all sets of vertices must have positions, normals, and indices and of the same type. Example: const cubeVertices = twgl.primtiives.createCubeVertices(2); const sphereVertices = twgl.primitives.createSphereVertices(1, 10, 10); // move the sphere 2 units up twgl.primitives.reorientVertices( sphereVertices, twgl.m4.translation([0, 2, 0])); // merge the sphere with the cube const cubeSphereVertices = twgl.primitives.concatVertices( [cubeVertices, sphereVertices]); // turn them into WebGL buffers and attrib data const bufferInfo = twgl.createBufferInfoFromArrays(gl, cubeSphereVertices); @param {module:twgl.Arrays[]} arrays Array of arrays of vertices @return {module:twgl.Arrays} The concatinated vertices. @memberOf module:twgl/primitives
[ "Concatinates", "sets", "of", "vertices" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L1950-L2019
8,860
greggman/twgl.js
src/primitives.js
getLengthOfCombinedArrays
function getLengthOfCombinedArrays(name) { let length = 0; let arraySpec; for (let ii = 0; ii < arrayOfArrays.length; ++ii) { const arrays = arrayOfArrays[ii]; const arrayInfo = arrays[name]; const array = getArray(arrayInfo); length += array.length; if (!arraySpec || arrayInfo.data) { arraySpec = arrayInfo; } } return { length: length, spec: arraySpec, }; }
javascript
function getLengthOfCombinedArrays(name) { let length = 0; let arraySpec; for (let ii = 0; ii < arrayOfArrays.length; ++ii) { const arrays = arrayOfArrays[ii]; const arrayInfo = arrays[name]; const array = getArray(arrayInfo); length += array.length; if (!arraySpec || arrayInfo.data) { arraySpec = arrayInfo; } } return { length: length, spec: arraySpec, }; }
[ "function", "getLengthOfCombinedArrays", "(", "name", ")", "{", "let", "length", "=", "0", ";", "let", "arraySpec", ";", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "arrayOfArrays", ".", "length", ";", "++", "ii", ")", "{", "const", "arrays", "=", "arrayOfArrays", "[", "ii", "]", ";", "const", "arrayInfo", "=", "arrays", "[", "name", "]", ";", "const", "array", "=", "getArray", "(", "arrayInfo", ")", ";", "length", "+=", "array", ".", "length", ";", "if", "(", "!", "arraySpec", "||", "arrayInfo", ".", "data", ")", "{", "arraySpec", "=", "arrayInfo", ";", "}", "}", "return", "{", "length", ":", "length", ",", "spec", ":", "arraySpec", ",", "}", ";", "}" ]
compute length of combined array and return one for reference
[ "compute", "length", "of", "combined", "array", "and", "return", "one", "for", "reference" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L1974-L1990
8,861
greggman/twgl.js
src/primitives.js
duplicateVertices
function duplicateVertices(arrays) { const newArrays = {}; Object.keys(arrays).forEach(function(name) { const arraySpec = arrays[name]; const srcArray = getArray(arraySpec); const newArraySpec = createArrayOfSameType(arraySpec, srcArray.length); copyElements(srcArray, getArray(newArraySpec), 0); newArrays[name] = newArraySpec; }); return newArrays; }
javascript
function duplicateVertices(arrays) { const newArrays = {}; Object.keys(arrays).forEach(function(name) { const arraySpec = arrays[name]; const srcArray = getArray(arraySpec); const newArraySpec = createArrayOfSameType(arraySpec, srcArray.length); copyElements(srcArray, getArray(newArraySpec), 0); newArrays[name] = newArraySpec; }); return newArrays; }
[ "function", "duplicateVertices", "(", "arrays", ")", "{", "const", "newArrays", "=", "{", "}", ";", "Object", ".", "keys", "(", "arrays", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "const", "arraySpec", "=", "arrays", "[", "name", "]", ";", "const", "srcArray", "=", "getArray", "(", "arraySpec", ")", ";", "const", "newArraySpec", "=", "createArrayOfSameType", "(", "arraySpec", ",", "srcArray", ".", "length", ")", ";", "copyElements", "(", "srcArray", ",", "getArray", "(", "newArraySpec", ")", ",", "0", ")", ";", "newArrays", "[", "name", "]", "=", "newArraySpec", ";", "}", ")", ";", "return", "newArrays", ";", "}" ]
Creates a duplicate set of vertices This is useful for calling reorientVertices when you also want to keep the original available @param {module:twgl.Arrays} arrays of vertices @return {module:twgl.Arrays} The dupilicated vertices. @memberOf module:twgl/primitives
[ "Creates", "a", "duplicate", "set", "of", "vertices" ]
ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd
https://github.com/greggman/twgl.js/blob/ae88dfe4d7a7d44a5b739fcbe50bccccd0e1a1fd/src/primitives.js#L2031-L2041
8,862
isomorphic-git/isomorphic-git
src/models/PGP.js
printKey
function printKey () { let keyid = printKeyid(this.primaryKey.getKeyId()) let userid = printUser(this.getPrimaryUser().user) return keyid + ' ' + userid }
javascript
function printKey () { let keyid = printKeyid(this.primaryKey.getKeyId()) let userid = printUser(this.getPrimaryUser().user) return keyid + ' ' + userid }
[ "function", "printKey", "(", ")", "{", "let", "keyid", "=", "printKeyid", "(", "this", ".", "primaryKey", ".", "getKeyId", "(", ")", ")", "let", "userid", "=", "printUser", "(", "this", ".", "getPrimaryUser", "(", ")", ".", "user", ")", "return", "keyid", "+", "' '", "+", "userid", "}" ]
Print a key
[ "Print", "a", "key" ]
fc29aba74ea55c798abb0274e0a032c6af90cb58
https://github.com/isomorphic-git/isomorphic-git/blob/fc29aba74ea55c798abb0274e0a032c6af90cb58/src/models/PGP.js#L10-L14
8,863
isomorphic-git/isomorphic-git
src/models/GitPackIndex.js
otherVarIntDecode
function otherVarIntDecode (reader, startWith) { let result = startWith let shift = 4 let byte = null do { byte = reader.readUInt8() result |= (byte & 0b01111111) << shift shift += 7 } while (byte & 0b10000000) return result }
javascript
function otherVarIntDecode (reader, startWith) { let result = startWith let shift = 4 let byte = null do { byte = reader.readUInt8() result |= (byte & 0b01111111) << shift shift += 7 } while (byte & 0b10000000) return result }
[ "function", "otherVarIntDecode", "(", "reader", ",", "startWith", ")", "{", "let", "result", "=", "startWith", "let", "shift", "=", "4", "let", "byte", "=", "null", "do", "{", "byte", "=", "reader", ".", "readUInt8", "(", ")", "result", "|=", "(", "byte", "&", "0b01111111", ")", "<<", "shift", "shift", "+=", "7", "}", "while", "(", "byte", "&", "0b10000000", ")", "return", "result", "}" ]
I'm pretty much copying this one from the git C source code, because it makes no sense.
[ "I", "m", "pretty", "much", "copying", "this", "one", "from", "the", "git", "C", "source", "code", "because", "it", "makes", "no", "sense", "." ]
fc29aba74ea55c798abb0274e0a032c6af90cb58
https://github.com/isomorphic-git/isomorphic-git/blob/fc29aba74ea55c798abb0274e0a032c6af90cb58/src/models/GitPackIndex.js#L35-L45
8,864
isomorphic-git/isomorphic-git
src/models/GitIndex.js
parseCacheEntryFlags
function parseCacheEntryFlags (bits) { return { assumeValid: Boolean(bits & 0b1000000000000000), extended: Boolean(bits & 0b0100000000000000), stage: (bits & 0b0011000000000000) >> 12, nameLength: bits & 0b0000111111111111 } }
javascript
function parseCacheEntryFlags (bits) { return { assumeValid: Boolean(bits & 0b1000000000000000), extended: Boolean(bits & 0b0100000000000000), stage: (bits & 0b0011000000000000) >> 12, nameLength: bits & 0b0000111111111111 } }
[ "function", "parseCacheEntryFlags", "(", "bits", ")", "{", "return", "{", "assumeValid", ":", "Boolean", "(", "bits", "&", "0b1000000000000000", ")", ",", "extended", ":", "Boolean", "(", "bits", "&", "0b0100000000000000", ")", ",", "stage", ":", "(", "bits", "&", "0b0011000000000000", ")", ">>", "12", ",", "nameLength", ":", "bits", "&", "0b0000111111111111", "}", "}" ]
Extract 1-bit assume-valid, 1-bit extended flag, 2-bit merge state flag, 12-bit path length flag
[ "Extract", "1", "-", "bit", "assume", "-", "valid", "1", "-", "bit", "extended", "flag", "2", "-", "bit", "merge", "state", "flag", "12", "-", "bit", "path", "length", "flag" ]
fc29aba74ea55c798abb0274e0a032c6af90cb58
https://github.com/isomorphic-git/isomorphic-git/blob/fc29aba74ea55c798abb0274e0a032c6af90cb58/src/models/GitIndex.js#L9-L16
8,865
jsonresume/resume-cli
lib/init.js
fillInit
function fillInit() { console.log('\nThis utility will generate a resume.json file in your current working directory.'); console.log('Fill out your name and email to get started, or leave the fields blank.'); console.log('All fields are optional.\n'); console.log('Press ^C at any time to quit.'); read({ prompt: 'name: ' }, function(er, name) { if (er) { console.log(); process.exit(); } read({ prompt: 'email: ' }, function(er, email) { if (er) { console.log(); process.exit(); } resumeJson.basics.name = name; resumeJson.basics.email = email; fs.writeFileSync(process.cwd() + '/resume.json', JSON.stringify(resumeJson, undefined, 2)); console.log('\nYour resume.json has been created!'.green); console.log(''); console.log('To generate a formatted .html .md .txt or .pdf resume from your resume.json'); console.log('type: `resume export [someFileName]` including file extension eg: `resume export myresume.html`'); console.log('\nYou can optionally specify an available theme for html and pdf resumes using the --theme flag.'); console.log('Example: `resume export myresume.pdf --theme flat`'); console.log('Or simply type: `resume export` and follow the prompts.'); console.log(''); process.exit(); callback(true); }); }); }
javascript
function fillInit() { console.log('\nThis utility will generate a resume.json file in your current working directory.'); console.log('Fill out your name and email to get started, or leave the fields blank.'); console.log('All fields are optional.\n'); console.log('Press ^C at any time to quit.'); read({ prompt: 'name: ' }, function(er, name) { if (er) { console.log(); process.exit(); } read({ prompt: 'email: ' }, function(er, email) { if (er) { console.log(); process.exit(); } resumeJson.basics.name = name; resumeJson.basics.email = email; fs.writeFileSync(process.cwd() + '/resume.json', JSON.stringify(resumeJson, undefined, 2)); console.log('\nYour resume.json has been created!'.green); console.log(''); console.log('To generate a formatted .html .md .txt or .pdf resume from your resume.json'); console.log('type: `resume export [someFileName]` including file extension eg: `resume export myresume.html`'); console.log('\nYou can optionally specify an available theme for html and pdf resumes using the --theme flag.'); console.log('Example: `resume export myresume.pdf --theme flat`'); console.log('Or simply type: `resume export` and follow the prompts.'); console.log(''); process.exit(); callback(true); }); }); }
[ "function", "fillInit", "(", ")", "{", "console", ".", "log", "(", "'\\nThis utility will generate a resume.json file in your current working directory.'", ")", ";", "console", ".", "log", "(", "'Fill out your name and email to get started, or leave the fields blank.'", ")", ";", "console", ".", "log", "(", "'All fields are optional.\\n'", ")", ";", "console", ".", "log", "(", "'Press ^C at any time to quit.'", ")", ";", "read", "(", "{", "prompt", ":", "'name: '", "}", ",", "function", "(", "er", ",", "name", ")", "{", "if", "(", "er", ")", "{", "console", ".", "log", "(", ")", ";", "process", ".", "exit", "(", ")", ";", "}", "read", "(", "{", "prompt", ":", "'email: '", "}", ",", "function", "(", "er", ",", "email", ")", "{", "if", "(", "er", ")", "{", "console", ".", "log", "(", ")", ";", "process", ".", "exit", "(", ")", ";", "}", "resumeJson", ".", "basics", ".", "name", "=", "name", ";", "resumeJson", ".", "basics", ".", "email", "=", "email", ";", "fs", ".", "writeFileSync", "(", "process", ".", "cwd", "(", ")", "+", "'/resume.json'", ",", "JSON", ".", "stringify", "(", "resumeJson", ",", "undefined", ",", "2", ")", ")", ";", "console", ".", "log", "(", "'\\nYour resume.json has been created!'", ".", "green", ")", ";", "console", ".", "log", "(", "''", ")", ";", "console", ".", "log", "(", "'To generate a formatted .html .md .txt or .pdf resume from your resume.json'", ")", ";", "console", ".", "log", "(", "'type: `resume export [someFileName]` including file extension eg: `resume export myresume.html`'", ")", ";", "console", ".", "log", "(", "'\\nYou can optionally specify an available theme for html and pdf resumes using the --theme flag.'", ")", ";", "console", ".", "log", "(", "'Example: `resume export myresume.pdf --theme flat`'", ")", ";", "console", ".", "log", "(", "'Or simply type: `resume export` and follow the prompts.'", ")", ";", "console", ".", "log", "(", "''", ")", ";", "process", ".", "exit", "(", ")", ";", "callback", "(", "true", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
slowly replace colors with chalk
[ "slowly", "replace", "colors", "with", "chalk" ]
229aa718f054ed4166275d8c1352d11319ffcab2
https://github.com/jsonresume/resume-cli/blob/229aa718f054ed4166275d8c1352d11319ffcab2/lib/init.js#L6-L46
8,866
zadvorsky/three.bas
dist/bas.module.js
ToonAnimationMaterial
function ToonAnimationMaterial(parameters) { if (!parameters.defines) { parameters.defines = {}; } parameters.defines['TOON'] = ''; PhongAnimationMaterial.call(this, parameters); }
javascript
function ToonAnimationMaterial(parameters) { if (!parameters.defines) { parameters.defines = {}; } parameters.defines['TOON'] = ''; PhongAnimationMaterial.call(this, parameters); }
[ "function", "ToonAnimationMaterial", "(", "parameters", ")", "{", "if", "(", "!", "parameters", ".", "defines", ")", "{", "parameters", ".", "defines", "=", "{", "}", ";", "}", "parameters", ".", "defines", "[", "'TOON'", "]", "=", "''", ";", "PhongAnimationMaterial", ".", "call", "(", "this", ",", "parameters", ")", ";", "}" ]
Extends THREE.MeshToonMaterial with custom shader chunks. MeshToonMaterial is mostly the same as MeshPhongMaterial. The only difference is a TOON define, and support for a gradientMap uniform. @param {Object} parameters Object containing material properties and custom shader chunks. @constructor
[ "Extends", "THREE", ".", "MeshToonMaterial", "with", "custom", "shader", "chunks", ".", "MeshToonMaterial", "is", "mostly", "the", "same", "as", "MeshPhongMaterial", ".", "The", "only", "difference", "is", "a", "TOON", "define", "and", "support", "for", "a", "gradientMap", "uniform", "." ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/dist/bas.module.js#L363-L370
8,867
zadvorsky/three.bas
dist/bas.module.js
MultiPrefabBufferGeometry
function MultiPrefabBufferGeometry(prefabs, repeatCount) { BufferGeometry.call(this); if (Array.isArray(prefabs)) { this.prefabGeometries = prefabs; } else { this.prefabGeometries = [prefabs]; } this.prefabGeometriesCount = this.prefabGeometries.length; /** * Number of prefabs. * @type {Number} */ this.prefabCount = repeatCount * this.prefabGeometriesCount; /** * How often the prefab array is repeated. * @type {Number} */ this.repeatCount = repeatCount; /** * Array of vertex counts per prefab. * @type {Array} */ this.prefabVertexCounts = this.prefabGeometries.map(function (p) { return p.isBufferGeometry ? p.attributes.position.count : p.vertices.length; }); /** * Total number of vertices for one repetition of the prefabs * @type {number} */ this.repeatVertexCount = this.prefabVertexCounts.reduce(function (r, v) { return r + v; }, 0); this.bufferIndices(); this.bufferPositions(); }
javascript
function MultiPrefabBufferGeometry(prefabs, repeatCount) { BufferGeometry.call(this); if (Array.isArray(prefabs)) { this.prefabGeometries = prefabs; } else { this.prefabGeometries = [prefabs]; } this.prefabGeometriesCount = this.prefabGeometries.length; /** * Number of prefabs. * @type {Number} */ this.prefabCount = repeatCount * this.prefabGeometriesCount; /** * How often the prefab array is repeated. * @type {Number} */ this.repeatCount = repeatCount; /** * Array of vertex counts per prefab. * @type {Array} */ this.prefabVertexCounts = this.prefabGeometries.map(function (p) { return p.isBufferGeometry ? p.attributes.position.count : p.vertices.length; }); /** * Total number of vertices for one repetition of the prefabs * @type {number} */ this.repeatVertexCount = this.prefabVertexCounts.reduce(function (r, v) { return r + v; }, 0); this.bufferIndices(); this.bufferPositions(); }
[ "function", "MultiPrefabBufferGeometry", "(", "prefabs", ",", "repeatCount", ")", "{", "BufferGeometry", ".", "call", "(", "this", ")", ";", "if", "(", "Array", ".", "isArray", "(", "prefabs", ")", ")", "{", "this", ".", "prefabGeometries", "=", "prefabs", ";", "}", "else", "{", "this", ".", "prefabGeometries", "=", "[", "prefabs", "]", ";", "}", "this", ".", "prefabGeometriesCount", "=", "this", ".", "prefabGeometries", ".", "length", ";", "/**\n * Number of prefabs.\n * @type {Number}\n */", "this", ".", "prefabCount", "=", "repeatCount", "*", "this", ".", "prefabGeometriesCount", ";", "/**\n * How often the prefab array is repeated.\n * @type {Number}\n */", "this", ".", "repeatCount", "=", "repeatCount", ";", "/**\n * Array of vertex counts per prefab.\n * @type {Array}\n */", "this", ".", "prefabVertexCounts", "=", "this", ".", "prefabGeometries", ".", "map", "(", "function", "(", "p", ")", "{", "return", "p", ".", "isBufferGeometry", "?", "p", ".", "attributes", ".", "position", ".", "count", ":", "p", ".", "vertices", ".", "length", ";", "}", ")", ";", "/**\n * Total number of vertices for one repetition of the prefabs\n * @type {number}\n */", "this", ".", "repeatVertexCount", "=", "this", ".", "prefabVertexCounts", ".", "reduce", "(", "function", "(", "r", ",", "v", ")", "{", "return", "r", "+", "v", ";", "}", ",", "0", ")", ";", "this", ".", "bufferIndices", "(", ")", ";", "this", ".", "bufferPositions", "(", ")", ";", "}" ]
A BufferGeometry where a 'prefab' geometry array is repeated a number of times. @param {Array} prefabs An array with Geometry instances to repeat. @param {Number} repeatCount The number of times to repeat the array of Geometries. @constructor
[ "A", "BufferGeometry", "where", "a", "prefab", "geometry", "array", "is", "repeated", "a", "number", "of", "times", "." ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/dist/bas.module.js#L657-L696
8,868
zadvorsky/three.bas
dist/bas.module.js
InstancedPrefabBufferGeometry
function InstancedPrefabBufferGeometry(prefab, count) { if (prefab.isGeometry === true) { console.error('InstancedPrefabBufferGeometry prefab must be a BufferGeometry.'); } InstancedBufferGeometry.call(this); this.prefabGeometry = prefab; this.copy(prefab); this.maxInstancedCount = count; this.prefabCount = count; }
javascript
function InstancedPrefabBufferGeometry(prefab, count) { if (prefab.isGeometry === true) { console.error('InstancedPrefabBufferGeometry prefab must be a BufferGeometry.'); } InstancedBufferGeometry.call(this); this.prefabGeometry = prefab; this.copy(prefab); this.maxInstancedCount = count; this.prefabCount = count; }
[ "function", "InstancedPrefabBufferGeometry", "(", "prefab", ",", "count", ")", "{", "if", "(", "prefab", ".", "isGeometry", "===", "true", ")", "{", "console", ".", "error", "(", "'InstancedPrefabBufferGeometry prefab must be a BufferGeometry.'", ")", ";", "}", "InstancedBufferGeometry", ".", "call", "(", "this", ")", ";", "this", ".", "prefabGeometry", "=", "prefab", ";", "this", ".", "copy", "(", "prefab", ")", ";", "this", ".", "maxInstancedCount", "=", "count", ";", "this", ".", "prefabCount", "=", "count", ";", "}" ]
A wrapper around THREE.InstancedBufferGeometry, which is more memory efficient than PrefabBufferGeometry, but requires the ANGLE_instanced_arrays extension. @param {BufferGeometry} prefab The Geometry instance to repeat. @param {Number} count The number of times to repeat the geometry. @constructor
[ "A", "wrapper", "around", "THREE", ".", "InstancedBufferGeometry", "which", "is", "more", "memory", "efficient", "than", "PrefabBufferGeometry", "but", "requires", "the", "ANGLE_instanced_arrays", "extension", "." ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/dist/bas.module.js#L907-L919
8,869
zadvorsky/three.bas
dist/bas.module.js
separateFaces
function separateFaces(geometry) { var vertices = []; for (var i = 0, il = geometry.faces.length; i < il; i++) { var n = vertices.length; var face = geometry.faces[i]; var a = face.a; var b = face.b; var c = face.c; var va = geometry.vertices[a]; var vb = geometry.vertices[b]; var vc = geometry.vertices[c]; vertices.push(va.clone()); vertices.push(vb.clone()); vertices.push(vc.clone()); face.a = n; face.b = n + 1; face.c = n + 2; } geometry.vertices = vertices; }
javascript
function separateFaces(geometry) { var vertices = []; for (var i = 0, il = geometry.faces.length; i < il; i++) { var n = vertices.length; var face = geometry.faces[i]; var a = face.a; var b = face.b; var c = face.c; var va = geometry.vertices[a]; var vb = geometry.vertices[b]; var vc = geometry.vertices[c]; vertices.push(va.clone()); vertices.push(vb.clone()); vertices.push(vc.clone()); face.a = n; face.b = n + 1; face.c = n + 2; } geometry.vertices = vertices; }
[ "function", "separateFaces", "(", "geometry", ")", "{", "var", "vertices", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "il", "=", "geometry", ".", "faces", ".", "length", ";", "i", "<", "il", ";", "i", "++", ")", "{", "var", "n", "=", "vertices", ".", "length", ";", "var", "face", "=", "geometry", ".", "faces", "[", "i", "]", ";", "var", "a", "=", "face", ".", "a", ";", "var", "b", "=", "face", ".", "b", ";", "var", "c", "=", "face", ".", "c", ";", "var", "va", "=", "geometry", ".", "vertices", "[", "a", "]", ";", "var", "vb", "=", "geometry", ".", "vertices", "[", "b", "]", ";", "var", "vc", "=", "geometry", ".", "vertices", "[", "c", "]", ";", "vertices", ".", "push", "(", "va", ".", "clone", "(", ")", ")", ";", "vertices", ".", "push", "(", "vb", ".", "clone", "(", ")", ")", ";", "vertices", ".", "push", "(", "vc", ".", "clone", "(", ")", ")", ";", "face", ".", "a", "=", "n", ";", "face", ".", "b", "=", "n", "+", "1", ";", "face", ".", "c", "=", "n", "+", "2", ";", "}", "geometry", ".", "vertices", "=", "vertices", ";", "}" ]
Duplicates vertices so each face becomes separate. Same as THREE.ExplodeModifier. @param {THREE.Geometry} geometry Geometry instance to modify.
[ "Duplicates", "vertices", "so", "each", "face", "becomes", "separate", ".", "Same", "as", "THREE", ".", "ExplodeModifier", "." ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/dist/bas.module.js#L979-L1004
8,870
zadvorsky/three.bas
dist/bas.module.js
createDepthAnimationMaterial
function createDepthAnimationMaterial(sourceMaterial) { return new DepthAnimationMaterial({ uniforms: sourceMaterial.uniforms, defines: sourceMaterial.defines, vertexFunctions: sourceMaterial.vertexFunctions, vertexParameters: sourceMaterial.vertexParameters, vertexInit: sourceMaterial.vertexInit, vertexPosition: sourceMaterial.vertexPosition }); }
javascript
function createDepthAnimationMaterial(sourceMaterial) { return new DepthAnimationMaterial({ uniforms: sourceMaterial.uniforms, defines: sourceMaterial.defines, vertexFunctions: sourceMaterial.vertexFunctions, vertexParameters: sourceMaterial.vertexParameters, vertexInit: sourceMaterial.vertexInit, vertexPosition: sourceMaterial.vertexPosition }); }
[ "function", "createDepthAnimationMaterial", "(", "sourceMaterial", ")", "{", "return", "new", "DepthAnimationMaterial", "(", "{", "uniforms", ":", "sourceMaterial", ".", "uniforms", ",", "defines", ":", "sourceMaterial", ".", "defines", ",", "vertexFunctions", ":", "sourceMaterial", ".", "vertexFunctions", ",", "vertexParameters", ":", "sourceMaterial", ".", "vertexParameters", ",", "vertexInit", ":", "sourceMaterial", ".", "vertexInit", ",", "vertexPosition", ":", "sourceMaterial", ".", "vertexPosition", "}", ")", ";", "}" ]
Create a THREE.BAS.DepthAnimationMaterial for shadows from a THREE.SpotLight or THREE.DirectionalLight by copying relevant shader chunks. Uniform values must be manually synced between the source material and the depth material. @see {@link http://three-bas-examples.surge.sh/examples/shadows/} @param {THREE.BAS.BaseAnimationMaterial} sourceMaterial Instance to get the shader chunks from. @returns {THREE.BAS.DepthAnimationMaterial}
[ "Create", "a", "THREE", ".", "BAS", ".", "DepthAnimationMaterial", "for", "shadows", "from", "a", "THREE", ".", "SpotLight", "or", "THREE", ".", "DirectionalLight", "by", "copying", "relevant", "shader", "chunks", ".", "Uniform", "values", "must", "be", "manually", "synced", "between", "the", "source", "material", "and", "the", "depth", "material", "." ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/dist/bas.module.js#L1071-L1080
8,871
zadvorsky/three.bas
dist/bas.module.js
createDistanceAnimationMaterial
function createDistanceAnimationMaterial(sourceMaterial) { return new DistanceAnimationMaterial({ uniforms: sourceMaterial.uniforms, defines: sourceMaterial.defines, vertexFunctions: sourceMaterial.vertexFunctions, vertexParameters: sourceMaterial.vertexParameters, vertexInit: sourceMaterial.vertexInit, vertexPosition: sourceMaterial.vertexPosition }); }
javascript
function createDistanceAnimationMaterial(sourceMaterial) { return new DistanceAnimationMaterial({ uniforms: sourceMaterial.uniforms, defines: sourceMaterial.defines, vertexFunctions: sourceMaterial.vertexFunctions, vertexParameters: sourceMaterial.vertexParameters, vertexInit: sourceMaterial.vertexInit, vertexPosition: sourceMaterial.vertexPosition }); }
[ "function", "createDistanceAnimationMaterial", "(", "sourceMaterial", ")", "{", "return", "new", "DistanceAnimationMaterial", "(", "{", "uniforms", ":", "sourceMaterial", ".", "uniforms", ",", "defines", ":", "sourceMaterial", ".", "defines", ",", "vertexFunctions", ":", "sourceMaterial", ".", "vertexFunctions", ",", "vertexParameters", ":", "sourceMaterial", ".", "vertexParameters", ",", "vertexInit", ":", "sourceMaterial", ".", "vertexInit", ",", "vertexPosition", ":", "sourceMaterial", ".", "vertexPosition", "}", ")", ";", "}" ]
Create a THREE.BAS.DistanceAnimationMaterial for shadows from a THREE.PointLight by copying relevant shader chunks. Uniform values must be manually synced between the source material and the distance material. @see {@link http://three-bas-examples.surge.sh/examples/shadows/} @param {THREE.BAS.BaseAnimationMaterial} sourceMaterial Instance to get the shader chunks from. @returns {THREE.BAS.DistanceAnimationMaterial}
[ "Create", "a", "THREE", ".", "BAS", ".", "DistanceAnimationMaterial", "for", "shadows", "from", "a", "THREE", ".", "PointLight", "by", "copying", "relevant", "shader", "chunks", ".", "Uniform", "values", "must", "be", "manually", "synced", "between", "the", "source", "material", "and", "the", "distance", "material", "." ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/dist/bas.module.js#L1091-L1100
8,872
zadvorsky/three.bas
dist/bas.module.js
ModelBufferGeometry
function ModelBufferGeometry(model, options) { BufferGeometry.call(this); /** * A reference to the geometry used to create this instance. * @type {THREE.Geometry} */ this.modelGeometry = model; /** * Number of faces of the model. * @type {Number} */ this.faceCount = this.modelGeometry.faces.length; /** * Number of vertices of the model. * @type {Number} */ this.vertexCount = this.modelGeometry.vertices.length; options = options || {}; options.computeCentroids && this.computeCentroids(); this.bufferIndices(); this.bufferPositions(options.localizeFaces); }
javascript
function ModelBufferGeometry(model, options) { BufferGeometry.call(this); /** * A reference to the geometry used to create this instance. * @type {THREE.Geometry} */ this.modelGeometry = model; /** * Number of faces of the model. * @type {Number} */ this.faceCount = this.modelGeometry.faces.length; /** * Number of vertices of the model. * @type {Number} */ this.vertexCount = this.modelGeometry.vertices.length; options = options || {}; options.computeCentroids && this.computeCentroids(); this.bufferIndices(); this.bufferPositions(options.localizeFaces); }
[ "function", "ModelBufferGeometry", "(", "model", ",", "options", ")", "{", "BufferGeometry", ".", "call", "(", "this", ")", ";", "/**\n * A reference to the geometry used to create this instance.\n * @type {THREE.Geometry}\n */", "this", ".", "modelGeometry", "=", "model", ";", "/**\n * Number of faces of the model.\n * @type {Number}\n */", "this", ".", "faceCount", "=", "this", ".", "modelGeometry", ".", "faces", ".", "length", ";", "/**\n * Number of vertices of the model.\n * @type {Number}\n */", "this", ".", "vertexCount", "=", "this", ".", "modelGeometry", ".", "vertices", ".", "length", ";", "options", "=", "options", "||", "{", "}", ";", "options", ".", "computeCentroids", "&&", "this", ".", "computeCentroids", "(", ")", ";", "this", ".", "bufferIndices", "(", ")", ";", "this", ".", "bufferPositions", "(", "options", ".", "localizeFaces", ")", ";", "}" ]
A THREE.BufferGeometry for animating individual faces of a THREE.Geometry. @param {THREE.Geometry} model The THREE.Geometry to base this geometry on. @param {Object=} options @param {Boolean=} options.computeCentroids If true, a centroids will be computed for each face and stored in THREE.BAS.ModelBufferGeometry.centroids. @param {Boolean=} options.localizeFaces If true, the positions for each face will be stored relative to the centroid. This is useful if you want to rotate or scale faces around their center. @constructor
[ "A", "THREE", ".", "BufferGeometry", "for", "animating", "individual", "faces", "of", "a", "THREE", ".", "Geometry", "." ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/dist/bas.module.js#L1112-L1138
8,873
zadvorsky/three.bas
examples/audio_visual/main.js
function (start, end) { var total = 0; start = start || 0; end = end || this.binCount; for (var i = start; i < end; i++) { total += this.frequencyByteData[i]; } return total / (end - start); }
javascript
function (start, end) { var total = 0; start = start || 0; end = end || this.binCount; for (var i = start; i < end; i++) { total += this.frequencyByteData[i]; } return total / (end - start); }
[ "function", "(", "start", ",", "end", ")", "{", "var", "total", "=", "0", ";", "start", "=", "start", "||", "0", ";", "end", "=", "end", "||", "this", ".", "binCount", ";", "for", "(", "var", "i", "=", "start", ";", "i", "<", "end", ";", "i", "++", ")", "{", "total", "+=", "this", ".", "frequencyByteData", "[", "i", "]", ";", "}", "return", "total", "/", "(", "end", "-", "start", ")", ";", "}" ]
not save if out of bounds
[ "not", "save", "if", "out", "of", "bounds" ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/examples/audio_visual/main.js#L331-L342
8,874
zadvorsky/three.bas
examples/points_animation/main.js
getRandomPointOnSphere
function getRandomPointOnSphere(r) { var u = THREE.Math.randFloat(0, 1); var v = THREE.Math.randFloat(0, 1); var theta = 2 * Math.PI * u; var phi = Math.acos(2 * v - 1); var x = r * Math.sin(theta) * Math.sin(phi); var y = r * Math.cos(theta) * Math.sin(phi); var z = r * Math.cos(phi); return { x, y, z, }; }
javascript
function getRandomPointOnSphere(r) { var u = THREE.Math.randFloat(0, 1); var v = THREE.Math.randFloat(0, 1); var theta = 2 * Math.PI * u; var phi = Math.acos(2 * v - 1); var x = r * Math.sin(theta) * Math.sin(phi); var y = r * Math.cos(theta) * Math.sin(phi); var z = r * Math.cos(phi); return { x, y, z, }; }
[ "function", "getRandomPointOnSphere", "(", "r", ")", "{", "var", "u", "=", "THREE", ".", "Math", ".", "randFloat", "(", "0", ",", "1", ")", ";", "var", "v", "=", "THREE", ".", "Math", ".", "randFloat", "(", "0", ",", "1", ")", ";", "var", "theta", "=", "2", "*", "Math", ".", "PI", "*", "u", ";", "var", "phi", "=", "Math", ".", "acos", "(", "2", "*", "v", "-", "1", ")", ";", "var", "x", "=", "r", "*", "Math", ".", "sin", "(", "theta", ")", "*", "Math", ".", "sin", "(", "phi", ")", ";", "var", "y", "=", "r", "*", "Math", ".", "cos", "(", "theta", ")", "*", "Math", ".", "sin", "(", "phi", ")", ";", "var", "z", "=", "r", "*", "Math", ".", "cos", "(", "phi", ")", ";", "return", "{", "x", ",", "y", ",", "z", ",", "}", ";", "}" ]
Get a random point on a sphere @param {Float} r Shpere radius @returns {Object} return the point's position
[ "Get", "a", "random", "point", "on", "a", "sphere" ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/examples/points_animation/main.js#L58-L71
8,875
zadvorsky/three.bas
examples/points_animation/main.js
getPointsOnPicture
function getPointsOnPicture(selector) { var img = document.querySelector(selector); var width = img.width; var height = img.height; var canvas = document.createElement('canvas'); document.body.appendChild(canvas); canvas.width = width; canvas.height = height; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); var imgData = ctx.getImageData(0, 0, width, height); var points = []; var xStep = 8; var yStep = 8; for (var x = 0; x < width; x += xStep) { for (var y = 0; y < height; y += yStep) { var i = (y * width + x) * 4; // not collect the points for alpha is zero if (imgData.data[i + 4] <= 0) { continue; } points.push({ x: x - width / 2, y: -(y - height / 2), z: 0, r: imgData.data[i] / 255, g: imgData.data[i + 1] / 255, b: imgData.data[i + 2] / 255, a: imgData.data[i + 3] / 255, }); } } return points; }
javascript
function getPointsOnPicture(selector) { var img = document.querySelector(selector); var width = img.width; var height = img.height; var canvas = document.createElement('canvas'); document.body.appendChild(canvas); canvas.width = width; canvas.height = height; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); var imgData = ctx.getImageData(0, 0, width, height); var points = []; var xStep = 8; var yStep = 8; for (var x = 0; x < width; x += xStep) { for (var y = 0; y < height; y += yStep) { var i = (y * width + x) * 4; // not collect the points for alpha is zero if (imgData.data[i + 4] <= 0) { continue; } points.push({ x: x - width / 2, y: -(y - height / 2), z: 0, r: imgData.data[i] / 255, g: imgData.data[i + 1] / 255, b: imgData.data[i + 2] / 255, a: imgData.data[i + 3] / 255, }); } } return points; }
[ "function", "getPointsOnPicture", "(", "selector", ")", "{", "var", "img", "=", "document", ".", "querySelector", "(", "selector", ")", ";", "var", "width", "=", "img", ".", "width", ";", "var", "height", "=", "img", ".", "height", ";", "var", "canvas", "=", "document", ".", "createElement", "(", "'canvas'", ")", ";", "document", ".", "body", ".", "appendChild", "(", "canvas", ")", ";", "canvas", ".", "width", "=", "width", ";", "canvas", ".", "height", "=", "height", ";", "var", "ctx", "=", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "ctx", ".", "drawImage", "(", "img", ",", "0", ",", "0", ",", "width", ",", "height", ")", ";", "var", "imgData", "=", "ctx", ".", "getImageData", "(", "0", ",", "0", ",", "width", ",", "height", ")", ";", "var", "points", "=", "[", "]", ";", "var", "xStep", "=", "8", ";", "var", "yStep", "=", "8", ";", "for", "(", "var", "x", "=", "0", ";", "x", "<", "width", ";", "x", "+=", "xStep", ")", "{", "for", "(", "var", "y", "=", "0", ";", "y", "<", "height", ";", "y", "+=", "yStep", ")", "{", "var", "i", "=", "(", "y", "*", "width", "+", "x", ")", "*", "4", ";", "// not collect the points for alpha is zero", "if", "(", "imgData", ".", "data", "[", "i", "+", "4", "]", "<=", "0", ")", "{", "continue", ";", "}", "points", ".", "push", "(", "{", "x", ":", "x", "-", "width", "/", "2", ",", "y", ":", "-", "(", "y", "-", "height", "/", "2", ")", ",", "z", ":", "0", ",", "r", ":", "imgData", ".", "data", "[", "i", "]", "/", "255", ",", "g", ":", "imgData", ".", "data", "[", "i", "+", "1", "]", "/", "255", ",", "b", ":", "imgData", ".", "data", "[", "i", "+", "2", "]", "/", "255", ",", "a", ":", "imgData", ".", "data", "[", "i", "+", "3", "]", "/", "255", ",", "}", ")", ";", "}", "}", "return", "points", ";", "}" ]
Translate a picture to a set of points @param {String} selector The DOM selector of image @returns {Array} return the set of points
[ "Translate", "a", "picture", "to", "a", "set", "of", "points" ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/examples/points_animation/main.js#L79-L117
8,876
zadvorsky/three.bas
dist/bas.js
BasicAnimationMaterial
function BasicAnimationMaterial(parameters) { this.varyingParameters = []; this.vertexParameters = []; this.vertexFunctions = []; this.vertexInit = []; this.vertexNormal = []; this.vertexPosition = []; this.vertexColor = []; this.vertexPostMorph = []; this.vertexPostSkinning = []; this.fragmentFunctions = []; this.fragmentParameters = []; this.fragmentInit = []; this.fragmentMap = []; this.fragmentDiffuse = []; BaseAnimationMaterial.call(this, parameters, three.ShaderLib['basic'].uniforms); this.lights = false; this.vertexShader = this.concatVertexShader(); this.fragmentShader = this.concatFragmentShader(); }
javascript
function BasicAnimationMaterial(parameters) { this.varyingParameters = []; this.vertexParameters = []; this.vertexFunctions = []; this.vertexInit = []; this.vertexNormal = []; this.vertexPosition = []; this.vertexColor = []; this.vertexPostMorph = []; this.vertexPostSkinning = []; this.fragmentFunctions = []; this.fragmentParameters = []; this.fragmentInit = []; this.fragmentMap = []; this.fragmentDiffuse = []; BaseAnimationMaterial.call(this, parameters, three.ShaderLib['basic'].uniforms); this.lights = false; this.vertexShader = this.concatVertexShader(); this.fragmentShader = this.concatFragmentShader(); }
[ "function", "BasicAnimationMaterial", "(", "parameters", ")", "{", "this", ".", "varyingParameters", "=", "[", "]", ";", "this", ".", "vertexParameters", "=", "[", "]", ";", "this", ".", "vertexFunctions", "=", "[", "]", ";", "this", ".", "vertexInit", "=", "[", "]", ";", "this", ".", "vertexNormal", "=", "[", "]", ";", "this", ".", "vertexPosition", "=", "[", "]", ";", "this", ".", "vertexColor", "=", "[", "]", ";", "this", ".", "vertexPostMorph", "=", "[", "]", ";", "this", ".", "vertexPostSkinning", "=", "[", "]", ";", "this", ".", "fragmentFunctions", "=", "[", "]", ";", "this", ".", "fragmentParameters", "=", "[", "]", ";", "this", ".", "fragmentInit", "=", "[", "]", ";", "this", ".", "fragmentMap", "=", "[", "]", ";", "this", ".", "fragmentDiffuse", "=", "[", "]", ";", "BaseAnimationMaterial", ".", "call", "(", "this", ",", "parameters", ",", "three", ".", "ShaderLib", "[", "'basic'", "]", ".", "uniforms", ")", ";", "this", ".", "lights", "=", "false", ";", "this", ".", "vertexShader", "=", "this", ".", "concatVertexShader", "(", ")", ";", "this", ".", "fragmentShader", "=", "this", ".", "concatFragmentShader", "(", ")", ";", "}" ]
Extends THREE.MeshBasicMaterial with custom shader chunks. @see http://three-bas-examples.surge.sh/examples/materials_basic/ @param {Object} parameters Object containing material properties and custom shader chunks. @constructor
[ "Extends", "THREE", ".", "MeshBasicMaterial", "with", "custom", "shader", "chunks", "." ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/dist/bas.js#L192-L215
8,877
zadvorsky/three.bas
dist/bas.js
PointsAnimationMaterial
function PointsAnimationMaterial(parameters) { this.varyingParameters = []; this.vertexFunctions = []; this.vertexParameters = []; this.vertexInit = []; this.vertexPosition = []; this.vertexColor = []; this.fragmentFunctions = []; this.fragmentParameters = []; this.fragmentInit = []; this.fragmentMap = []; this.fragmentDiffuse = []; // use fragment shader to shape to point, reference: https://thebookofshaders.com/07/ this.fragmentShape = []; BaseAnimationMaterial.call(this, parameters, three.ShaderLib['points'].uniforms); this.vertexShader = this.concatVertexShader(); this.fragmentShader = this.concatFragmentShader(); }
javascript
function PointsAnimationMaterial(parameters) { this.varyingParameters = []; this.vertexFunctions = []; this.vertexParameters = []; this.vertexInit = []; this.vertexPosition = []; this.vertexColor = []; this.fragmentFunctions = []; this.fragmentParameters = []; this.fragmentInit = []; this.fragmentMap = []; this.fragmentDiffuse = []; // use fragment shader to shape to point, reference: https://thebookofshaders.com/07/ this.fragmentShape = []; BaseAnimationMaterial.call(this, parameters, three.ShaderLib['points'].uniforms); this.vertexShader = this.concatVertexShader(); this.fragmentShader = this.concatFragmentShader(); }
[ "function", "PointsAnimationMaterial", "(", "parameters", ")", "{", "this", ".", "varyingParameters", "=", "[", "]", ";", "this", ".", "vertexFunctions", "=", "[", "]", ";", "this", ".", "vertexParameters", "=", "[", "]", ";", "this", ".", "vertexInit", "=", "[", "]", ";", "this", ".", "vertexPosition", "=", "[", "]", ";", "this", ".", "vertexColor", "=", "[", "]", ";", "this", ".", "fragmentFunctions", "=", "[", "]", ";", "this", ".", "fragmentParameters", "=", "[", "]", ";", "this", ".", "fragmentInit", "=", "[", "]", ";", "this", ".", "fragmentMap", "=", "[", "]", ";", "this", ".", "fragmentDiffuse", "=", "[", "]", ";", "// use fragment shader to shape to point, reference: https://thebookofshaders.com/07/", "this", ".", "fragmentShape", "=", "[", "]", ";", "BaseAnimationMaterial", ".", "call", "(", "this", ",", "parameters", ",", "three", ".", "ShaderLib", "[", "'points'", "]", ".", "uniforms", ")", ";", "this", ".", "vertexShader", "=", "this", ".", "concatVertexShader", "(", ")", ";", "this", ".", "fragmentShader", "=", "this", ".", "concatFragmentShader", "(", ")", ";", "}" ]
Extends THREE.PointsMaterial with custom shader chunks. @param {Object} parameters Object containing material properties and custom shader chunks. @constructor
[ "Extends", "THREE", ".", "PointsMaterial", "with", "custom", "shader", "chunks", "." ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/dist/bas.js#L384-L405
8,878
zadvorsky/three.bas
dist/bas.js
PrefabBufferGeometry
function PrefabBufferGeometry(prefab, count) { three.BufferGeometry.call(this); /** * A reference to the prefab geometry used to create this instance. * @type {Geometry|BufferGeometry} */ this.prefabGeometry = prefab; this.isPrefabBufferGeometry = prefab.isBufferGeometry; /** * Number of prefabs. * @type {Number} */ this.prefabCount = count; /** * Number of vertices of the prefab. * @type {Number} */ if (this.isPrefabBufferGeometry) { this.prefabVertexCount = prefab.attributes.position.count; } else { this.prefabVertexCount = prefab.vertices.length; } this.bufferIndices(); this.bufferPositions(); }
javascript
function PrefabBufferGeometry(prefab, count) { three.BufferGeometry.call(this); /** * A reference to the prefab geometry used to create this instance. * @type {Geometry|BufferGeometry} */ this.prefabGeometry = prefab; this.isPrefabBufferGeometry = prefab.isBufferGeometry; /** * Number of prefabs. * @type {Number} */ this.prefabCount = count; /** * Number of vertices of the prefab. * @type {Number} */ if (this.isPrefabBufferGeometry) { this.prefabVertexCount = prefab.attributes.position.count; } else { this.prefabVertexCount = prefab.vertices.length; } this.bufferIndices(); this.bufferPositions(); }
[ "function", "PrefabBufferGeometry", "(", "prefab", ",", "count", ")", "{", "three", ".", "BufferGeometry", ".", "call", "(", "this", ")", ";", "/**\n * A reference to the prefab geometry used to create this instance.\n * @type {Geometry|BufferGeometry}\n */", "this", ".", "prefabGeometry", "=", "prefab", ";", "this", ".", "isPrefabBufferGeometry", "=", "prefab", ".", "isBufferGeometry", ";", "/**\n * Number of prefabs.\n * @type {Number}\n */", "this", ".", "prefabCount", "=", "count", ";", "/**\n * Number of vertices of the prefab.\n * @type {Number}\n */", "if", "(", "this", ".", "isPrefabBufferGeometry", ")", "{", "this", ".", "prefabVertexCount", "=", "prefab", ".", "attributes", ".", "position", ".", "count", ";", "}", "else", "{", "this", ".", "prefabVertexCount", "=", "prefab", ".", "vertices", ".", "length", ";", "}", "this", ".", "bufferIndices", "(", ")", ";", "this", ".", "bufferPositions", "(", ")", ";", "}" ]
A BufferGeometry where a 'prefab' geometry is repeated a number of times. @param {Geometry|BufferGeometry} prefab The Geometry instance to repeat. @param {Number} count The number of times to repeat the geometry. @constructor
[ "A", "BufferGeometry", "where", "a", "prefab", "geometry", "is", "repeated", "a", "number", "of", "times", "." ]
e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44
https://github.com/zadvorsky/three.bas/blob/e29194aae319c6b3dbd6e4a72ad6c9fa0fe67f44/dist/bas.js#L474-L502
8,879
OpenVidu/openvidu
openvidu-browser/src/OpenViduInternal/KurentoUtils/kurento-jsonrpc/index.js
RpcNotification
function RpcNotification(method, params) { if(defineProperty_IE8) { this.method = method this.params = params } else { Object.defineProperty(this, 'method', {value: method, enumerable: true}); Object.defineProperty(this, 'params', {value: params, enumerable: true}); } }
javascript
function RpcNotification(method, params) { if(defineProperty_IE8) { this.method = method this.params = params } else { Object.defineProperty(this, 'method', {value: method, enumerable: true}); Object.defineProperty(this, 'params', {value: params, enumerable: true}); } }
[ "function", "RpcNotification", "(", "method", ",", "params", ")", "{", "if", "(", "defineProperty_IE8", ")", "{", "this", ".", "method", "=", "method", "this", ".", "params", "=", "params", "}", "else", "{", "Object", ".", "defineProperty", "(", "this", ",", "'method'", ",", "{", "value", ":", "method", ",", "enumerable", ":", "true", "}", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'params'", ",", "{", "value", ":", "params", ",", "enumerable", ":", "true", "}", ")", ";", "}", "}" ]
Representation of a RPC notification @class @constructor @param {String} method -method of the notification @param params - parameters of the notification
[ "Representation", "of", "a", "RPC", "notification" ]
89db47dd37949ceab29e5228371a8fcab04d8d55
https://github.com/OpenVidu/openvidu/blob/89db47dd37949ceab29e5228371a8fcab04d8d55/openvidu-browser/src/OpenViduInternal/KurentoUtils/kurento-jsonrpc/index.js#L132-L144
8,880
OpenVidu/openvidu
openvidu-browser/src/OpenViduInternal/KurentoUtils/kurento-jsonrpc/index.js
storeResponse
function storeResponse(message, id, dest) { var response = { message: message, /** Timeout to auto-clean old responses */ timeout: setTimeout(function() { responses.remove(id, dest); }, response_timeout) }; responses.set(response, id, dest); }
javascript
function storeResponse(message, id, dest) { var response = { message: message, /** Timeout to auto-clean old responses */ timeout: setTimeout(function() { responses.remove(id, dest); }, response_timeout) }; responses.set(response, id, dest); }
[ "function", "storeResponse", "(", "message", ",", "id", ",", "dest", ")", "{", "var", "response", "=", "{", "message", ":", "message", ",", "/** Timeout to auto-clean old responses */", "timeout", ":", "setTimeout", "(", "function", "(", ")", "{", "responses", ".", "remove", "(", "id", ",", "dest", ")", ";", "}", ",", "response_timeout", ")", "}", ";", "responses", ".", "set", "(", "response", ",", "id", ",", "dest", ")", ";", "}" ]
Store the response to prevent to process duplicate request later
[ "Store", "the", "response", "to", "prevent", "to", "process", "duplicate", "request", "later" ]
89db47dd37949ceab29e5228371a8fcab04d8d55
https://github.com/OpenVidu/openvidu/blob/89db47dd37949ceab29e5228371a8fcab04d8d55/openvidu-browser/src/OpenViduInternal/KurentoUtils/kurento-jsonrpc/index.js#L289-L303
8,881
OpenVidu/openvidu
openvidu-browser/src/OpenViduInternal/KurentoUtils/kurento-jsonrpc/index.js
storeProcessedResponse
function storeProcessedResponse(ack, from) { var timeout = setTimeout(function() { processedResponses.remove(ack, from); }, duplicates_timeout); processedResponses.set(timeout, ack, from); }
javascript
function storeProcessedResponse(ack, from) { var timeout = setTimeout(function() { processedResponses.remove(ack, from); }, duplicates_timeout); processedResponses.set(timeout, ack, from); }
[ "function", "storeProcessedResponse", "(", "ack", ",", "from", ")", "{", "var", "timeout", "=", "setTimeout", "(", "function", "(", ")", "{", "processedResponses", ".", "remove", "(", "ack", ",", "from", ")", ";", "}", ",", "duplicates_timeout", ")", ";", "processedResponses", ".", "set", "(", "timeout", ",", "ack", ",", "from", ")", ";", "}" ]
Store the response to ignore duplicated messages later
[ "Store", "the", "response", "to", "ignore", "duplicated", "messages", "later" ]
89db47dd37949ceab29e5228371a8fcab04d8d55
https://github.com/OpenVidu/openvidu/blob/89db47dd37949ceab29e5228371a8fcab04d8d55/openvidu-browser/src/OpenViduInternal/KurentoUtils/kurento-jsonrpc/index.js#L308-L317
8,882
midwayjs/midway
packages/midway-init/boilerplate/midway-ts-ant-design-pro-boilerplate/boilerplate/client/src/models/menu.js
formatter
function formatter(data, parentAuthority, parentName) { if (!data) { return undefined; } return data .map(item => { if (!item.name || !item.path) { return null; } let locale = 'menu'; if (parentName && parentName !== '/') { locale = `${parentName}.${item.name}`; } else { locale = `menu.${item.name}`; } const result = { ...item, title:locale }; if (item.routes) { const children = formatter(item.routes, item.authority, locale); // Reduce memory usage result.children = children; } delete result.routes; return result; }) .filter(item => item); }
javascript
function formatter(data, parentAuthority, parentName) { if (!data) { return undefined; } return data .map(item => { if (!item.name || !item.path) { return null; } let locale = 'menu'; if (parentName && parentName !== '/') { locale = `${parentName}.${item.name}`; } else { locale = `menu.${item.name}`; } const result = { ...item, title:locale }; if (item.routes) { const children = formatter(item.routes, item.authority, locale); // Reduce memory usage result.children = children; } delete result.routes; return result; }) .filter(item => item); }
[ "function", "formatter", "(", "data", ",", "parentAuthority", ",", "parentName", ")", "{", "if", "(", "!", "data", ")", "{", "return", "undefined", ";", "}", "return", "data", ".", "map", "(", "item", "=>", "{", "if", "(", "!", "item", ".", "name", "||", "!", "item", ".", "path", ")", "{", "return", "null", ";", "}", "let", "locale", "=", "'menu'", ";", "if", "(", "parentName", "&&", "parentName", "!==", "'/'", ")", "{", "locale", "=", "`", "${", "parentName", "}", "${", "item", ".", "name", "}", "`", ";", "}", "else", "{", "locale", "=", "`", "${", "item", ".", "name", "}", "`", ";", "}", "const", "result", "=", "{", "...", "item", ",", "title", ":", "locale", "}", ";", "if", "(", "item", ".", "routes", ")", "{", "const", "children", "=", "formatter", "(", "item", ".", "routes", ",", "item", ".", "authority", ",", "locale", ")", ";", "// Reduce memory usage", "result", ".", "children", "=", "children", ";", "}", "delete", "result", ".", "routes", ";", "return", "result", ";", "}", ")", ".", "filter", "(", "item", "=>", "item", ")", ";", "}" ]
Conversion router to menu.
[ "Conversion", "router", "to", "menu", "." ]
e7aeb80dedc31d25d8ac0fbe5a789062a7da5eb8
https://github.com/midwayjs/midway/blob/e7aeb80dedc31d25d8ac0fbe5a789062a7da5eb8/packages/midway-init/boilerplate/midway-ts-ant-design-pro-boilerplate/boilerplate/client/src/models/menu.js#L5-L34
8,883
geotiffjs/geotiff.js
src/compression/lzw.js
getByte
function getByte(array, position, length) { const d = position % 8; const a = Math.floor(position / 8); const de = 8 - d; const ef = (position + length) - ((a + 1) * 8); let fg = (8 * (a + 2)) - (position + length); const dg = ((a + 2) * 8) - position; fg = Math.max(0, fg); if (a >= array.length) { console.warn('ran off the end of the buffer before finding EOI_CODE (end on input code)'); return EOI_CODE; } let chunk1 = array[a] & ((2 ** (8 - d)) - 1); chunk1 <<= (length - de); let chunks = chunk1; if (a + 1 < array.length) { let chunk2 = array[a + 1] >>> fg; chunk2 <<= Math.max(0, (length - dg)); chunks += chunk2; } if (ef > 8 && a + 2 < array.length) { const hi = ((a + 3) * 8) - (position + length); const chunk3 = array[a + 2] >>> hi; chunks += chunk3; } return chunks; }
javascript
function getByte(array, position, length) { const d = position % 8; const a = Math.floor(position / 8); const de = 8 - d; const ef = (position + length) - ((a + 1) * 8); let fg = (8 * (a + 2)) - (position + length); const dg = ((a + 2) * 8) - position; fg = Math.max(0, fg); if (a >= array.length) { console.warn('ran off the end of the buffer before finding EOI_CODE (end on input code)'); return EOI_CODE; } let chunk1 = array[a] & ((2 ** (8 - d)) - 1); chunk1 <<= (length - de); let chunks = chunk1; if (a + 1 < array.length) { let chunk2 = array[a + 1] >>> fg; chunk2 <<= Math.max(0, (length - dg)); chunks += chunk2; } if (ef > 8 && a + 2 < array.length) { const hi = ((a + 3) * 8) - (position + length); const chunk3 = array[a + 2] >>> hi; chunks += chunk3; } return chunks; }
[ "function", "getByte", "(", "array", ",", "position", ",", "length", ")", "{", "const", "d", "=", "position", "%", "8", ";", "const", "a", "=", "Math", ".", "floor", "(", "position", "/", "8", ")", ";", "const", "de", "=", "8", "-", "d", ";", "const", "ef", "=", "(", "position", "+", "length", ")", "-", "(", "(", "a", "+", "1", ")", "*", "8", ")", ";", "let", "fg", "=", "(", "8", "*", "(", "a", "+", "2", ")", ")", "-", "(", "position", "+", "length", ")", ";", "const", "dg", "=", "(", "(", "a", "+", "2", ")", "*", "8", ")", "-", "position", ";", "fg", "=", "Math", ".", "max", "(", "0", ",", "fg", ")", ";", "if", "(", "a", ">=", "array", ".", "length", ")", "{", "console", ".", "warn", "(", "'ran off the end of the buffer before finding EOI_CODE (end on input code)'", ")", ";", "return", "EOI_CODE", ";", "}", "let", "chunk1", "=", "array", "[", "a", "]", "&", "(", "(", "2", "**", "(", "8", "-", "d", ")", ")", "-", "1", ")", ";", "chunk1", "<<=", "(", "length", "-", "de", ")", ";", "let", "chunks", "=", "chunk1", ";", "if", "(", "a", "+", "1", "<", "array", ".", "length", ")", "{", "let", "chunk2", "=", "array", "[", "a", "+", "1", "]", ">>>", "fg", ";", "chunk2", "<<=", "Math", ".", "max", "(", "0", ",", "(", "length", "-", "dg", ")", ")", ";", "chunks", "+=", "chunk2", ";", "}", "if", "(", "ef", ">", "8", "&&", "a", "+", "2", "<", "array", ".", "length", ")", "{", "const", "hi", "=", "(", "(", "a", "+", "3", ")", "*", "8", ")", "-", "(", "position", "+", "length", ")", ";", "const", "chunk3", "=", "array", "[", "a", "+", "2", "]", ">>>", "hi", ";", "chunks", "+=", "chunk3", ";", "}", "return", "chunks", ";", "}" ]
end of information
[ "end", "of", "information" ]
b2ac9467b943836664f10730676adcd3cef5a544
https://github.com/geotiffjs/geotiff.js/blob/b2ac9467b943836664f10730676adcd3cef5a544/src/compression/lzw.js#L8-L34
8,884
easysoft/zui
dist/js/zui.js
function(element, options) { var that = this; that.name = NAME; that.$ = $(element); options = that.options = $.extend({}, Pager.DEFAULTS, this.$.data(), options); var lang = options.lang || $.zui.clientLang(); that.lang = $.isPlainObject(lang) ? ($.extend(true, {}, LANG[lang.lang || $.zui.clientLang()], lang)) : LANG[lang]; that.state = {}; that.set(options.page, options.recTotal, options.recPerPage, true); that.$.on('click', '.pager-goto-btn', function() { var $goto = $(this).closest('.pager-goto'); var page = parseInt($goto.find('.pager-goto-input').val()); if (page !== NaN) { that.set(page); } }).on('click', '.pager-item', function() { var page = $(this).data('page'); if (typeof page === 'number' && page > 0) { that.set(page); } }).on('click', '.pager-size-menu [data-size]', function() { var size = $(this).data('size'); if (typeof size === 'number' && size > 0) { that.set(-1, -1, size); } }); }
javascript
function(element, options) { var that = this; that.name = NAME; that.$ = $(element); options = that.options = $.extend({}, Pager.DEFAULTS, this.$.data(), options); var lang = options.lang || $.zui.clientLang(); that.lang = $.isPlainObject(lang) ? ($.extend(true, {}, LANG[lang.lang || $.zui.clientLang()], lang)) : LANG[lang]; that.state = {}; that.set(options.page, options.recTotal, options.recPerPage, true); that.$.on('click', '.pager-goto-btn', function() { var $goto = $(this).closest('.pager-goto'); var page = parseInt($goto.find('.pager-goto-input').val()); if (page !== NaN) { that.set(page); } }).on('click', '.pager-item', function() { var page = $(this).data('page'); if (typeof page === 'number' && page > 0) { that.set(page); } }).on('click', '.pager-size-menu [data-size]', function() { var size = $(this).data('size'); if (typeof size === 'number' && size > 0) { that.set(-1, -1, size); } }); }
[ "function", "(", "element", ",", "options", ")", "{", "var", "that", "=", "this", ";", "that", ".", "name", "=", "NAME", ";", "that", ".", "$", "=", "$", "(", "element", ")", ";", "options", "=", "that", ".", "options", "=", "$", ".", "extend", "(", "{", "}", ",", "Pager", ".", "DEFAULTS", ",", "this", ".", "$", ".", "data", "(", ")", ",", "options", ")", ";", "var", "lang", "=", "options", ".", "lang", "||", "$", ".", "zui", ".", "clientLang", "(", ")", ";", "that", ".", "lang", "=", "$", ".", "isPlainObject", "(", "lang", ")", "?", "(", "$", ".", "extend", "(", "true", ",", "{", "}", ",", "LANG", "[", "lang", ".", "lang", "||", "$", ".", "zui", ".", "clientLang", "(", ")", "]", ",", "lang", ")", ")", ":", "LANG", "[", "lang", "]", ";", "that", ".", "state", "=", "{", "}", ";", "that", ".", "set", "(", "options", ".", "page", ",", "options", ".", "recTotal", ",", "options", ".", "recPerPage", ",", "true", ")", ";", "that", ".", "$", ".", "on", "(", "'click'", ",", "'.pager-goto-btn'", ",", "function", "(", ")", "{", "var", "$goto", "=", "$", "(", "this", ")", ".", "closest", "(", "'.pager-goto'", ")", ";", "var", "page", "=", "parseInt", "(", "$goto", ".", "find", "(", "'.pager-goto-input'", ")", ".", "val", "(", ")", ")", ";", "if", "(", "page", "!==", "NaN", ")", "{", "that", ".", "set", "(", "page", ")", ";", "}", "}", ")", ".", "on", "(", "'click'", ",", "'.pager-item'", ",", "function", "(", ")", "{", "var", "page", "=", "$", "(", "this", ")", ".", "data", "(", "'page'", ")", ";", "if", "(", "typeof", "page", "===", "'number'", "&&", "page", ">", "0", ")", "{", "that", ".", "set", "(", "page", ")", ";", "}", "}", ")", ".", "on", "(", "'click'", ",", "'.pager-size-menu [data-size]'", ",", "function", "(", ")", "{", "var", "size", "=", "$", "(", "this", ")", ".", "data", "(", "'size'", ")", ";", "if", "(", "typeof", "size", "===", "'number'", "&&", "size", ">", "0", ")", "{", "that", ".", "set", "(", "-", "1", ",", "-", "1", ",", "size", ")", ";", "}", "}", ")", ";", "}" ]
The pager model class
[ "The", "pager", "model", "class" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/dist/js/zui.js#L434-L465
8,885
easysoft/zui
dist/js/zui.js
function () { var ie = this.isIE() || this.isIE10() || false; if (ie) { for (var i = 10; i > 5; i--) { if (this.isIE(i)) { ie = i; break; } } } this.ie = ie; this.cssHelper(); }
javascript
function () { var ie = this.isIE() || this.isIE10() || false; if (ie) { for (var i = 10; i > 5; i--) { if (this.isIE(i)) { ie = i; break; } } } this.ie = ie; this.cssHelper(); }
[ "function", "(", ")", "{", "var", "ie", "=", "this", ".", "isIE", "(", ")", "||", "this", ".", "isIE10", "(", ")", "||", "false", ";", "if", "(", "ie", ")", "{", "for", "(", "var", "i", "=", "10", ";", "i", ">", "5", ";", "i", "--", ")", "{", "if", "(", "this", ".", "isIE", "(", "i", ")", ")", "{", "ie", "=", "i", ";", "break", ";", "}", "}", "}", "this", ".", "ie", "=", "ie", ";", "this", ".", "cssHelper", "(", ")", ";", "}" ]
The browser modal class
[ "The", "browser", "modal", "class" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/dist/js/zui.js#L1207-L1221
8,886
easysoft/zui
dist/js/zui.js
function() { // Since window has its own native 'resize' event, return false so that // jQuery will bind the event using DOM methods. Since only 'window' // objects have a .setTimeout method, this should be a sufficient test. // Unless, of course, we're throttling the 'resize' event for window. if(!jq_resize[str_throttle] && this[str_setTimeout]) { return false; } var elem = $(this); // Add this element to the list of internal elements to monitor. elems = elems.add(elem); // Initialize data store on the element. $.data(this, str_data, { w: elem.width(), h: elem.height() }); // If this is the first element added, start the polling loop. if(elems.length === 1) { loopy(); } }
javascript
function() { // Since window has its own native 'resize' event, return false so that // jQuery will bind the event using DOM methods. Since only 'window' // objects have a .setTimeout method, this should be a sufficient test. // Unless, of course, we're throttling the 'resize' event for window. if(!jq_resize[str_throttle] && this[str_setTimeout]) { return false; } var elem = $(this); // Add this element to the list of internal elements to monitor. elems = elems.add(elem); // Initialize data store on the element. $.data(this, str_data, { w: elem.width(), h: elem.height() }); // If this is the first element added, start the polling loop. if(elems.length === 1) { loopy(); } }
[ "function", "(", ")", "{", "// Since window has its own native 'resize' event, return false so that", "// jQuery will bind the event using DOM methods. Since only 'window'", "// objects have a .setTimeout method, this should be a sufficient test.", "// Unless, of course, we're throttling the 'resize' event for window.", "if", "(", "!", "jq_resize", "[", "str_throttle", "]", "&&", "this", "[", "str_setTimeout", "]", ")", "{", "return", "false", ";", "}", "var", "elem", "=", "$", "(", "this", ")", ";", "// Add this element to the list of internal elements to monitor.", "elems", "=", "elems", ".", "add", "(", "elem", ")", ";", "// Initialize data store on the element.", "$", ".", "data", "(", "this", ",", "str_data", ",", "{", "w", ":", "elem", ".", "width", "(", ")", ",", "h", ":", "elem", ".", "height", "(", ")", "}", ")", ";", "// If this is the first element added, start the polling loop.", "if", "(", "elems", ".", "length", "===", "1", ")", "{", "loopy", "(", ")", ";", "}", "}" ]
Called only when the first 'resize' event callback is bound per element.
[ "Called", "only", "when", "the", "first", "resize", "event", "callback", "is", "bound", "per", "element", "." ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/dist/js/zui.js#L1757-L1781
8,887
easysoft/zui
dist/js/zui.js
function() { // Since window has its own native 'resize' event, return false so that // jQuery will unbind the event using DOM methods. Since only 'window' // objects have a .setTimeout method, this should be a sufficient test. // Unless, of course, we're throttling the 'resize' event for window. if(!jq_resize[str_throttle] && this[str_setTimeout]) { return false; } var elem = $(this); // Remove this element from the list of internal elements to monitor. elems = elems.not(elem); // Remove any data stored on the element. elem.removeData(str_data); // If this is the last element removed, stop the polling loop. if(!elems.length) { clearTimeout(timeout_id); } }
javascript
function() { // Since window has its own native 'resize' event, return false so that // jQuery will unbind the event using DOM methods. Since only 'window' // objects have a .setTimeout method, this should be a sufficient test. // Unless, of course, we're throttling the 'resize' event for window. if(!jq_resize[str_throttle] && this[str_setTimeout]) { return false; } var elem = $(this); // Remove this element from the list of internal elements to monitor. elems = elems.not(elem); // Remove any data stored on the element. elem.removeData(str_data); // If this is the last element removed, stop the polling loop. if(!elems.length) { clearTimeout(timeout_id); } }
[ "function", "(", ")", "{", "// Since window has its own native 'resize' event, return false so that", "// jQuery will unbind the event using DOM methods. Since only 'window'", "// objects have a .setTimeout method, this should be a sufficient test.", "// Unless, of course, we're throttling the 'resize' event for window.", "if", "(", "!", "jq_resize", "[", "str_throttle", "]", "&&", "this", "[", "str_setTimeout", "]", ")", "{", "return", "false", ";", "}", "var", "elem", "=", "$", "(", "this", ")", ";", "// Remove this element from the list of internal elements to monitor.", "elems", "=", "elems", ".", "not", "(", "elem", ")", ";", "// Remove any data stored on the element.", "elem", ".", "removeData", "(", "str_data", ")", ";", "// If this is the last element removed, stop the polling loop.", "if", "(", "!", "elems", ".", "length", ")", "{", "clearTimeout", "(", "timeout_id", ")", ";", "}", "}" ]
Called only when the last 'resize' event callback is unbound per element.
[ "Called", "only", "when", "the", "last", "resize", "event", "callback", "is", "unbound", "per", "element", "." ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/dist/js/zui.js#L1784-L1805
8,888
easysoft/zui
dist/js/zui.js
new_handler
function new_handler(e, w, h) { var elem = $(this), data = $.data(this, str_data) || {}; // If called from the polling loop, w and h will be passed in as // arguments. If called manually, via .trigger( 'resize' ) or .resize(), // those values will need to be computed. data.w = w !== undefined ? w : elem.width(); data.h = h !== undefined ? h : elem.height(); old_handler.apply(this, arguments); }
javascript
function new_handler(e, w, h) { var elem = $(this), data = $.data(this, str_data) || {}; // If called from the polling loop, w and h will be passed in as // arguments. If called manually, via .trigger( 'resize' ) or .resize(), // those values will need to be computed. data.w = w !== undefined ? w : elem.width(); data.h = h !== undefined ? h : elem.height(); old_handler.apply(this, arguments); }
[ "function", "new_handler", "(", "e", ",", "w", ",", "h", ")", "{", "var", "elem", "=", "$", "(", "this", ")", ",", "data", "=", "$", ".", "data", "(", "this", ",", "str_data", ")", "||", "{", "}", ";", "// If called from the polling loop, w and h will be passed in as", "// arguments. If called manually, via .trigger( 'resize' ) or .resize(),", "// those values will need to be computed.", "data", ".", "w", "=", "w", "!==", "undefined", "?", "w", ":", "elem", ".", "width", "(", ")", ";", "data", ".", "h", "=", "h", "!==", "undefined", "?", "h", ":", "elem", ".", "height", "(", ")", ";", "old_handler", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}" ]
The new_handler function is executed every time the event is triggered. This is used to update the internal element data store with the width and height when the event is triggered manually, to avoid double-firing of the event callback. See the "Double firing issue in jQuery 1.3.2" comments above for more information.
[ "The", "new_handler", "function", "is", "executed", "every", "time", "the", "event", "is", "triggered", ".", "This", "is", "used", "to", "update", "the", "internal", "element", "data", "store", "with", "the", "width", "and", "height", "when", "the", "event", "is", "triggered", "manually", "to", "avoid", "double", "-", "firing", "of", "the", "event", "callback", ".", "See", "the", "Double", "firing", "issue", "in", "jQuery", "1", ".", "3", ".", "2", "comments", "above", "for", "more", "information", "." ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/dist/js/zui.js#L1825-L1836
8,889
easysoft/zui
dist/js/zui.js
function(modal, callback, redirect) { var originModal = modal; if($.isFunction(modal)) { var oldModal = redirect; redirect = callback; callback = modal; modal = oldModal; } modal = getModal(modal); if(modal && modal.length) { modal.each(function() { $(this).data(NAME).close(callback, redirect); }); } else if(!$('body').hasClass('modal-open') && !$('.modal.in').length) { // check if current page is as modal iframe if ($('body').hasClass('body-modal')) { window.parent.$.zui.closeModal(originModal, callback, redirect); } } }
javascript
function(modal, callback, redirect) { var originModal = modal; if($.isFunction(modal)) { var oldModal = redirect; redirect = callback; callback = modal; modal = oldModal; } modal = getModal(modal); if(modal && modal.length) { modal.each(function() { $(this).data(NAME).close(callback, redirect); }); } else if(!$('body').hasClass('modal-open') && !$('.modal.in').length) { // check if current page is as modal iframe if ($('body').hasClass('body-modal')) { window.parent.$.zui.closeModal(originModal, callback, redirect); } } }
[ "function", "(", "modal", ",", "callback", ",", "redirect", ")", "{", "var", "originModal", "=", "modal", ";", "if", "(", "$", ".", "isFunction", "(", "modal", ")", ")", "{", "var", "oldModal", "=", "redirect", ";", "redirect", "=", "callback", ";", "callback", "=", "modal", ";", "modal", "=", "oldModal", ";", "}", "modal", "=", "getModal", "(", "modal", ")", ";", "if", "(", "modal", "&&", "modal", ".", "length", ")", "{", "modal", ".", "each", "(", "function", "(", ")", "{", "$", "(", "this", ")", ".", "data", "(", "NAME", ")", ".", "close", "(", "callback", ",", "redirect", ")", ";", "}", ")", ";", "}", "else", "if", "(", "!", "$", "(", "'body'", ")", ".", "hasClass", "(", "'modal-open'", ")", "&&", "!", "$", "(", "'.modal.in'", ")", ".", "length", ")", "{", "// check if current page is as modal iframe", "if", "(", "$", "(", "'body'", ")", ".", "hasClass", "(", "'body-modal'", ")", ")", "{", "window", ".", "parent", ".", "$", ".", "zui", ".", "closeModal", "(", "originModal", ",", "callback", ",", "redirect", ")", ";", "}", "}", "}" ]
callback, redirect, modal
[ "callback", "redirect", "modal" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/dist/js/zui.js#L3779-L3798
8,890
easysoft/zui
dist/js/zui.js
function(element, options) { var that = this; that.name = NAME; that.$ = $(element); options = that.options = $.extend({trigger: 'contextmenu'}, ContextMenu.DEFAULTS, this.$.data(), options); var trigger = options.trigger; that.id = $.zui.uuid(); var eventHandler = function(e) { if (e.type === 'mousedown' && e.button !== 2) { return; } var config = { x: e.clientX, y: e.clientY, event: e }; if (options.itemsCreator) { config.items = options.itemsCreator.call(this, e); } that.show(config); e.preventDefault(); e.returnValue = false; // 解决IE8右键弹出 return false; }; var eventName = trigger + '.' + NAME; if (options.selector) { that.$.on(eventName, options.selector, eventHandler); } else { that.$.on(eventName, eventHandler); } }
javascript
function(element, options) { var that = this; that.name = NAME; that.$ = $(element); options = that.options = $.extend({trigger: 'contextmenu'}, ContextMenu.DEFAULTS, this.$.data(), options); var trigger = options.trigger; that.id = $.zui.uuid(); var eventHandler = function(e) { if (e.type === 'mousedown' && e.button !== 2) { return; } var config = { x: e.clientX, y: e.clientY, event: e }; if (options.itemsCreator) { config.items = options.itemsCreator.call(this, e); } that.show(config); e.preventDefault(); e.returnValue = false; // 解决IE8右键弹出 return false; }; var eventName = trigger + '.' + NAME; if (options.selector) { that.$.on(eventName, options.selector, eventHandler); } else { that.$.on(eventName, eventHandler); } }
[ "function", "(", "element", ",", "options", ")", "{", "var", "that", "=", "this", ";", "that", ".", "name", "=", "NAME", ";", "that", ".", "$", "=", "$", "(", "element", ")", ";", "options", "=", "that", ".", "options", "=", "$", ".", "extend", "(", "{", "trigger", ":", "'contextmenu'", "}", ",", "ContextMenu", ".", "DEFAULTS", ",", "this", ".", "$", ".", "data", "(", ")", ",", "options", ")", ";", "var", "trigger", "=", "options", ".", "trigger", ";", "that", ".", "id", "=", "$", ".", "zui", ".", "uuid", "(", ")", ";", "var", "eventHandler", "=", "function", "(", "e", ")", "{", "if", "(", "e", ".", "type", "===", "'mousedown'", "&&", "e", ".", "button", "!==", "2", ")", "{", "return", ";", "}", "var", "config", "=", "{", "x", ":", "e", ".", "clientX", ",", "y", ":", "e", ".", "clientY", ",", "event", ":", "e", "}", ";", "if", "(", "options", ".", "itemsCreator", ")", "{", "config", ".", "items", "=", "options", ".", "itemsCreator", ".", "call", "(", "this", ",", "e", ")", ";", "}", "that", ".", "show", "(", "config", ")", ";", "e", ".", "preventDefault", "(", ")", ";", "e", ".", "returnValue", "=", "false", ";", "// 解决IE8右键弹出", "return", "false", ";", "}", ";", "var", "eventName", "=", "trigger", "+", "'.'", "+", "NAME", ";", "if", "(", "options", ".", "selector", ")", "{", "that", ".", "$", ".", "on", "(", "eventName", ",", "options", ".", "selector", ",", "eventHandler", ")", ";", "}", "else", "{", "that", ".", "$", ".", "on", "(", "eventName", ",", "eventHandler", ")", ";", "}", "}" ]
The contextmenu model class
[ "The", "contextmenu", "model", "class" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/dist/js/zui.js#L4781-L4814
8,891
easysoft/zui
assets/live.js
function () { if (document.body) { // make sure all resources are loaded on first activation if (!loaded) Live.loadresources(); Live.checkForChanges(); } setTimeout(Live.heartbeat, interval); }
javascript
function () { if (document.body) { // make sure all resources are loaded on first activation if (!loaded) Live.loadresources(); Live.checkForChanges(); } setTimeout(Live.heartbeat, interval); }
[ "function", "(", ")", "{", "if", "(", "document", ".", "body", ")", "{", "// make sure all resources are loaded on first activation\r", "if", "(", "!", "loaded", ")", "Live", ".", "loadresources", "(", ")", ";", "Live", ".", "checkForChanges", "(", ")", ";", "}", "setTimeout", "(", "Live", ".", "heartbeat", ",", "interval", ")", ";", "}" ]
performs a cycle per interval
[ "performs", "a", "cycle", "per", "interval" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/assets/live.js#L37-L44
8,892
easysoft/zui
assets/live.js
function () { // helper method to assert if a given url is local function isLocal(url) { var loc = document.location, reg = new RegExp("^\\.|^\/(?!\/)|^[\\w]((?!://).)*$|" + loc.protocol + "//" + loc.host); return url.match(reg); } // gather all resources var scripts = document.getElementsByTagName("script"), links = document.getElementsByTagName("link"), uris = []; // track local js urls for (var i = 0; i < scripts.length; i++) { var script = scripts[i], src = script.getAttribute("src"); if (src && isLocal(src)) uris.push(src); if (src && src.match(/\blive.js#/)) { for (var type in active) active[type] = src.match("[#,|]" + type) != null if (src.match("notify")) alert("Live.js is loaded."); } } if (!active.js) uris = []; if (active.html) uris.push(document.location.href); // track local css urls for (var i = 0; i < links.length && active.css; i++) { var link = links[i], rel = link.getAttribute("rel"), href = link.getAttribute("href", 2); if (href && rel && rel.match(new RegExp("stylesheet", "i")) && isLocal(href)) { uris.push(href); currentLinkElements[href] = link; } } // initialize the resources info for (var i = 0; i < uris.length; i++) { var url = uris[i]; Live.getHead(url, function (url, info) { resources[url] = info; }); } // add rule for morphing between old and new css files var head = document.getElementsByTagName("head")[0], style = document.createElement("style"), rule = "transition: all .3s ease-out;" css = [".livejs-loading * { ", rule, " -webkit-", rule, "-moz-", rule, "-o-", rule, "}"].join(''); style.setAttribute("type", "text/css"); head.appendChild(style); style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css)); // yep loaded = true; }
javascript
function () { // helper method to assert if a given url is local function isLocal(url) { var loc = document.location, reg = new RegExp("^\\.|^\/(?!\/)|^[\\w]((?!://).)*$|" + loc.protocol + "//" + loc.host); return url.match(reg); } // gather all resources var scripts = document.getElementsByTagName("script"), links = document.getElementsByTagName("link"), uris = []; // track local js urls for (var i = 0; i < scripts.length; i++) { var script = scripts[i], src = script.getAttribute("src"); if (src && isLocal(src)) uris.push(src); if (src && src.match(/\blive.js#/)) { for (var type in active) active[type] = src.match("[#,|]" + type) != null if (src.match("notify")) alert("Live.js is loaded."); } } if (!active.js) uris = []; if (active.html) uris.push(document.location.href); // track local css urls for (var i = 0; i < links.length && active.css; i++) { var link = links[i], rel = link.getAttribute("rel"), href = link.getAttribute("href", 2); if (href && rel && rel.match(new RegExp("stylesheet", "i")) && isLocal(href)) { uris.push(href); currentLinkElements[href] = link; } } // initialize the resources info for (var i = 0; i < uris.length; i++) { var url = uris[i]; Live.getHead(url, function (url, info) { resources[url] = info; }); } // add rule for morphing between old and new css files var head = document.getElementsByTagName("head")[0], style = document.createElement("style"), rule = "transition: all .3s ease-out;" css = [".livejs-loading * { ", rule, " -webkit-", rule, "-moz-", rule, "-o-", rule, "}"].join(''); style.setAttribute("type", "text/css"); head.appendChild(style); style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css)); // yep loaded = true; }
[ "function", "(", ")", "{", "// helper method to assert if a given url is local\r", "function", "isLocal", "(", "url", ")", "{", "var", "loc", "=", "document", ".", "location", ",", "reg", "=", "new", "RegExp", "(", "\"^\\\\.|^\\/(?!\\/)|^[\\\\w]((?!://).)*$|\"", "+", "loc", ".", "protocol", "+", "\"//\"", "+", "loc", ".", "host", ")", ";", "return", "url", ".", "match", "(", "reg", ")", ";", "}", "// gather all resources\r", "var", "scripts", "=", "document", ".", "getElementsByTagName", "(", "\"script\"", ")", ",", "links", "=", "document", ".", "getElementsByTagName", "(", "\"link\"", ")", ",", "uris", "=", "[", "]", ";", "// track local js urls\r", "for", "(", "var", "i", "=", "0", ";", "i", "<", "scripts", ".", "length", ";", "i", "++", ")", "{", "var", "script", "=", "scripts", "[", "i", "]", ",", "src", "=", "script", ".", "getAttribute", "(", "\"src\"", ")", ";", "if", "(", "src", "&&", "isLocal", "(", "src", ")", ")", "uris", ".", "push", "(", "src", ")", ";", "if", "(", "src", "&&", "src", ".", "match", "(", "/", "\\blive.js#", "/", ")", ")", "{", "for", "(", "var", "type", "in", "active", ")", "active", "[", "type", "]", "=", "src", ".", "match", "(", "\"[#,|]\"", "+", "type", ")", "!=", "null", "if", "(", "src", ".", "match", "(", "\"notify\"", ")", ")", "alert", "(", "\"Live.js is loaded.\"", ")", ";", "}", "}", "if", "(", "!", "active", ".", "js", ")", "uris", "=", "[", "]", ";", "if", "(", "active", ".", "html", ")", "uris", ".", "push", "(", "document", ".", "location", ".", "href", ")", ";", "// track local css urls\r", "for", "(", "var", "i", "=", "0", ";", "i", "<", "links", ".", "length", "&&", "active", ".", "css", ";", "i", "++", ")", "{", "var", "link", "=", "links", "[", "i", "]", ",", "rel", "=", "link", ".", "getAttribute", "(", "\"rel\"", ")", ",", "href", "=", "link", ".", "getAttribute", "(", "\"href\"", ",", "2", ")", ";", "if", "(", "href", "&&", "rel", "&&", "rel", ".", "match", "(", "new", "RegExp", "(", "\"stylesheet\"", ",", "\"i\"", ")", ")", "&&", "isLocal", "(", "href", ")", ")", "{", "uris", ".", "push", "(", "href", ")", ";", "currentLinkElements", "[", "href", "]", "=", "link", ";", "}", "}", "// initialize the resources info\r", "for", "(", "var", "i", "=", "0", ";", "i", "<", "uris", ".", "length", ";", "i", "++", ")", "{", "var", "url", "=", "uris", "[", "i", "]", ";", "Live", ".", "getHead", "(", "url", ",", "function", "(", "url", ",", "info", ")", "{", "resources", "[", "url", "]", "=", "info", ";", "}", ")", ";", "}", "// add rule for morphing between old and new css files\r", "var", "head", "=", "document", ".", "getElementsByTagName", "(", "\"head\"", ")", "[", "0", "]", ",", "style", "=", "document", ".", "createElement", "(", "\"style\"", ")", ",", "rule", "=", "\"transition: all .3s ease-out;\"", "css", "=", "[", "\".livejs-loading * { \"", ",", "rule", ",", "\" -webkit-\"", ",", "rule", ",", "\"-moz-\"", ",", "rule", ",", "\"-o-\"", ",", "rule", ",", "\"}\"", "]", ".", "join", "(", "''", ")", ";", "style", ".", "setAttribute", "(", "\"type\"", ",", "\"text/css\"", ")", ";", "head", ".", "appendChild", "(", "style", ")", ";", "style", ".", "styleSheet", "?", "style", ".", "styleSheet", ".", "cssText", "=", "css", ":", "style", ".", "appendChild", "(", "document", ".", "createTextNode", "(", "css", ")", ")", ";", "// yep\r", "loaded", "=", "true", ";", "}" ]
loads all local css and js resources upon first activation
[ "loads", "all", "local", "css", "and", "js", "resources", "upon", "first", "activation" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/assets/live.js#L47-L104
8,893
easysoft/zui
assets/live.js
isLocal
function isLocal(url) { var loc = document.location, reg = new RegExp("^\\.|^\/(?!\/)|^[\\w]((?!://).)*$|" + loc.protocol + "//" + loc.host); return url.match(reg); }
javascript
function isLocal(url) { var loc = document.location, reg = new RegExp("^\\.|^\/(?!\/)|^[\\w]((?!://).)*$|" + loc.protocol + "//" + loc.host); return url.match(reg); }
[ "function", "isLocal", "(", "url", ")", "{", "var", "loc", "=", "document", ".", "location", ",", "reg", "=", "new", "RegExp", "(", "\"^\\\\.|^\\/(?!\\/)|^[\\\\w]((?!://).)*$|\"", "+", "loc", ".", "protocol", "+", "\"//\"", "+", "loc", ".", "host", ")", ";", "return", "url", ".", "match", "(", "reg", ")", ";", "}" ]
helper method to assert if a given url is local
[ "helper", "method", "to", "assert", "if", "a", "given", "url", "is", "local" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/assets/live.js#L50-L54
8,894
easysoft/zui
assets/live.js
function () { for (var url in resources) { if (pendingRequests[url]) continue; Live.getHead(url, function (url, newInfo) { var oldInfo = resources[url], hasChanged = false; resources[url] = newInfo; for (var header in oldInfo) { // do verification based on the header type var oldValue = oldInfo[header], newValue = newInfo[header], contentType = newInfo["Content-Type"]; switch (header.toLowerCase()) { case "etag": if (!newValue) break; // fall through to default default: hasChanged = oldValue != newValue; break; } // if changed, act if (hasChanged) { Live.refreshResource(url, contentType); break; } } }); } }
javascript
function () { for (var url in resources) { if (pendingRequests[url]) continue; Live.getHead(url, function (url, newInfo) { var oldInfo = resources[url], hasChanged = false; resources[url] = newInfo; for (var header in oldInfo) { // do verification based on the header type var oldValue = oldInfo[header], newValue = newInfo[header], contentType = newInfo["Content-Type"]; switch (header.toLowerCase()) { case "etag": if (!newValue) break; // fall through to default default: hasChanged = oldValue != newValue; break; } // if changed, act if (hasChanged) { Live.refreshResource(url, contentType); break; } } }); } }
[ "function", "(", ")", "{", "for", "(", "var", "url", "in", "resources", ")", "{", "if", "(", "pendingRequests", "[", "url", "]", ")", "continue", ";", "Live", ".", "getHead", "(", "url", ",", "function", "(", "url", ",", "newInfo", ")", "{", "var", "oldInfo", "=", "resources", "[", "url", "]", ",", "hasChanged", "=", "false", ";", "resources", "[", "url", "]", "=", "newInfo", ";", "for", "(", "var", "header", "in", "oldInfo", ")", "{", "// do verification based on the header type\r", "var", "oldValue", "=", "oldInfo", "[", "header", "]", ",", "newValue", "=", "newInfo", "[", "header", "]", ",", "contentType", "=", "newInfo", "[", "\"Content-Type\"", "]", ";", "switch", "(", "header", ".", "toLowerCase", "(", ")", ")", "{", "case", "\"etag\"", ":", "if", "(", "!", "newValue", ")", "break", ";", "// fall through to default\r", "default", ":", "hasChanged", "=", "oldValue", "!=", "newValue", ";", "break", ";", "}", "// if changed, act\r", "if", "(", "hasChanged", ")", "{", "Live", ".", "refreshResource", "(", "url", ",", "contentType", ")", ";", "break", ";", "}", "}", "}", ")", ";", "}", "}" ]
check all tracking resources for changes
[ "check", "all", "tracking", "resources", "for", "changes" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/assets/live.js#L107-L137
8,895
easysoft/zui
assets/live.js
function (url, type) { switch (type.toLowerCase()) { // css files can be reloaded dynamically by replacing the link element case "text/css": var link = currentLinkElements[url], html = document.body.parentNode, head = link.parentNode, next = link.nextSibling, newLink = document.createElement("link"); html.className = html.className.replace(/\s*livejs\-loading/gi, '') + ' livejs-loading'; newLink.setAttribute("type", "text/css"); newLink.setAttribute("rel", "stylesheet"); newLink.setAttribute("href", url + "?now=" + new Date() * 1); next ? head.insertBefore(newLink, next) : head.appendChild(newLink); currentLinkElements[url] = newLink; oldLinkElements[url] = link; // schedule removal of the old link Live.removeoldLinkElements(); break; // check if an html resource is our current url, then reload case "text/html": if (url != document.location.href) return; // local javascript changes cause a reload as well case "text/javascript": case "application/javascript": case "application/x-javascript": document.location.reload(); } }
javascript
function (url, type) { switch (type.toLowerCase()) { // css files can be reloaded dynamically by replacing the link element case "text/css": var link = currentLinkElements[url], html = document.body.parentNode, head = link.parentNode, next = link.nextSibling, newLink = document.createElement("link"); html.className = html.className.replace(/\s*livejs\-loading/gi, '') + ' livejs-loading'; newLink.setAttribute("type", "text/css"); newLink.setAttribute("rel", "stylesheet"); newLink.setAttribute("href", url + "?now=" + new Date() * 1); next ? head.insertBefore(newLink, next) : head.appendChild(newLink); currentLinkElements[url] = newLink; oldLinkElements[url] = link; // schedule removal of the old link Live.removeoldLinkElements(); break; // check if an html resource is our current url, then reload case "text/html": if (url != document.location.href) return; // local javascript changes cause a reload as well case "text/javascript": case "application/javascript": case "application/x-javascript": document.location.reload(); } }
[ "function", "(", "url", ",", "type", ")", "{", "switch", "(", "type", ".", "toLowerCase", "(", ")", ")", "{", "// css files can be reloaded dynamically by replacing the link element \r", "case", "\"text/css\"", ":", "var", "link", "=", "currentLinkElements", "[", "url", "]", ",", "html", "=", "document", ".", "body", ".", "parentNode", ",", "head", "=", "link", ".", "parentNode", ",", "next", "=", "link", ".", "nextSibling", ",", "newLink", "=", "document", ".", "createElement", "(", "\"link\"", ")", ";", "html", ".", "className", "=", "html", ".", "className", ".", "replace", "(", "/", "\\s*livejs\\-loading", "/", "gi", ",", "''", ")", "+", "' livejs-loading'", ";", "newLink", ".", "setAttribute", "(", "\"type\"", ",", "\"text/css\"", ")", ";", "newLink", ".", "setAttribute", "(", "\"rel\"", ",", "\"stylesheet\"", ")", ";", "newLink", ".", "setAttribute", "(", "\"href\"", ",", "url", "+", "\"?now=\"", "+", "new", "Date", "(", ")", "*", "1", ")", ";", "next", "?", "head", ".", "insertBefore", "(", "newLink", ",", "next", ")", ":", "head", ".", "appendChild", "(", "newLink", ")", ";", "currentLinkElements", "[", "url", "]", "=", "newLink", ";", "oldLinkElements", "[", "url", "]", "=", "link", ";", "// schedule removal of the old link\r", "Live", ".", "removeoldLinkElements", "(", ")", ";", "break", ";", "// check if an html resource is our current url, then reload \r", "case", "\"text/html\"", ":", "if", "(", "url", "!=", "document", ".", "location", ".", "href", ")", "return", ";", "// local javascript changes cause a reload as well\r", "case", "\"text/javascript\"", ":", "case", "\"application/javascript\"", ":", "case", "\"application/x-javascript\"", ":", "document", ".", "location", ".", "reload", "(", ")", ";", "}", "}" ]
act upon a changed url of certain content type
[ "act", "upon", "a", "changed", "url", "of", "certain", "content", "type" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/assets/live.js#L140-L173
8,896
easysoft/zui
assets/live.js
function () { var pending = 0; for (var url in oldLinkElements) { // if this sheet has any cssRules, delete the old link try { var link = currentLinkElements[url], oldLink = oldLinkElements[url], html = document.body.parentNode, sheet = link.sheet || link.styleSheet, rules = sheet.rules || sheet.cssRules; if (rules.length >= 0) { oldLink.parentNode.removeChild(oldLink); delete oldLinkElements[url]; setTimeout(function () { html.className = html.className.replace(/\s*livejs\-loading/gi, ''); }, 100); } } catch (e) { pending++; } if (pending) setTimeout(Live.removeoldLinkElements, 50); } }
javascript
function () { var pending = 0; for (var url in oldLinkElements) { // if this sheet has any cssRules, delete the old link try { var link = currentLinkElements[url], oldLink = oldLinkElements[url], html = document.body.parentNode, sheet = link.sheet || link.styleSheet, rules = sheet.rules || sheet.cssRules; if (rules.length >= 0) { oldLink.parentNode.removeChild(oldLink); delete oldLinkElements[url]; setTimeout(function () { html.className = html.className.replace(/\s*livejs\-loading/gi, ''); }, 100); } } catch (e) { pending++; } if (pending) setTimeout(Live.removeoldLinkElements, 50); } }
[ "function", "(", ")", "{", "var", "pending", "=", "0", ";", "for", "(", "var", "url", "in", "oldLinkElements", ")", "{", "// if this sheet has any cssRules, delete the old link\r", "try", "{", "var", "link", "=", "currentLinkElements", "[", "url", "]", ",", "oldLink", "=", "oldLinkElements", "[", "url", "]", ",", "html", "=", "document", ".", "body", ".", "parentNode", ",", "sheet", "=", "link", ".", "sheet", "||", "link", ".", "styleSheet", ",", "rules", "=", "sheet", ".", "rules", "||", "sheet", ".", "cssRules", ";", "if", "(", "rules", ".", "length", ">=", "0", ")", "{", "oldLink", ".", "parentNode", ".", "removeChild", "(", "oldLink", ")", ";", "delete", "oldLinkElements", "[", "url", "]", ";", "setTimeout", "(", "function", "(", ")", "{", "html", ".", "className", "=", "html", ".", "className", ".", "replace", "(", "/", "\\s*livejs\\-loading", "/", "gi", ",", "''", ")", ";", "}", ",", "100", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "pending", "++", ";", "}", "if", "(", "pending", ")", "setTimeout", "(", "Live", ".", "removeoldLinkElements", ",", "50", ")", ";", "}", "}" ]
removes the old stylesheet rules only once the new one has finished loading
[ "removes", "the", "old", "stylesheet", "rules", "only", "once", "the", "new", "one", "has", "finished", "loading" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/assets/live.js#L176-L198
8,897
easysoft/zui
assets/live.js
function (url, callback) { pendingRequests[url] = true; var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XmlHttp"); xhr.open("HEAD", url, true); xhr.onreadystatechange = function () { delete pendingRequests[url]; if (xhr.readyState == 4 && xhr.status != 304) { xhr.getAllResponseHeaders(); var info = {}; for (var h in headers) { var value = xhr.getResponseHeader(h); // adjust the simple Etag variant to match on its significant part if (h.toLowerCase() == "etag" && value) value = value.replace(/^W\//, ''); if (h.toLowerCase() == "content-type" && value) value = value.replace(/^(.*?);.*?$/i, "$1"); info[h] = value; } callback(url, info); } } xhr.send(); }
javascript
function (url, callback) { pendingRequests[url] = true; var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XmlHttp"); xhr.open("HEAD", url, true); xhr.onreadystatechange = function () { delete pendingRequests[url]; if (xhr.readyState == 4 && xhr.status != 304) { xhr.getAllResponseHeaders(); var info = {}; for (var h in headers) { var value = xhr.getResponseHeader(h); // adjust the simple Etag variant to match on its significant part if (h.toLowerCase() == "etag" && value) value = value.replace(/^W\//, ''); if (h.toLowerCase() == "content-type" && value) value = value.replace(/^(.*?);.*?$/i, "$1"); info[h] = value; } callback(url, info); } } xhr.send(); }
[ "function", "(", "url", ",", "callback", ")", "{", "pendingRequests", "[", "url", "]", "=", "true", ";", "var", "xhr", "=", "window", ".", "XMLHttpRequest", "?", "new", "XMLHttpRequest", "(", ")", ":", "new", "ActiveXObject", "(", "\"Microsoft.XmlHttp\"", ")", ";", "xhr", ".", "open", "(", "\"HEAD\"", ",", "url", ",", "true", ")", ";", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "delete", "pendingRequests", "[", "url", "]", ";", "if", "(", "xhr", ".", "readyState", "==", "4", "&&", "xhr", ".", "status", "!=", "304", ")", "{", "xhr", ".", "getAllResponseHeaders", "(", ")", ";", "var", "info", "=", "{", "}", ";", "for", "(", "var", "h", "in", "headers", ")", "{", "var", "value", "=", "xhr", ".", "getResponseHeader", "(", "h", ")", ";", "// adjust the simple Etag variant to match on its significant part\r", "if", "(", "h", ".", "toLowerCase", "(", ")", "==", "\"etag\"", "&&", "value", ")", "value", "=", "value", ".", "replace", "(", "/", "^W\\/", "/", ",", "''", ")", ";", "if", "(", "h", ".", "toLowerCase", "(", ")", "==", "\"content-type\"", "&&", "value", ")", "value", "=", "value", ".", "replace", "(", "/", "^(.*?);.*?$", "/", "i", ",", "\"$1\"", ")", ";", "info", "[", "h", "]", "=", "value", ";", "}", "callback", "(", "url", ",", "info", ")", ";", "}", "}", "xhr", ".", "send", "(", ")", ";", "}" ]
performs a HEAD request and passes the header info to the given callback
[ "performs", "a", "HEAD", "request", "and", "passes", "the", "header", "info", "to", "the", "given", "callback" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/assets/live.js#L201-L221
8,898
easysoft/zui
dist/lib/markdoc/zui.markdoc.js
function(element, options) { var that = this; that.name = NAME; that.$ = $(element); that.options = $.extend({}, MarkDoc.DEFAULTS, this.$.data(), options); that.$.data('originContent', that.$.text()); that.render(); }
javascript
function(element, options) { var that = this; that.name = NAME; that.$ = $(element); that.options = $.extend({}, MarkDoc.DEFAULTS, this.$.data(), options); that.$.data('originContent', that.$.text()); that.render(); }
[ "function", "(", "element", ",", "options", ")", "{", "var", "that", "=", "this", ";", "that", ".", "name", "=", "NAME", ";", "that", ".", "$", "=", "$", "(", "element", ")", ";", "that", ".", "options", "=", "$", ".", "extend", "(", "{", "}", ",", "MarkDoc", ".", "DEFAULTS", ",", "this", ".", "$", ".", "data", "(", ")", ",", "options", ")", ";", "that", ".", "$", ".", "data", "(", "'originContent'", ",", "that", ".", "$", ".", "text", "(", ")", ")", ";", "that", ".", "render", "(", ")", ";", "}" ]
model name The markdoc model class
[ "model", "name", "The", "markdoc", "model", "class" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/dist/lib/markdoc/zui.markdoc.js#L1311-L1319
8,899
easysoft/zui
dist/lib/chart/zui.chart.js
function(easeDecimal) { var animDecimal = (easeDecimal) ? easeDecimal : 1; this.clear(); // ZUI change begin var labelPositionMap; // ZUI change end helpers.each(this.segments, function(segment, index) { segment.transition({ circumference: this.calculateCircumference(segment.value), outerRadius: this.outerRadius, innerRadius: (this.outerRadius / 100) * this.options.percentageInnerCutout }, animDecimal); segment.endAngle = segment.startAngle + segment.circumference; // ZUI change begin if (!this.options.reverseDrawOrder) { // ZUI change end // ZUI change begin segment.draw(); // ZUI change end } // ZUI change end if(index === 0) { segment.startAngle = Math.PI * 1.5; } //Check to see if it's the last segment, if not get the next and update the start angle if(index < this.segments.length - 1) { this.segments[index + 1].startAngle = segment.endAngle; } }, this); // ZUI change begin if (this.options.reverseDrawOrder) { helpers.each(this.segments.slice().reverse(), function(segment, index) { segment.draw(); }, this); } /// ZUI change end /// ZUI change begin if(this.options.scaleShowLabels) { var segmentsArray = this.segments.slice().sort(function(a,b){return b.value - a.value;}); var labelPositionMap = {}; helpers.each(segmentsArray, function(segment, index) { if(segment.showLabel) this.drawLabel(segment, easeDecimal, labelPositionMap); }, this); } /// ZUI change end }
javascript
function(easeDecimal) { var animDecimal = (easeDecimal) ? easeDecimal : 1; this.clear(); // ZUI change begin var labelPositionMap; // ZUI change end helpers.each(this.segments, function(segment, index) { segment.transition({ circumference: this.calculateCircumference(segment.value), outerRadius: this.outerRadius, innerRadius: (this.outerRadius / 100) * this.options.percentageInnerCutout }, animDecimal); segment.endAngle = segment.startAngle + segment.circumference; // ZUI change begin if (!this.options.reverseDrawOrder) { // ZUI change end // ZUI change begin segment.draw(); // ZUI change end } // ZUI change end if(index === 0) { segment.startAngle = Math.PI * 1.5; } //Check to see if it's the last segment, if not get the next and update the start angle if(index < this.segments.length - 1) { this.segments[index + 1].startAngle = segment.endAngle; } }, this); // ZUI change begin if (this.options.reverseDrawOrder) { helpers.each(this.segments.slice().reverse(), function(segment, index) { segment.draw(); }, this); } /// ZUI change end /// ZUI change begin if(this.options.scaleShowLabels) { var segmentsArray = this.segments.slice().sort(function(a,b){return b.value - a.value;}); var labelPositionMap = {}; helpers.each(segmentsArray, function(segment, index) { if(segment.showLabel) this.drawLabel(segment, easeDecimal, labelPositionMap); }, this); } /// ZUI change end }
[ "function", "(", "easeDecimal", ")", "{", "var", "animDecimal", "=", "(", "easeDecimal", ")", "?", "easeDecimal", ":", "1", ";", "this", ".", "clear", "(", ")", ";", "// ZUI change begin", "var", "labelPositionMap", ";", "// ZUI change end", "helpers", ".", "each", "(", "this", ".", "segments", ",", "function", "(", "segment", ",", "index", ")", "{", "segment", ".", "transition", "(", "{", "circumference", ":", "this", ".", "calculateCircumference", "(", "segment", ".", "value", ")", ",", "outerRadius", ":", "this", ".", "outerRadius", ",", "innerRadius", ":", "(", "this", ".", "outerRadius", "/", "100", ")", "*", "this", ".", "options", ".", "percentageInnerCutout", "}", ",", "animDecimal", ")", ";", "segment", ".", "endAngle", "=", "segment", ".", "startAngle", "+", "segment", ".", "circumference", ";", "// ZUI change begin", "if", "(", "!", "this", ".", "options", ".", "reverseDrawOrder", ")", "{", "// ZUI change end", "// ZUI change begin", "segment", ".", "draw", "(", ")", ";", "// ZUI change end", "}", "// ZUI change end", "if", "(", "index", "===", "0", ")", "{", "segment", ".", "startAngle", "=", "Math", ".", "PI", "*", "1.5", ";", "}", "//Check to see if it's the last segment, if not get the next and update the start angle", "if", "(", "index", "<", "this", ".", "segments", ".", "length", "-", "1", ")", "{", "this", ".", "segments", "[", "index", "+", "1", "]", ".", "startAngle", "=", "segment", ".", "endAngle", ";", "}", "}", ",", "this", ")", ";", "// ZUI change begin", "if", "(", "this", ".", "options", ".", "reverseDrawOrder", ")", "{", "helpers", ".", "each", "(", "this", ".", "segments", ".", "slice", "(", ")", ".", "reverse", "(", ")", ",", "function", "(", "segment", ",", "index", ")", "{", "segment", ".", "draw", "(", ")", ";", "}", ",", "this", ")", ";", "}", "/// ZUI change end", "/// ZUI change begin", "if", "(", "this", ".", "options", ".", "scaleShowLabels", ")", "{", "var", "segmentsArray", "=", "this", ".", "segments", ".", "slice", "(", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "b", ".", "value", "-", "a", ".", "value", ";", "}", ")", ";", "var", "labelPositionMap", "=", "{", "}", ";", "helpers", ".", "each", "(", "segmentsArray", ",", "function", "(", "segment", ",", "index", ")", "{", "if", "(", "segment", ".", "showLabel", ")", "this", ".", "drawLabel", "(", "segment", ",", "easeDecimal", ",", "labelPositionMap", ")", ";", "}", ",", "this", ")", ";", "}", "/// ZUI change end", "}" ]
ZUI change end
[ "ZUI", "change", "end" ]
a5af01d76e9481d618d6abd3e873a8ee7e49c59f
https://github.com/easysoft/zui/blob/a5af01d76e9481d618d6abd3e873a8ee7e49c59f/dist/lib/chart/zui.chart.js#L2822-L2872