Module: twgl

twgl

The main TWGL module.

Methods

createAttribsFromArrays(gl, arrays) → {Object.<string, AttribInfo>}

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

Given

 var 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

 var attribs = {
   position: { numComponents: 3, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   texcoord: { numComponents: 2, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   normal:   { numComponents: 3, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   color:    { numComponents: 4, type: gl.UNSIGNED_BYTE, normalize: true,  buffer: WebGLBuffer, },
 };

notes:

  • Arrays can take various forms

    Bare JavaScript Arrays

    var arrays = {
       position: [-1, 1, 0],
       normal: [0, 1, 0],
       ...
    }

    Bare TypedArrays

    var arrays = {
       position: new Float32Array([-1, 1, 0]),
       color: new Uint8Array([255, 128, 64, 255]),
       ...
    }
  • Will guess at numComponents if not specified based on name.

    If coord is in the name assumes numComponents = 2

    If color is in the name assumes numComponents = 4

    otherwise assumes numComponents = 3

Parameters:
Name Type Description
gl WebGLRenderingContext

The webgl rendering context.

arrays Arrays

The arrays

Returns:

the attribs

Type
Object.<string, AttribInfo>

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

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

Parameters:
Name Type Description
program WebGLProgram

the program to create setters for.

See:
Returns:

an object with a setter for each attribute by name.

Type
Object.<string, function()>

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:

var 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:

A typed array.

Type
ArrayBuffer

createBufferInfoFromArrays(gl, arrays) → {BufferInfo}

Creates a BufferInfo from an object of arrays.

This can be passed to setBuffersAndAttributes and to module:twgl:drawBufferInfo.

Given an object like

var 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.

var 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

var 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

var positions = createAugmentedTypedArray(3, 4);
var texcoords = createAugmentedTypedArray(2, 4);
var normals   = createAugmentedTypedArray(3, 4);
var 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]);

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

For the last example it is equivalent to

var 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 Description
gl WebGLRenderingContext

A WebGLRenderingContext

arrays Arrays

Your data

Returns:

A BufferInfo

Type
BufferInfo

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

Creates buffers from typed arrays

Given something like this

var 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
{WebGLRenderingContext)

gl A WebGLRenderingContext.

arrays Arrays
Returns:

returns an object with one WebGLBuffer per array

Type
Object.<string, WebGLBuffer>

createFramebufferInfo(gl, attachments, width, height) → {FramebufferInfo}

Creates a framebuffer and attachments.

This returns a FramebufferInfo because it needs to return the attachments as well as the framebuffer.

The simplest usage

// create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer
var fbi = twgl.createFramebuffer(gl);

More complex usage

// create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer
var attachments = [
  { format: RGB565, mag: NEAREST },
  { format: STENCIL_INDEX8 },
]
var fbi = twgl.createFramebuffer(gl, attachments);

Passing in a specific size

var width = 256;
var height = 256;
var fbi = twgl.createFramebuffer(gl, attachments, width, height);

Note!! It is up to you to check if the framebuffer is renderable by calling gl.checkFramebufferStatus. WebGL only guarantees 3 combinations of attachments work.

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

the WebGLRenderingContext

attachments AttachmentOptions[] <optional>

which attachments to create. If not provided the default is a framebuffer with an RGBA, UNSIGNED_BYTE texture COLOR_ATTACHMENT0 and a DEPTH_STENCIL renderbuffer DEPTH_STENCIL_ATTACHMENT.

width number <optional>

the width for the attachments. Default = size of drawingBuffer

height number <optional>

the height for the attachments. Defautt = size of drawingBuffer

Returns:

the framebuffer and attachments.

Type
FramebufferInfo

createProgram(shaders, opt_attribs, opt_locations, opt_errorCallback) → {WebGLProgram}

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

Parameters:
Name Type Argument Description
shaders WebGLShader[]

The shaders to attach

opt_attribs string[] <optional>

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

opt_locations number[] <optional>

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

opt_errorCallback ErrorCallback <optional>

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:

the created program or null if error.

Type
WebGLProgram

createProgramFromScripts(gl, shaderScriptIds, opt_attribs, opt_locations, opt_errorCallback) → {WebGLProgram}

Creates a program from 2 script tags.

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

The WebGLRenderingContext to use.

shaderScriptIds 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 string[] <optional>

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

opt_locations number[] <optional>

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

opt_errorCallback 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:

The created program.

Type
WebGLProgram

createProgramFromSources(gl, shaderSourcess, opt_attribs, opt_locations, opt_errorCallback) → {WebGLProgram}

Creates a program from 2 sources.

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

The WebGLRenderingContext to use.

shaderSourcess string[]

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

opt_attribs string[] <optional>

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

opt_locations number[] <optional>

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

opt_errorCallback 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:

The created program.

Type
WebGLProgram

createProgramInfo(gl, shaderSourcess, opt_attribs, opt_locations, opt_errorCallback) → {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 Argument Description
gl WebGLRenderingContext

The WebGLRenderingContext to use.

shaderSourcess 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 string[] <optional>

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

opt_locations number[] <optional>

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

opt_errorCallback 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:

The created program.

Type
ProgramInfo

createTexture(gl, options, callback) → {WebGLTexture}

Creates a texture based on the options passed in.

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

the WebGLRenderingContext

options TextureOptions <optional>

A TextureOptions object with whatever parameters you want set.

callback TextureReadyCallback <optional>

A callback called when an image has been downloaded and uploaded to the texture.

Returns:

the created texture.

Type
WebGLTexture

createTextures(gl, options, callback)

Creates a bunch of textures based on the passed in options.

Example:

var 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
Parameters:
Name Type Argument Description
gl WebGLRenderingContext

the WebGLRenderingContext

options Object.<string, TextureOptions>

A object of TextureOptions one per texture.

callback TexturesReadyCallback <optional>

A callback called when all textures have been downloaded.

Returns:

{Object.) the created textures by name

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

Creates setter functions for all uniforms of a shader program.

Parameters:
Name Type Description
program WebGLProgram

the program to create setters for.

See:
Returns:

an object with a setter by name for each uniform

Type
Object.<string, function()>

drawBufferInfo(gl, type, bufferInfo, count, offset)

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 Argument Description
gl WebGLRenderingContext

A WebGLRenderingContext

type enum

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

bufferInfo BufferInfo

as returned from createBufferInfoFromArrays

count number <optional>

An optional count. Defaults to bufferInfo.numElements

offset number <optional>

An optional offset. Defaults to 0.

drawObjectList(objectsToDraw)

Draws a list of objects

Parameters:
Name Type Description
objectsToDraw DrawObject[]

an array of objects to draw.

getWebGLContext(canvas, opt_attribs)

Gets a WebGL context.

Parameters:
Name Type Argument Description
canvas HTMLCanvasElement

a canvas element.

opt_attribs WebGLContextCreationAttirbutes <optional>

optional webgl context creation attributes

loadCubemapFromUrls(gl, tex, options, callback)

Loads a cubemap from 6 urls as specified in options.src. Will set the cubemap to a 1x1 pixel color so that it is usable immediately unless option.color === false.

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

the WebGLRenderingContext

tex WebGLTexture

the WebGLTexture to set parameters for

options TextureOptions

A TextureOptions object with whatever parameters you want set.

callback CubemapReadyCallback <optional>

A function to be called when all the images have finished loading. err will be non null if there was an error.

loadTextureFromUrl(gl, tex, options, callback) → {HTMLImageElement}

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.

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

the WebGLRenderingContext

tex WebGLTexture

the WebGLTexture to set parameters for

options TextureOptions <optional>

A TextureOptions object with whatever parameters you want set.

callback TextureReadyCallback <optional>

A function to be called when the image has finished loading. err will be non null if there was an error.

Returns:

the image being downloaded.

Type
HTMLImageElement

resizeCanvasToDisplaySize(canvas, a) → {boolean}

Resize a canvas to match the size it's displayed.

Parameters:
Name Type Argument Description
canvas HTMLCanvasElement

The canvas to resize.

a number <optional>

multiplier. So you can pass in window.devicePixelRatio if you want to.

Returns:

true if the canvas was resized.

Type
boolean

resizeFramebufferInfo(gl, framebufferInfo, attachments, width, height)

Resizes the attachments of a framebuffer.

You need to pass in the same attachments as you passed in createFramebuffer because TWGL has no idea the format/type of each attachment.

The simplest usage

// create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer
var fbi = twgl.createFramebuffer(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
var attachments = [
  { format: RGB565, mag: NEAREST },
  { format: STENCIL_INDEX8 },
]
var fbi = twgl.createFramebuffer(gl, attachments);

...

function render() {
  if (twgl.resizeCanvasToDisplaySize(gl.canvas)) {
    // resize the attachments to match
    twgl.resizeFramebufferInfo(gl, fbi, attachments);
  }
Parameters:
Name Type Argument Description
gl WebGLRenderingContext

the WebGLRenderingContext

framebufferInfo FramebufferInfo

a framebufferInfo as returned from createFramebuffer.

attachments AttachmentOptions[] <optional>

the same attachments options as passed to createFramebuffer.

width number <optional>

the width for the attachments. Default = size of drawingBuffer

height number <optional>

the height for the attachments. Defautt = size of drawingBuffer

resizeTexture(gl, tex, options, width, height)

Resizes a texture based on the options passed in.

Note: This is not a generic resize anything function. It's mostly used by 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

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

the WebGLRenderingContext

tex WebGLTexture

the texture to resize

options TextureOptions

A TextureOptions object with whatever parameters you want set.

width number <optional>

the new width. If not passed in will use options.width

height number <optional>

the new height. If not passed in will use options.height

setAttributePrefix(prefix)

Sets the default attrib prefix

When writing shaders I prefer to name attributes with a_, uniforms with u_ and varyings with v_ as it makes it clear where they came from. But, when building geometry I prefer using unprefixed names.

In otherwords I'll create arrays of geometry like this

var arrays = {
  position: ...
  normal: ...
  texcoord: ...
};

But need those mapped to attributes and my attributes start with a_.

Parameters:
Name Type Description
prefix string

prefix for attribs

setAttributes(setters, buffers)

Sets attributes and binds buffers (deprecated... use setBuffersAndAttributes)

Example:

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

var attribSetters = createAttributeSetters(program);

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

var 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

var 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,
  },
};
Parameters:
Name Type Description
setters Object.<string, function()>

Attribute setters as returned from createAttributeSetters

buffers Object.<string, AttribInfo>

AttribInfos mapped by attribute name.

Deprecated:

setBuffersAndAttributes(gl, setters, buffers)

Sets attributes and buffers including the ELEMENT_ARRAY_BUFFER if appropriate

Example:

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

var 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],                 },
};

