webgl-utils

Methods

(static) createAttribsFromArrays(gl, arrays, opt_mappingopt) → {Object.<string, module:webgl-utils.AttribInfo>}

Creates a set of attribute data and WebGLBuffers from set of arrays

Given

 let arrays = {
   position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
   texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1],                 },
   normal:   { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],     },
   color:    { numComponents: 4, data: [255, 255, 255, 255, 255, 0, 0, 255, 0, 0, 255, 255], type: Uint8Array, },
   indices:  { numComponents: 3, data: [0, 1, 2, 1, 2, 3],                       },
 };

returns something like

 let attribs = {
   a_position: { numComponents: 3, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   a_texcoord: { numComponents: 2, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   a_normal:   { numComponents: 3, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   a_color:    { numComponents: 4, type: gl.UNSIGNED_BYTE, normalize: true,  buffer: WebGLBuffer, },
 };
Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

The webgl rendering context.

arrays Object.<string, (array|typedarray)>

The arrays

opt_mapping Object.<string, string> <optional>

mapping from attribute name to array name.
if not specified defaults to "a_name" -> "name".

Returns:
Type:
Object.<string, module:webgl-utils.AttribInfo>

the attribs

(static) createAttributeSetters(program) → {Object.<string, function()>}

Creates setter functions for all attributes of a shader
program. You can pass this to module:webgl-utils.setBuffersAndAttributes to set all your buffers and attributes.

See:
Parameters:
Name Type Description
program WebGLProgram

the program to create setters for.

Returns:
Type:
Object.<string, function()>

an object with a setter for each attribute by name.

(static) createAugmentedTypedArray(numComponents, numElements, opt_type) → {ArrayBuffer}

creates a typed array with a push function attached
so that you can easily push values.

push can take multiple arguments. If an argument is an array each element
of the array will be added to the typed array.

Example:

let array = createAugmentedTypedArray(3, 2);  // creates a Float32Array with 6 values
array.push(1, 2, 3);
array.push([4, 5, 6]);
// array now contains [1, 2, 3, 4, 5, 6]

Also has numComponents and numElements properties.

Parameters:
Name Type Description
numComponents number

number of components

numElements number

number of elements. The total size of the array will be numComponents * numElements.

opt_type constructor

A constructor for the type. Default = Float32Array.

Returns:
Type:
ArrayBuffer

A typed array.

(static) createBufferInfoFromArrays(gl, arrays, opt_mappingopt) → {module:webgl-utils.BufferInfo}

Creates a BufferInfo from an object of arrays.

This can be passed to module:webgl-utils.setBuffersAndAttributes and to
module:webgl-utils:drawBufferInfo.

Given an object like

let arrays = {
  position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
  texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1],                 },
  normal:   { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],     },
  indices:  { numComponents: 3, data: [0, 1, 2, 1, 2, 3],                       },
};

Creates an BufferInfo like this

bufferInfo = {
  numElements: 4,        // or whatever the number of elements is
  indices: WebGLBuffer,  // this property will not exist if there are no indices
  attribs: {
    a_position: { buffer: WebGLBuffer, numComponents: 3, },
    a_normal:   { buffer: WebGLBuffer, numComponents: 3, },
    a_texcoord: { buffer: WebGLBuffer, numComponents: 2, },
  },
};

The properties of arrays can be JavaScript arrays in which case the number of components
will be guessed.

let arrays = {
   position: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0],
   texcoord: [0, 0, 0, 1, 1, 0, 1, 1],
   normal:   [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],
   indices:  [0, 1, 2, 1, 2, 3],
};

They can also by TypedArrays

let arrays = {
   position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),
   texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),
   normal:   new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
   indices:  new Uint16Array([0, 1, 2, 1, 2, 3]),
};

Or augmentedTypedArrays

let positions = createAugmentedTypedArray(3, 4);
let texcoords = createAugmentedTypedArray(2, 4);
let normals   = createAugmentedTypedArray(3, 4);
let indices   = createAugmentedTypedArray(3, 2, Uint16Array);

positions.push([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]);
texcoords.push([0, 0, 0, 1, 1, 0, 1, 1]);
normals.push([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]);
indices.push([0, 1, 2, 1, 2, 3]);

let arrays = {
   position: positions,
   texcoord: texcoords,
   normal:   normals,
   indices:  indices,
};

For the last example it is equivalent to

let bufferInfo = {
  attribs: {
    a_position: { numComponents: 3, buffer: gl.createBuffer(), },
    a_texcoods: { numComponents: 2, buffer: gl.createBuffer(), },
    a_normals: { numComponents: 3, buffer: gl.createBuffer(), },
  },
  indices: gl.createBuffer(),
  numElements: 6,
};

gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_position.buffer);
gl.bufferData(gl.ARRAY_BUFFER, arrays.position, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_texcoord.buffer);
gl.bufferData(gl.ARRAY_BUFFER, arrays.texcoord, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_normal.buffer);
gl.bufferData(gl.ARRAY_BUFFER, arrays.normal, gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferInfo.indices);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, arrays.indices, gl.STATIC_DRAW);
Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

A WebGLRenderingContext

arrays Object.<string, (array|object|typedarray)>

Your data

opt_mapping Object.<string, string> <optional>

an optional mapping of attribute to array name.
If not passed in it's assumed the array names will be mapped to an attribute
of the same name with "a_" prefixed to it. An other words.

   let arrays = {
      position: ...,
      texcoord: ...,
      normal:   ...,
      indices:  ...,
   };

   bufferInfo = createBufferInfoFromArrays(gl, arrays);

Is the same as

   let arrays = {
      position: ...,
      texcoord: ...,
      normal:   ...,
      indices:  ...,
   };

   let mapping = {
     a_position: "position",
     a_texcoord: "texcoord",
     a_normal:   "normal",
   };

   bufferInfo = createBufferInfoFromArrays(gl, arrays, mapping);
Returns:
Type:
module:webgl-utils.BufferInfo

A BufferInfo

(static) createBuffersFromArrays(gl, arrays) → {Object.<string, WebGLBuffer>}

Creates buffers from typed arrays

Given something like this

let arrays = {
   positions: [1, 2, 3],
   normals: [0, 0, 1],
}

returns something like

buffers = {
  positions: WebGLBuffer,
  normals: WebGLBuffer,
}

If the buffer is named 'indices' it will be made an ELEMENT_ARRAY_BUFFER.

Parameters:
Name Type Description
gl WebGLRenderingContext

A WebGLRenderingContext.

arrays Object.<string, (array|typedarray)>
Returns:
Type:
Object.<string, WebGLBuffer>

returns an object with one WebGLBuffer per array

(static) createProgram(shaders, opt_attribsopt, opt_locationsopt, opt_errorCallback)

Creates a program, attaches shaders, binds attrib locations, links the
program and calls useProgram.

Parameters:
Name Type Attributes Description
shaders Array.<WebGLShader>

The shaders to attach

opt_attribs Array.<string> <optional>

An array of attribs names. Locations will be assigned by index if not passed in

opt_locations Array.<number> <optional>

The locations for the. A parallel array to opt_attribs letting you assign locations.

opt_errorCallback module:webgl-utils.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.

(static) createProgramFromScripts(gl, shaderScriptIds, opt_attribsopt, opt_locationsopt, opt_errorCallback) → {WebGLProgram}

Creates a program from 2 script tags.

Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

The WebGLRenderingContext
to use.

shaderScriptIds Array.<string>

Array of ids of the script
tags for the shaders. The first is assumed to be the
vertex shader, the second the fragment shader.

opt_attribs Array.<string> <optional>

An array of attribs names. Locations will be assigned by index if not passed in

opt_locations Array.<number> <optional>

The locations for the. A parallel array to opt_attribs letting you assign locations.

opt_errorCallback module:webgl-utils.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.

Returns:
Type:
WebGLProgram

The created program.

(static) createProgramFromSources(gl, shaderSourcess, opt_attribsopt, opt_locationsopt, opt_errorCallback) → {WebGLProgram}

Creates a program from 2 sources.

Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

The WebGLRenderingContext
to use.

shaderSourcess Array.<string>

Array of sources for the
shaders. The first is assumed to be the vertex shader,
the second the fragment shader.

opt_attribs Array.<string> <optional>

An array of attribs names. Locations will be assigned by index if not passed in

opt_locations Array.<number> <optional>

The locations for the. A parallel array to opt_attribs letting you assign locations.

opt_errorCallback module:webgl-utils.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.

Returns:
Type:
WebGLProgram

The created program.

(static) createProgramInfo(gl, shaderSourcess, opt_attribsopt, opt_locationsopt, opt_errorCallback) → {module:webgl-utils.ProgramInfo}

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,
}
Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

The WebGLRenderingContext
to use.

shaderSourcess Array.<string>

Array of sources for the
shaders or ids. The first is assumed to be the vertex shader,
the second the fragment shader.

opt_attribs Array.<string> <optional>

An array of attribs names. Locations will be assigned by index if not passed in

opt_locations Array.<number> <optional>

The locations for the. A parallel array to opt_attribs letting you assign locations.