var bufferInfo = createBufferInfoFromArrays(gl, arrays);

gl.useProgram(programInfo.program);

This will automatically bind the buffers AND set the attributes.

setBuffersAndAttributes(gl, programInfo, 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 ProgramInfo| Object.<string, function()>

A ProgramInfo as returned from createProgrmaInfo Attribute setters as returned from createAttributeSetters

buffers BufferInfo

a BufferInfo as returned from createBufferInfoFromArrays.

setDefaultTextureColor(color)

Sets the default texture color.

The default texture color is used when loading textures from urls. Because the URL will be loaded async we'd like to be able to use the texture immediately. By putting a 1x1 pixel color in the texture we can start using the texture before the URL has loaded.

Parameters:
Name Type Description
color number[]

Array of 4 values in the range 0 to 1

setEmptyTexture(gl, tex, 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.

Parameters:
Name Type Description
gl WebGLRenderingContext

the WebGLRenderingContext

tex WebGLTexture

the WebGLTexture to set parameters for

options TextureOptions

A TextureOptions object with whatever parameters you want set.

setTextureFilteringForSize(gl, tex, options, width, height)

Sets filtering or generates mips for texture based on width or height If width or height is not passed in uses options.width and//or options.height

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

the WebGLRenderingContext

tex WebGLTexture

the WebGLTexture to set parameters for

options TextureOptions <optional>

A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture.

width number <optional>

width of texture

height number <optional>

height of texture

setTextureFromArray(gl, tex, src, options)

Sets a texture from an array or typed array. If the width or height is not provided will attempt to guess the size. See TextureOptions.

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

the WebGLRenderingContext

tex WebGLTexture

the WebGLTexture to set parameters for

src Array.<number>| ArrayBuffer

An array or typed arry with texture data.

options TextureOptions <optional>

A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture.

setTextureFromElement(gl, tex, element, options)

Set a texture from the contents of an element. Will also set texture filtering or generate mips based on the dimensions of the element unless options.auto === false. If target === gl.TEXTURE_CUBE_MAP will attempt to slice image into 1x6, 2x3, 3x2, or 6x1 images, one for each face.

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

the WebGLRenderingContext

tex WebGLTexture

the WebGLTexture to set parameters for

element HTMLElement

a canvas, img, or video element.

options TextureOptions <optional>

A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture.

setTextureParameters(gl, tex, options)

Sets the texture parameters of a texture.

Parameters:
Name Type Description
gl WebGLRenderingContext

the WebGLRenderingContext

tex WebGLTexture

the WebGLTexture to set parameters for

options TextureOptions

A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture.

setTextureTo1PixelColor(gl, tex, options)

Sets a texture to a 1x1 pixel color. If options.color === false is nothing happens. If it's not set the default texture color is used which can be set by calling setDefaultTextureColor.

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

the WebGLRenderingContext

tex WebGLTexture

the WebGLTexture to set parameters for

options TextureOptions <optional>

A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture.

setUniforms(setters, values)

Set uniforms and binds related textures.

example:

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

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

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

var 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, uniforms);

For the example above it is equivalent to

var 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

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

var 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, uniforms);
setUniforms(programInfo, moreUniforms);
Parameters:
Name Type Description
setters ProgramInfo| Object.<string, function()>

a ProgramInfo as returned from createProgramInfo or the setters returned from createUniformSetters.

values Object.<string, ?>

an object with values for the uniforms. You can pass multiple objects by putting them in an array or by calling with more arguments.For example

var sharedUniforms = {
  u_fogNear: 10,
  u_projection: ...
  ...
};

var localUniforms = {
  u_world: ...
  u_diffuseColor: ...
};

twgl.setUniforms(programInfo, sharedUniforms, localUniforms);

// is the same as

twgl.setUniforms(programInfo, [sharedUniforms, localUniforms]);

// is the same as

twgl.setUniforms(programInfo, sharedUniforms);
twgl.setUniforms(programInfo, localUniforms};

Type Definitions

Arrays

This is a JavaScript object of arrays by name. The names should match your shader's attributes. If your attributes have a common prefix you can specify it by calling setAttributePrefix.

Bare JavaScript Arrays

    var arrays = {
       position: [-1, 1, 0],
       normal: [0, 1, 0],
       ...
    }

Bare TypedArrays

    var arrays = {
       position: new Float32Array([-1, 1, 0]),
       color: new Uint8Array([255, 128, 64, 255]),
       ...
    }
  • Will guess at numComponents if not specified based on name.

    If coord is in the name assumes numComponents = 2

    If color is in the name assumes numComponents = 4

    otherwise assumes numComponents = 3