opt_errorCallback module:webgl-utils.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.

Returns:
Type:
module:webgl-utils.ProgramInfo

The created program.

(static) createUniformSetters(program) → {Object.<string, function()>}

Creates setter functions for all uniforms of a shader
program.

See:
Parameters:
Name Type Description
program WebGLProgram

the program to create setters for.

Returns:
Type:
Object.<string, function()>

an object with a setter by name for each uniform

(static) drawBufferInfo(gl, bufferInfo, primitiveTypeopt, countopt, offsetopt)

Calls gl.drawElements or gl.drawArrays, whichever is appropriate

normally you'd call gl.drawElements or gl.drawArrays yourself
but calling this means if you switch from indexed data to non-indexed
data you don't have to remember to update your draw call.

Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

A WebGLRenderingContext

bufferInfo module:webgl-utils.BufferInfo

as returned from createBufferInfoFromArrays

primitiveType enum <optional>

eg (gl.TRIANGLES, gl.LINES, gl.POINTS, gl.TRIANGLE_STRIP, ...)

count number <optional>

An optional count. Defaults to bufferInfo.numElements

offset number <optional>

An optional offset. Defaults to 0.

(static) drawObjectList(gl, objectsToDraw)

Draws a list of objects

Parameters:
Name Type Description
gl WebGLRenderingContext

A WebGLRenderingContext

objectsToDraw Array.<DrawObject>

an array of objects to draw.

(static) getExtensionWithKnownPrefixes(name) → {WebGLExtension}

Given an extension name like WEBGL_compressed_texture_s3tc
returns the supported version extension, like
WEBKIT_WEBGL_compressed_teture_s3tc

Parameters:
Name Type Description
name string

Name of extension to look for

Returns:
Type:
WebGLExtension

The extension or undefined if not
found.

(static) resizeCanvasToDisplaySize(canvas, multiplieropt) → {boolean}

Resize a canvas to match the size its displayed.

Parameters:
Name Type Attributes Description
canvas HTMLCanvasElement

The canvas to resize.

multiplier number <optional>

amount to multiply by.
Pass in window.devicePixelRatio for native pixels.

Returns:
Type:
boolean

true if the canvas was resized.

(static) setAttributes(setters, attribs)

Sets attributes and binds buffers (deprecated... use module:webgl-utils.setBuffersAndAttributes)

Example:

let program = createProgramFromScripts(
    gl, ["some-vs", "some-fs"]);

let attribSetters = createAttributeSetters(program);

let positionBuffer = gl.createBuffer();
let texcoordBuffer = gl.createBuffer();

let attribs = {
  a_position: {buffer: positionBuffer, numComponents: 3},
  a_texcoord: {buffer: texcoordBuffer, numComponents: 2},
};

gl.useProgram(program);

This will automatically bind the buffers AND set the
attributes.

setAttributes(attribSetters, attribs);

Properties of attribs. For each attrib you can add
properties:

  • type: the type of data in the buffer. Default = gl.FLOAT
  • normalize: whether or not to normalize the data. Default = false
  • stride: the stride. Default = 0
  • offset: offset into the buffer. Default = 0

For example if you had 3 value float positions, 2 value
float texcoord and 4 value uint8 colors you'd setup your
attribs like this

let attribs = {
  a_position: {buffer: positionBuffer, numComponents: 3},
  a_texcoord: {buffer: texcoordBuffer, numComponents: 2},
  a_color: {
    buffer: colorBuffer,
    numComponents: 4,
    type: gl.UNSIGNED_BYTE,
    normalize: true,
  },
};
Deprecated:
Parameters:
Name Type Description
setters Object.<string, function()> | model:webgl-utils.ProgramInfo

Attribute setters as returned from createAttributeSetters or a ProgramInfo as returned module:webgl-utils.createProgramInfo

attribs Object.<string, module:webgl-utils.AttribInfo>

AttribInfos mapped by attribute name.

(static) setBuffersAndAttributes(gl, setters, buffers)

Sets attributes and buffers including the ELEMENT_ARRAY_BUFFER if appropriate

Example:

let programInfo = createProgramInfo(
    gl, ["some-vs", "some-fs"]);

let arrays = {
  position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
  texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1],                 },
};

let bufferInfo = createBufferInfoFromArrays(gl, arrays);

gl.useProgram(programInfo.program);

This will automatically bind the buffers AND set the
attributes.

setBuffersAndAttributes(programInfo.attribSetters, bufferInfo);

For the example above it is equivilent to

gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.enableVertexAttribArray(a_positionLocation);
gl.vertexAttribPointer(a_positionLocation, 3, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
gl.enableVertexAttribArray(a_texcoordLocation);
gl.vertexAttribPointer(a_texcoordLocation, 4, gl.FLOAT, false, 0, 0);
Parameters:
Name Type Description
gl WebGLRenderingContext

A WebGLRenderingContext.

setters Object.<string, function()>

Attribute setters as returned from createAttributeSetters

buffers module:webgl-utils.BufferInfo

a BufferInfo as returned from createBufferInfoFromArrays.

(static) setUniforms(setters, an)

Set uniforms and binds related textures.

Example:

let programInfo = createProgramInfo(
    gl, ["some-vs", "some-fs"]);

let tex1 = gl.createTexture();
let tex2 = gl.createTexture();

... assume we setup the textures with data ...

let uniforms = {
  u_someSampler: tex1,
  u_someOtherSampler: tex2,
  u_someColor: [1,0,0,1],
  u_somePosition: [0,1,1],
  u_someMatrix: [
    1,0,0,0,
    0,1,0,0,
    0,0,1,0,
    0,0,0,0,
  ],
};

gl.useProgram(program);

This will automatically bind the textures AND set the
uniforms.

setUniforms(programInfo.uniformSetters, uniforms);

For the example above it is equivalent to

let texUnit = 0;
gl.activeTexture(gl.TEXTURE0 + texUnit);
gl.bindTexture(gl.TEXTURE_2D, tex1);
gl.uniform1i(u_someSamplerLocation, texUnit++);
gl.activeTexture(gl.TEXTURE0 + texUnit);
gl.bindTexture(gl.TEXTURE_2D, tex2);
gl.uniform1i(u_someSamplerLocation, texUnit++);
gl.uniform4fv(u_someColorLocation, [1, 0, 0, 1]);
gl.uniform3fv(u_somePositionLocation, [0, 1, 1]);
gl.uniformMatrix4fv(u_someMatrix, false, [
    1,0,0,0,
    0,1,0,0,
    0,0,1,0,
    0,0,0,0,
  ]);

Note it is perfectly reasonable to call setUniforms multiple times. For example

let uniforms = {
  u_someSampler: tex1,
  u_someOtherSampler: tex2,
};

let moreUniforms {
  u_someColor: [1,0,0,1],
  u_somePosition: [0,1,1],
  u_someMatrix: [
    1,0,0,0,
    0,1,0,0,
    0,0,1,0,
    0,0,0,0,
  ],
};

setUniforms(programInfo.uniformSetters, uniforms);
setUniforms(programInfo.uniformSetters, moreUniforms);
Parameters:
Name Type Description
setters Object.<string, function()> | module:webgl-utils.ProgramInfo

the setters returned from
createUniformSetters or a ProgramInfo from module:webgl-utils.createProgramInfo.

an Object.<string, value>

object with values for the
uniforms.

Type Definitions

AttribInfo

Properties:
Name Type Attributes Description
numComponents number <optional>

the number of components for this attribute.

size number <optional>

the number of components for this attribute.

type number <optional>

the type of the attribute (eg. gl.FLOAT, gl.UNSIGNED_BYTE, etc...) Default = gl.FLOAT

normalized boolean <optional>

whether or not to normalize the data. Default = false

offset number <optional>

offset into buffer in bytes. Default = 0

stride number <optional>

the stride in bytes per element. Default = 0

buffer WebGLBuffer

the buffer that contains the data for this attribute

Type:
  • Object

BufferInfo

Properties:
Name Type Attributes Description
numElements number

The number of elements to pass to gl.drawArrays or gl.drawElements.

indices WebGLBuffer <optional>

The indices ELEMENT_ARRAY_BUFFER if any indices exist.

attribs Object.<string, module:webgl-utils.AttribInfo>

The attribs approriate to call setAttributes

Type:
  • Object

DrawObject

Properties:
Name Type Description
programInfo module:webgl-utils.ProgramInfo

A ProgramInfo as returned from createProgramInfo

bufferInfo module:webgl-utils.BufferInfo

A BufferInfo as returned from createBufferInfoFromArrays

uniforms Object.<string, ?>

The values for the uniforms

Type:
  • Object

ErrorCallback(msg)

Error Callback

Parameters:
Name Type Description
msg string

error message.

ProgramInfo

Properties:
Name Type Description
program WebGLProgram

A shader program

uniformSetters: Object.<string, function()>

object of setters as returned from createUniformSetters,

attribSetters: Object.<string, function()>

object of setters as returned from createAttribSetters,

Type:
  • Object

Setters

Type:
  • Object.<string, function()>