Objects with various fields. See FullArraySpec.

var 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],                       },
};
Type:

ArraySpec

An individual array in Arrays

When passed to createBufferInfoFromArrays if an ArraySpec is number[] or ArrayBuffer the types will be guessed based on the name. indices will be Uint16Array, everything else will be Float32Array

Type:

AttachmentOptions

The options for a framebuffer attachment.

Note: For a format that is a texture include all the texture options from TextureOptions for example min, mag, clamp, etc... Note that unlike TextureOptions auto defaults to false for attachment textures

Type:
  • Object
Properties:
Name Type Argument Description
attach number <optional>

The attachment point. Defaults to gl.COLOR_ATTACTMENT0 + ndx unless type is a depth or stencil type then it's gl.DEPTH_ATTACHMENT or gl.DEPTH_STENCIL_ATTACHMENT depending on the format or attachment type.

format number <optional>

The format. If one of gl.RGBA4, gl.RGB565, gl.RGB5_A1, gl.DEPTH_COMPONENT16, gl.STENCIL_INDEX8 or gl.DEPTH_STENCIL then will create a renderbuffer. Otherwise will create a texture. Default = gl.RGBA

type number <optional>

The type. Used for texture. Default = gl.UNSIGNED_BYTE.

target number <optional>

The texture target for gl.framebufferTexture2D. Defaults to gl.TEXTURE_2D. Set to appropriate face for cube maps.

level number <optional>

level for gl.framebufferTexture2D. Defaults to 0.

attachment WebGLObject <optional>

An existing renderbuffer or texture. If provided will attach this Object. This allows you to share attachemnts across framebuffers.

AttribInfo

The info for an attribute. This is effectively just the arguments to gl.vertexAttribPointer plus the WebGLBuffer for the attribute.

Type:
  • Object
Properties:
Name Type Argument Description
numComponents number <optional>

the number of components for this attribute.

size number <optional>

synonym for numComponents.

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

drawType number <optional>

the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW

BufferInfo

Type:
  • Object
Properties:
Name Type Argument 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, AttribInfo>

The attribs approriate to call setAttributes

CubemapReadyCallback(err, tex, imgs)

A callback for when an image finished downloading and been uploaded into a texture

Parameters:
Name Type Description
err *

If truthy there was an error.

tex WebGLTexture

the texture.

imgs HTMLImageElement[]

the images for each face.

DrawObject

Type:
  • Object
Properties:
Name Type Argument Description
active boolean <optional>

whether or not to draw. Default = true (must be false to be not true). In otherwords undefined = true

type number <optional>

type to draw eg. gl.TRIANGLES, gl.LINES, etc...

programInfo ProgramInfo

A ProgramInfo as returned from createProgramInfo

bufferInfo BufferInfo

A BufferInfo as returned from createBufferInfoFromArrays

uniforms Object.<string, ?>

The values for the uniforms. You can pass multiple objects by putting them in an array. For example

var sharedUniforms = {
  u_fogNear: 10,
  u_projection: ...
  ...
};

var localUniforms = {
  u_world: ...
  u_diffuseColor: ...
};

var drawObj = {
  ...
  uniforms: [sharedUniforms, localUniforms],
};
offset number <optional>

the offset to pass to gl.drawArrays or gl.drawElements. Defaults to 0.

count number <optional>

the count to pass to gl.drawArrays or gl.drawElemnts. Defaults to bufferInfo.numElements.

ErrorCallback(msg)

Error Callback

Parameters:
Name Type Description
msg string

error message.

FramebufferInfo

Type:
  • Object
Properties:
Name Type Description
framebuffer WebGLFramebuffer

The WebGLFramebuffer for this framebufferInfo

attachments WebGLObject[]

The created attachments in the same order as passed in to createFramebufferInfo.

FullArraySpec

Use this type of array spec when TWGL can't guess the type or number of compoments of an array

Type:
  • Object
Properties:
Name Type Argument Description
data Array.<number>| ArrayBuffer

The data of the array.

numComponents number <optional>

number of components for vertexAttribPointer. Default is based on the name of the array. If coord is in the name assumes numComponents = 2. If color is in the name assumes numComponents = 4. otherwise assumes numComponents = 3

type constructor

The type. This is only used if data is a JavaScript array. It is the constructor for the typedarray. (eg. Uint8Array). For example if you want colors in a Uint8Array you might have a FullArraySpec like { type: Uint8Array, data: [255,0,255,255, ...], }.

size number <optional>

synonym for numComponents.

normalize boolean <optional>

normalize for vertexAttribPointer. Default is true if type is Int8Array or Uint8Array otherwise false.

stride number <optional>

stride for vertexAttribPointer. Default = 0

offset number <optional>

offset for vertexAttribPointer. Default = 0

attrib string <optional>

name of attribute this array maps to. Defaults to same name as array prefixed by the defaultAttribPrefix.

name string <optional>

synonym for attrib.

attribName string <optional>

synonym for attrib.

ProgramInfo

Type:
  • Object
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,

TextureFunc(gl, options) → {*}

A function to generate the source for a texture.

Parameters:
Name Type Description
gl WebGLRenderingContext

A WebGLRenderingContext

options TextureOptions

the texture options

Returns:

Returns any of the things documentented for src for TextureOptions.

Type
*

TextureOptions

Texture options passed to most texture functions. Each function will use whatever options are appropriate for its needs. This lets you pass the same options to all functions.

Type:
  • Object
Properties:
Name Type Argument Description
target number <optional>

the type of texture gl.TEXTURE_2D or gl.TEXTURE_CUBE_MAP. Defaults to gl.TEXTURE_2D.

width number <optional>

the width of the texture. Only used if src is an array or typed array or null.

height number <optional>

the height of a texture. Only used if src is an array or typed array or null.

min number <optional>

the min filter setting (eg. gl.LINEAR). Defaults to gl.NEAREST_MIPMAP_LINEAR or if texture is not a power of 2 on both dimensions then defaults to gl.LINEAR.

mag number <optional>

the mag filter setting (eg. gl.LINEAR). Defaults to gl.LINEAR

format number <optional>

format for texture. Defaults to gl.RGBA.

type number <optional>

type for texture. Defaults to gl.UNSIGNED_BYTE unless src is ArrayBuffer. If src is ArrayBuffer defaults to type that matches ArrayBuffer type.

wrap number <optional>

Texture wrapping for both S and T. Defaults to gl.REPEAT for 2D and gl.CLAMP_TO_EDGE for cube

wrapS number <optional>

Texture wrapping for S. Defaults to gl.REPEAT and gl.CLAMP_TO_EDGE for cube. If set takes precedence over wrap.

wrapT number <optional>

Texture wrapping for T. Defaults to 'gl.REPEATandgl.CLAMP_TO_EDGEfor cube. If set takes precedence overwrap`.

unpackAlignment number <optional>

The gl.UNPACK_ALIGNMENT used when uploading an array. Defaults to 1.

premultiplyAlpha number <optional>

Whether or not to premultiply alpha. Defaults to whatever the current setting is. This lets you set it once before calling twgl.createTexture or twgl.createTextures and only override the current setting for specific textures.

flipY number <optional>

Whether or not to flip the texture vertically on upload. Defaults to whatever the current setting is. This lets you set it once before calling twgl.createTexture or twgl.createTextures and only override the current setting for specific textures.

colorspaceConversion number <optional>

Whether or not to let the browser do colorspace conversion of the texture on upload. Defaults to whatever the current setting is. This lets you set it once before calling twgl.createTexture or twgl.createTextures and only override the current setting for specific textures.

color Array.<number>| ArrayBuffer

color used as temporary 1x1 pixel color for textures loaded async when src is a string. If it's a JavaScript array assumes color is 0 to 1 like most GL colors as in [1, 0, 0, 1] = red=1, green=0, blue=0, alpha=0. Defaults to [0.5, 0.75, 1, 1]. See setDefaultTextureColor. If false texture is set. Can be used to re-load a texture

auto boolean <optional>

If not false then texture working filtering is set automatically for non-power of 2 images and mips are generated for power of 2 images.

cubeFaceOrder number[] <optional>

The order that cube faces are pull out of an img or set of images. The default is

[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]
src Array.<number>| ArrayBuffer| HTMLCanvasElement| HTMLImageElement| HTMLVideoElement| string| Array.<string>| TextureFunc <optional>

source for texture

If string then it's assumed to be a URL to an image. The image will be downloaded async. A usable 1x1 pixel texture will be returned immediatley. The texture will be updated once the image has downloaded. If target is gl.TEXTURE_CUBE_MAP will attempt to divide image into 6 square pieces. 1x6, 6x1, 3x2, 2x3. The pieces will be uploaded in cubeFaceOrder

If string[] then it must have 6 entries, one for each face of a cube map. Target must be gl.TEXTURE_CUBE_MAP.

If HTMLElement then it wil be used immediately to create the contents of the texture. Examples HTMLImageElement, HTMLCanvasElement, HTMLVideoElement.

If number[] or ArrayBuffer it's assumed to be data for a texture. If width or height is not specified it is guessed as follows. First the number of elements is computed by src.length / numComponets where numComponents is derived from format. If target is gl.TEXTURE_CUBE_MAP then numElements is divided by 6. Then

  • If neither width nor height are specified and sqrt(numElements) is an integer width and height are set to sqrt(numElements). Otherwise width = numElements and height = 1.

  • If only one of width or height is specified then the other equals numElements / specifiedDimension.

If number[] will be converted to type.

If src is a function it will be called with a WebGLRenderingContext and these options. Whatever it returns is subject to these rules. So it can return a string url, an HTMLElement an array etc...

If src is undefined then an empty texture will be created of size width by height.

TextureReadyCallback(err, tex, img)

A callback for when an image finished downloading and been uploaded into a texture

Parameters:
Name Type Description
err *

If truthy there was an error.

tex WebGLTexture

the texture.

img HTMLImageElement

the image element.

TexturesReadyCallback(err, tex, options)

A callback for when all images have finished downloading and been uploaded into their respective textures

Parameters:
Name Type Description
err *

If truthy there was an error.

tex WebGLTexture

the texture.

options Object.<string, TextureOptions>

A object of TextureOptions one per texture.