Instantly share code, notes, and snippets.

Embed
What would you like to do?
requirebin sketch
document.body.style.margin = 0;
document.body.style.padding = 0;
const width = window.innerWidth;
const height = window.innerHeight;
const canvas = document.body.appendChild(document.createElement('canvas'))
const fit = require('canvas-fit');
const bezier = require('bezier');
window.addEventListener('resize', fit(canvas), false)
const regl = require('regl')({
canvas: canvas
});
const createFramebuffer = () => {
return regl.framebuffer({
color: regl.texture({
width: width,
height: height,
min: 'linear',
max: 'linear'
}),
depth: false
});
}
const backbuffer = createFramebuffer();
const fbo1 = createFramebuffer();
const fbo2 = createFramebuffer();
const blurFrag = `
precision mediump float;
vec4 blur(sampler2D image, vec2 uv, vec2 resolution, vec2 d) {
vec4 color = vec4(0.0);
vec2 off1 = vec2(1.3846153846) * d;
vec2 off2 = vec2(3.2307692308) * d;
color += texture2D(image, uv) * 0.2270270270;
color += texture2D(image, uv + (off1 / resolution)) * 0.3162162162;
color += texture2D(image, uv - (off1 / resolution)) * 0.3162162162;
color += texture2D(image, uv + (off2 / resolution)) * 0.0702702703;
color += texture2D(image, uv - (off2 / resolution)) * 0.0702702703;
return color;
}
uniform sampler2D fbo;
uniform vec2 resolution;
uniform vec2 direction;
varying vec2 uv;
void main() {
gl_FragColor = blur(fbo, uv, resolution.xy, direction);
}
`;
const blur = regl({
frag: blurFrag,
uniforms: {
fbo: regl.prop('fbo'),
resolution: regl.prop('resolution'),
direction: regl.prop('direction')
},
vert: `
precision mediump float;
attribute vec2 position;
varying vec2 uv;
void main () {
uv = position;
gl_Position = vec4(1.0 - 2.0 * position, 0, 1);
}`,
attributes: {
position: [
-2, 0,
0, -2,
2, 2]
},
count: 3,
framebuffer: regl.prop('framebuffer')
});
const blend = regl({
frag: `
precision mediump float;
uniform sampler2D backbuffer;
uniform sampler2D blur;
varying vec2 uv;
void main() {
vec4 bb = texture2D(backbuffer, uv);
vec4 bl = texture2D(blur, uv);
gl_FragColor = bl + bb;
}
`,
uniforms: {
backbuffer: regl.prop('backbuffer'),
blur: regl.prop('blur')
},
vert: `
precision mediump float;
attribute vec2 position;
varying vec2 uv;
void main () {
uv = position;
gl_Position = vec4(1.0 - 2.0 * position, 0, 1);
}`,
attributes: {
position: [
-2, 0,
0, -2,
2, 2]
},
count: 3
});
const vert = `
precision mediump float;
attribute vec2 position;
varying vec2 uv;
void main() {
gl_Position = vec4(position, 0, 1);
}
`;
const lineFrag = `
precision mediump float;
uniform vec4 color;
void main() {
gl_FragColor = color;
}
`;
const line = regl({
vert: vert,
frag: lineFrag,
attributes: {
position: regl.prop('position')
},
uniforms: {
color: regl.prop('color')
},
count: regl.prop('count'),
primitive: 'lines',
lineWidth: 1,
framebuffer: regl.prop('framebuffer')
});
regl.frame(({ time, viewportWidth, viewportHeight }) => {
regl.clear({
color: [0, 0, 0, 1]
// depth: 1
})
regl({framebuffer: backbuffer}, () => { regl.clear({ color: [0, 0, 0, 1] }); });
line({
framebuffer: backbuffer,
position: [[Math.cos(time), -1], [Math.sin(time), 1]],
color: [0.5, 0.7, 0.3, 0.9],
count: 2
});
blur({
fbo: backbuffer,
direction: [0.0, 1.0],
resolution: [viewportWidth, viewportHeight],
framebuffer: fbo1
});
blur({
fbo: fbo1,
direction: [1.0, 0.0],
resolution: [viewportWidth, viewportHeight],
framebuffer: fbo2
});
blend({
backbuffer: backbuffer,
blur: fbo2
});
})
setTimeout(function(){
;require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = getSize
function getSize(element) {
// Handle cases where the element is not already
// attached to the DOM by briefly appending it
// to document.body, and removing it again later.
if (element === window || element === document.body) {
return [window.innerWidth, window.innerHeight]
}
if (!element.parentNode) {
var temporary = true
document.body.appendChild(element)
}
var bounds = element.getBoundingClientRect()
var styles = getComputedStyle(element)
var height = (bounds.height|0)
+ parse(styles.getPropertyValue('margin-top'))
+ parse(styles.getPropertyValue('margin-bottom'))
var width = (bounds.width|0)
+ parse(styles.getPropertyValue('margin-left'))
+ parse(styles.getPropertyValue('margin-right'))
if (temporary) {
document.body.removeChild(element)
}
return [width, height]
}
function parse(prop) {
return parseFloat(prop) || 0
}
},{}],"canvas-fit":[function(require,module,exports){
var size = require('element-size')
module.exports = fit
var scratch = new Float32Array(2)
function fit(canvas, parent, scale) {
var isSVG = canvas.nodeName.toUpperCase() === 'SVG'
canvas.style.position = canvas.style.position || 'absolute'
canvas.style.top = 0
canvas.style.left = 0
resize.scale = parseFloat(scale || 1)
resize.parent = parent
return resize()
function resize() {
var p = resize.parent || canvas.parentNode
if (typeof p === 'function') {
var dims = p(scratch) || scratch
var width = dims[0]
var height = dims[1]
} else
if (p && p !== document.body) {
var psize = size(p)
var width = psize[0]|0
var height = psize[1]|0
} else {
var width = window.innerWidth
var height = window.innerHeight
}
if (isSVG) {
canvas.setAttribute('width', width * resize.scale + 'px')
canvas.setAttribute('height', height * resize.scale + 'px')
} else {
canvas.width = width * resize.scale
canvas.height = height * resize.scale
}
canvas.style.width = width + 'px'
canvas.style.height = height + 'px'
return resize
}
}
},{"element-size":1}]},{},[])
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL2hvbWUvYWRtaW4vYnJvd3NlcmlmeS1jZG4vbm9kZV9tb2R1bGVzL2Jyb3dzZXJpZnkvbm9kZV9tb2R1bGVzL2Jyb3dzZXItcGFjay9fcHJlbHVkZS5qcyIsIm5vZGVfbW9kdWxlcy9lbGVtZW50LXNpemUvaW5kZXguanMiLCJpbmRleC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQ0FBO0FBQ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ICAgICAgdmFyIGRpbXMgICA9IHAoc2NyYXRjaCkgfHwgc2NyYXRjaFxuICAgICAgdmFyIHdpZHRoICA9IGRpbXNbMF1cbiAgICAgIHZhciBoZWlnaHQgPSBkaW1zWzFdXG4gICAgfSBlbHNlXG4gICAgaWYgKHAgJiYgcCAhPT0gZG9jdW1lbnQuYm9keSkge1xuICAgICAgdmFyIHBzaXplICA9IHNpemUocClcbiAgICAgIHZhciB3aWR0aCAgPSBwc2l6ZVswXXwwXG4gICAgICB2YXIgaGVpZ2h0ID0gcHNpemVbMV18MFxuICAgIH0gZWxzZSB7XG4gICAgICB2YXIgd2lkdGggID0gd2luZG93LmlubmVyV2lkdGhcbiAgICAgIHZhciBoZWlnaHQgPSB3aW5kb3cuaW5uZXJIZWlnaHRcbiAgICB9XG5cbiAgICBpZiAoaXNTVkcpIHtcbiAgICAgIGNhbnZhcy5zZXRBdHRyaWJ1dGUoJ3dpZHRoJywgd2lkdGggKiByZXNpemUuc2NhbGUgKyAncHgnKVxuICAgICAgY2FudmFzLnNldEF0dHJpYnV0ZSgnaGVpZ2h0JywgaGVpZ2h0ICogcmVzaXplLnNjYWxlICsgJ3B4JylcbiAgICB9IGVsc2Uge1xuICAgICAgY2FudmFzLndpZHRoID0gd2lkdGggKiByZXNpemUuc2NhbGVcbiAgICAgIGNhbnZhcy5oZWlnaHQgPSBoZWlnaHQgKiByZXNpemUuc2NhbGVcbiAgICB9XG5cbiAgICBjYW52YXMuc3R5bGUud2lkdGggPSB3aWR0aCArICdweCdcbiAgICBjYW52YXMuc3R5bGUuaGVpZ2h0ID0gaGVpZ2h0ICsgJ3B4J1xuXG4gICAgcmV0dXJuIHJlc2l6ZVxuICB9XG59XG4iXX0=
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"bezier":[function(require,module,exports){
var cache = {
'1': bezier1
, '2': bezier2
, '3': bezier3
, '4': bezier4
}
module.exports = neat
module.exports.prepare = prepare
function neat(arr, t) {
return prepare(arr.length)(arr, t)
}
function prepare(pieces) {
pieces = +pieces|0
if (!pieces) throw new Error('Cannot create a interpolator with no elements')
if (cache[pieces]) return cache[pieces]
var fn = ['var ut = 1 - t', '']
var n = pieces
while (n--) {
for (var j = 0; j < n; j += 1) {
if (n+1 === pieces) {
fn.push('var p'+j+' = arr['+j+'] * ut + arr['+(j+1)+'] * t')
} else
if (n > 1) {
fn.push('p'+j+' = p'+j+' * ut + p'+(j+1)+' * t')
} else {
fn.push('return p'+j+' * ut + p'+(j+1)+' * t')
}
}
if (n > 1) fn.push('')
}
fn = [
'return function bezier'+pieces+'(arr, t) {'
, fn.map(function(s) { return ' ' + s }).join('\n')
, '}'
].join('\n')
return Function(fn)()
}
//
// Including the first four degrees
// manually - there's a slight performance penalty
// to generated code. It's outweighed by
// the gains of the optimisations, but always
// helps to cover the most common cases :)
//
function bezier1(arr) {
return arr[0]
}
function bezier2(arr, t) {
return arr[0] + (arr[1] - arr[0]) * t
}
function bezier3(arr, t) {
var ut = 1 - t
return (arr[0] * ut + arr[1] * t) * ut + (arr[1] * ut + arr[2] * t) * t
}
function bezier4(arr, t) {
var ut = 1 - t
var a1 = arr[1] * ut + arr[2] * t
return ((arr[0] * ut + arr[1] * t) * ut + a1 * t) * ut + (a1 * ut + (arr[2] * ut + arr[3] * t) * t) * t
}
},{}]},{},[])
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL2hvbWUvYWRtaW4vYnJvd3NlcmlmeS1jZG4vbm9kZV9tb2R1bGVzL2Jyb3dzZXJpZnkvbm9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iBiZXppZXI0KGFyciwgdCkge1xuICB2YXIgdXQgPSAxIC0gdFxuICB2YXIgYTEgPSBhcnJbMV0gKiB1dCArIGFyclsyXSAqIHRcbiAgcmV0dXJuICgoYXJyWzBdICogdXQgKyBhcnJbMV0gKiB0KSAqIHV0ICsgYTEgKiB0KSAqIHV0ICsgKGExICogdXQgKyAoYXJyWzJdICogdXQgKyBhcnJbM10gKiB0KSAqIHQpICogdFxufVxuIl19
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var GL_FLOAT = 5126
function AttributeRecord () {
this.state = 0
this.x = 0.0
this.y = 0.0
this.z = 0.0
this.w = 0.0
this.buffer = null
this.size = 0
this.normalized = false
this.type = GL_FLOAT
this.offset = 0
this.stride = 0
this.divisor = 0
}
module.exports = function wrapAttributeState (
gl,
extensions,
limits,
bufferState,
stringStore) {
var NUM_ATTRIBUTES = limits.maxAttributes
var attributeBindings = new Array(NUM_ATTRIBUTES)
for (var i = 0; i < NUM_ATTRIBUTES; ++i) {
attributeBindings[i] = new AttributeRecord()
}
return {
Record: AttributeRecord,
scope: {},
state: attributeBindings
}
}
},{}],2:[function(require,module,exports){
var check = require('./util/check')
var isTypedArray = require('./util/is-typed-array')
var isNDArrayLike = require('./util/is-ndarray')
var values = require('./util/values')
var pool = require('./util/pool')
var arrayTypes = require('./constants/arraytypes.json')
var bufferTypes = require('./constants/dtypes.json')
var usageTypes = require('./constants/usage.json')
var GL_STATIC_DRAW = 0x88E4
var GL_STREAM_DRAW = 0x88E0
var GL_UNSIGNED_BYTE = 5121
var GL_FLOAT = 5126
var DTYPES_SIZES = []
DTYPES_SIZES[5120] = 1 // int8
DTYPES_SIZES[5122] = 2 // int16
DTYPES_SIZES[5124] = 4 // int32
DTYPES_SIZES[5121] = 1 // uint8
DTYPES_SIZES[5123] = 2 // uint16
DTYPES_SIZES[5125] = 4 // uint32
DTYPES_SIZES[5126] = 4 // float32
function typedArrayCode (data) {
return arrayTypes[Object.prototype.toString.call(data)] | 0
}
function copyArray (out, inp) {
for (var i = 0; i < inp.length; ++i) {
out[i] = inp[i]
}
}
function transpose (
result, data, shapeX, shapeY, strideX, strideY, offset) {
var ptr = 0
for (var i = 0; i < shapeX; ++i) {
for (var j = 0; j < shapeY; ++j) {
result[ptr++] = data[strideX * i + strideY * j + offset]
}
}
}
function flatten (result, data, dimension) {
var ptr = 0
for (var i = 0; i < data.length; ++i) {
var v = data[i]
for (var j = 0; j < dimension; ++j) {
result[ptr++] = v[j]
}
}
}
module.exports = function wrapBufferState (gl, stats, config) {
var bufferCount = 0
var bufferSet = {}
function REGLBuffer (type) {
this.id = bufferCount++
this.buffer = gl.createBuffer()
this.type = type
this.usage = GL_STATIC_DRAW
this.byteLength = 0
this.dimension = 1
this.dtype = GL_UNSIGNED_BYTE
this.persistentData = null
if (config.profile) {
this.stats = {size: 0}
}
}
REGLBuffer.prototype.bind = function () {
gl.bindBuffer(this.type, this.buffer)
}
REGLBuffer.prototype.destroy = function () {
destroy(this)
}
var streamPool = []
function createStream (type, data) {
var buffer = streamPool.pop()
if (!buffer) {
buffer = new REGLBuffer(type)
}
buffer.bind()
initBufferFromData(buffer, data, GL_STREAM_DRAW, 0, 1, false)
return buffer
}
function destroyStream (stream) {
streamPool.push(stream)
}
function initBufferFromTypedArray (buffer, data, usage) {
buffer.byteLength = data.byteLength
gl.bufferData(buffer.type, data, usage)
}
function initBufferFromData (buffer, data, usage, dtype, dimension, persist) {
buffer.usage = usage
if (Array.isArray(data)) {
buffer.dtype = dtype || GL_FLOAT
if (data.length > 0) {
var flatData
if (Array.isArray(data[0])) {
buffer.dimension = data[0].length
flatData = pool.allocType(
buffer.dtype,
data.length * buffer.dimension)
flatten(flatData, data, buffer.dimension)
initBufferFromTypedArray(buffer, flatData, usage)
if (persist) {
buffer.persistentData = flatData
} else {
pool.freeType(flatData)
}
} else if (typeof data[0] === 'number') {
buffer.dimension = dimension
var typedData = pool.allocType(buffer.dtype, data.length)
copyArray(typedData, data)
initBufferFromTypedArray(buffer, typedData, usage)
if (persist) {
buffer.persistentData = typedData
} else {
pool.freeType(typedData)
}
} else if (isTypedArray(data[0])) {
buffer.dimension = data[0].length
buffer.dtype = dtype || typedArrayCode(data[0]) || GL_FLOAT
flatData = pool.allocType(
buffer.dtype,
data.length * buffer.dimension)
flatten(flatData, data, buffer.dimension)
initBufferFromTypedArray(buffer, flatData, usage)
if (persist) {
buffer.persistentData = flatData
} else {
pool.freeType(flatData)
}
} else {
check.raise('invalid buffer data')
}
}
} else if (isTypedArray(data)) {
buffer.dtype = dtype || typedArrayCode(data)
buffer.dimension = dimension
initBufferFromTypedArray(buffer, data, usage)
if (persist) {
buffer.persistentData = new Uint8Array(new Uint8Array(data.buffer))
}
} else if (isNDArrayLike(data)) {
var shape = data.shape
var stride = data.stride
var offset = data.offset
var shapeX = 0
var shapeY = 0
var strideX = 0
var strideY = 0
if (shape.length === 1) {
shapeX = shape[0]
shapeY = 1
strideX = stride[0]
strideY = 0
} else if (shape.length === 2) {
shapeX = shape[0]
shapeY = shape[1]
strideX = stride[0]
strideY = stride[1]
} else {
check.raise('invalid shape')
}
buffer.dtype = dtype || typedArrayCode(data.data) || GL_FLOAT
buffer.dimension = shapeY
var transposeData = pool.allocType(buffer.dtype, shapeX * shapeY)
transpose(transposeData,
data.data,
shapeX, shapeY,
strideX, strideY,
offset)
initBufferFromTypedArray(buffer, transposeData, usage)
if (persist) {
buffer.persistentData = transposeData
} else {
pool.freeType(transposeData)
}
} else {
check.raise('invalid buffer data')
}
}
function destroy (buffer) {
stats.bufferCount--
var handle = buffer.buffer
check(handle, 'buffer must not be deleted already')
gl.deleteBuffer(handle)
buffer.buffer = null
delete bufferSet[buffer.id]
}
function createBuffer (options, type, deferInit, persistent) {
stats.bufferCount++
var buffer = new REGLBuffer(type)
bufferSet[buffer.id] = buffer
function reglBuffer (options) {
var usage = GL_STATIC_DRAW
var data = null
var byteLength = 0
var dtype = 0
var dimension = 1
if (Array.isArray(options) ||
isTypedArray(options) ||
isNDArrayLike(options)) {
data = options
} else if (typeof options === 'number') {
byteLength = options | 0
} else if (options) {
check.type(
options, 'object',
'buffer arguments must be an object, a number or an array')
if ('data' in options) {
check(
data === null ||
Array.isArray(data) ||
isTypedArray(data) ||
isNDArrayLike(data),
'invalid data for buffer')
data = options.data
}
if ('usage' in options) {
check.parameter(options.usage, usageTypes, 'invalid buffer usage')
usage = usageTypes[options.usage]
}
if ('type' in options) {
check.parameter(options.type, bufferTypes, 'invalid buffer type')
dtype = bufferTypes[options.type]
}
if ('dimension' in options) {
check.type(options.dimension, 'number', 'invalid dimension')
dimension = options.dimension | 0
}
if ('length' in options) {
check.nni(byteLength, 'buffer length must be a nonnegative integer')
byteLength = options.length | 0
}
}
buffer.bind()
if (!data) {
gl.bufferData(buffer.type, byteLength, usage)
buffer.dtype = dtype || GL_UNSIGNED_BYTE
buffer.usage = usage
buffer.dimension = dimension
buffer.byteLength = byteLength
} else {
initBufferFromData(buffer, data, usage, dtype, dimension, persistent)
}
if (config.profile) {
buffer.stats.size = buffer.byteLength * DTYPES_SIZES[buffer.dtype]
}
return reglBuffer
}
function setSubData (data, offset) {
check(offset + data.byteLength <= buffer.byteLength,
'invalid buffer subdata call, buffer is too small. ' + ' Can\'t write data of size ' + data.byteLength + ' starting from offset ' + offset + ' to a buffer of size ' + buffer.byteLength)
gl.bufferSubData(buffer.type, offset, data)
}
function subdata (data, offset_) {
var offset = (offset_ || 0) | 0
buffer.bind()
if (Array.isArray(data)) {
if (data.length > 0) {
if (typeof data[0] === 'number') {
var converted = pool.allocType(buffer.dtype, data.length)
copyArray(converted, data)
setSubData(converted, offset)
pool.freeType(converted)
} else if (Array.isArray(data[0]) || isTypedArray(data[0])) {
var dimension = data[0].length
var flatData = pool.allocType(buffer.dtype, data.length * dimension)
flatten(flatData, data, dimension)
setSubData(flatData, offset)
pool.freeType(flatData)
} else {
check.raise('invalid buffer data')
}
}
} else if (isTypedArray(data)) {
setSubData(data, offset)
} else if (isNDArrayLike(data)) {
var shape = data.shape
var stride = data.stride
var shapeX = 0
var shapeY = 0
var strideX = 0
var strideY = 0
if (shape.length === 1) {
shapeX = shape[0]
shapeY = 1
strideX = stride[0]
strideY = 0
} else if (shape.length === 2) {
shapeX = shape[0]
shapeY = shape[1]
strideX = stride[0]
strideY = stride[1]
} else {
check.raise('invalid shape')
}
var dtype = Array.isArray(data.data)
? buffer.dtype
: typedArrayCode(data.data)
var transposeData = pool.allocType(dtype, shapeX * shapeY)
transpose(transposeData,
data.data,
shapeX, shapeY,
strideX, strideY,
data.offset)
setSubData(transposeData, offset)
pool.freeType(transposeData)
} else {
check.raise('invalid data for buffer subdata')
}
return reglBuffer
}
if (!deferInit) {
reglBuffer(options)
}
reglBuffer._reglType = 'buffer'
reglBuffer._buffer = buffer
reglBuffer.subdata = subdata
if (config.profile) {
reglBuffer.stats = buffer.stats
}
reglBuffer.destroy = function () { destroy(buffer) }
return reglBuffer
}
function restoreBuffers () {
values(bufferSet).forEach(function (buffer) {
buffer.buffer = gl.createBuffer()
gl.bindBuffer(buffer.type, buffer.buffer)
gl.bufferData(
buffer.type, buffer.persistentData || buffer.byteLength, buffer.usage)
})
}
if (config.profile) {
stats.getTotalBufferSize = function () {
var total = 0
// TODO: Right now, the streams are not part of the total count.
Object.keys(bufferSet).forEach(function (key) {
total += bufferSet[key].stats.size
})
return total
}
}
return {
create: createBuffer,
createStream: createStream,
destroyStream: destroyStream,
clear: function () {
values(bufferSet).forEach(destroy)
streamPool.forEach(destroy)
},
getBuffer: function (wrapper) {
if (wrapper && wrapper._buffer instanceof REGLBuffer) {
return wrapper._buffer
}
return null
},
restore: restoreBuffers,
_initBuffer: initBufferFromData
}
}
},{"./constants/arraytypes.json":3,"./constants/dtypes.json":4,"./constants/usage.json":6,"./util/check":20,"./util/is-ndarray":25,"./util/is-typed-array":26,"./util/pool":28,"./util/values":31}],3:[function(require,module,exports){
module.exports={
"[object Int8Array]": 5120
, "[object Int16Array]": 5122
, "[object Int32Array]": 5124
, "[object Uint8Array]": 5121
, "[object Uint8ClampedArray]": 5121
, "[object Uint16Array]": 5123
, "[object Uint32Array]": 5125
, "[object Float32Array]": 5126
, "[object Float64Array]": 5121
, "[object ArrayBuffer]": 5121
}
},{}],4:[function(require,module,exports){
module.exports={
"int8": 5120
, "int16": 5122
, "int32": 5124
, "uint8": 5121
, "uint16": 5123
, "uint32": 5125
, "float": 5126
, "float32": 5126
}
},{}],5:[function(require,module,exports){
module.exports={
"points": 0,
"point": 0,
"lines": 1,
"line": 1,
"line loop": 2,
"line strip": 3,
"triangles": 4,
"triangle": 4,
"triangle strip": 5,
"triangle fan": 6
}
},{}],6:[function(require,module,exports){
module.exports={
"static": 35044,
"dynamic": 35048,
"stream": 35040
}
},{}],7:[function(require,module,exports){
var check = require('./util/check')
var createEnvironment = require('./util/codegen')
var loop = require('./util/loop')
var isTypedArray = require('./util/is-typed-array')
var isNDArray = require('./util/is-ndarray')
var isArrayLike = require('./util/is-array-like')
var dynamic = require('./dynamic')
var primTypes = require('./constants/primitives.json')
var glTypes = require('./constants/dtypes.json')
// "cute" names for vector components
var CUTE_COMPONENTS = 'xyzw'.split('')
var GL_UNSIGNED_BYTE = 5121
var ATTRIB_STATE_POINTER = 1
var ATTRIB_STATE_CONSTANT = 2
var DYN_FUNC = 0
var DYN_PROP = 1
var DYN_CONTEXT = 2
var DYN_STATE = 3
var DYN_THUNK = 4
var S_DITHER = 'dither'
var S_BLEND_ENABLE = 'blend.enable'
var S_BLEND_COLOR = 'blend.color'
var S_BLEND_EQUATION = 'blend.equation'
var S_BLEND_FUNC = 'blend.func'
var S_DEPTH_ENABLE = 'depth.enable'
var S_DEPTH_FUNC = 'depth.func'
var S_DEPTH_RANGE = 'depth.range'
var S_DEPTH_MASK = 'depth.mask'
var S_COLOR_MASK = 'colorMask'
var S_CULL_ENABLE = 'cull.enable'
var S_CULL_FACE = 'cull.face'
var S_FRONT_FACE = 'frontFace'
var S_LINE_WIDTH = 'lineWidth'
var S_POLYGON_OFFSET_ENABLE = 'polygonOffset.enable'
var S_POLYGON_OFFSET_OFFSET = 'polygonOffset.offset'
var S_SAMPLE_ALPHA = 'sample.alpha'
var S_SAMPLE_ENABLE = 'sample.enable'
var S_SAMPLE_COVERAGE = 'sample.coverage'
var S_STENCIL_ENABLE = 'stencil.enable'
var S_STENCIL_MASK = 'stencil.mask'
var S_STENCIL_FUNC = 'stencil.func'
var S_STENCIL_OPFRONT = 'stencil.opFront'
var S_STENCIL_OPBACK = 'stencil.opBack'
var S_SCISSOR_ENABLE = 'scissor.enable'
var S_SCISSOR_BOX = 'scissor.box'
var S_VIEWPORT = 'viewport'
var S_PROFILE = 'profile'
var S_FRAMEBUFFER = 'framebuffer'
var S_VERT = 'vert'
var S_FRAG = 'frag'
var S_ELEMENTS = 'elements'
var S_PRIMITIVE = 'primitive'
var S_COUNT = 'count'
var S_OFFSET = 'offset'
var S_INSTANCES = 'instances'
var SUFFIX_WIDTH = 'Width'
var SUFFIX_HEIGHT = 'Height'
var S_FRAMEBUFFER_WIDTH = S_FRAMEBUFFER + SUFFIX_WIDTH
var S_FRAMEBUFFER_HEIGHT = S_FRAMEBUFFER + SUFFIX_HEIGHT
var S_VIEWPORT_WIDTH = S_VIEWPORT + SUFFIX_WIDTH
var S_VIEWPORT_HEIGHT = S_VIEWPORT + SUFFIX_HEIGHT
var S_DRAWINGBUFFER = 'drawingBuffer'
var S_DRAWINGBUFFER_WIDTH = S_DRAWINGBUFFER + SUFFIX_WIDTH
var S_DRAWINGBUFFER_HEIGHT = S_DRAWINGBUFFER + SUFFIX_HEIGHT
var NESTED_OPTIONS = [
S_BLEND_FUNC,
S_BLEND_EQUATION,
S_STENCIL_FUNC,
S_STENCIL_OPFRONT,
S_STENCIL_OPBACK,
S_SAMPLE_COVERAGE,
S_VIEWPORT,
S_SCISSOR_BOX,
S_POLYGON_OFFSET_OFFSET
]
var GL_ARRAY_BUFFER = 34962
var GL_ELEMENT_ARRAY_BUFFER = 34963
var GL_FRAGMENT_SHADER = 35632
var GL_VERTEX_SHADER = 35633
var GL_TEXTURE_2D = 0x0DE1
var GL_TEXTURE_CUBE_MAP = 0x8513
var GL_CULL_FACE = 0x0B44
var GL_BLEND = 0x0BE2
var GL_DITHER = 0x0BD0
var GL_STENCIL_TEST = 0x0B90
var GL_DEPTH_TEST = 0x0B71
var GL_SCISSOR_TEST = 0x0C11
var GL_POLYGON_OFFSET_FILL = 0x8037
var GL_SAMPLE_ALPHA_TO_COVERAGE = 0x809E
var GL_SAMPLE_COVERAGE = 0x80A0
var GL_FLOAT = 5126
var GL_FLOAT_VEC2 = 35664
var GL_FLOAT_VEC3 = 35665
var GL_FLOAT_VEC4 = 35666
var GL_INT = 5124
var GL_INT_VEC2 = 35667
var GL_INT_VEC3 = 35668
var GL_INT_VEC4 = 35669
var GL_BOOL = 35670
var GL_BOOL_VEC2 = 35671
var GL_BOOL_VEC3 = 35672
var GL_BOOL_VEC4 = 35673
var GL_FLOAT_MAT2 = 35674
var GL_FLOAT_MAT3 = 35675
var GL_FLOAT_MAT4 = 35676
var GL_SAMPLER_2D = 35678
var GL_SAMPLER_CUBE = 35680
var GL_TRIANGLES = 4
var GL_FRONT = 1028
var GL_BACK = 1029
var GL_CW = 0x0900
var GL_CCW = 0x0901
var GL_MIN_EXT = 0x8007
var GL_MAX_EXT = 0x8008
var GL_ALWAYS = 519
var GL_KEEP = 7680
var GL_ZERO = 0
var GL_ONE = 1
var GL_FUNC_ADD = 0x8006
var GL_LESS = 513
var GL_FRAMEBUFFER = 0x8D40
var GL_COLOR_ATTACHMENT0 = 0x8CE0
var blendFuncs = {
'0': 0,
'1': 1,
'zero': 0,
'one': 1,
'src color': 768,
'one minus src color': 769,
'src alpha': 770,
'one minus src alpha': 771,
'dst color': 774,
'one minus dst color': 775,
'dst alpha': 772,
'one minus dst alpha': 773,
'constant color': 32769,
'one minus constant color': 32770,
'constant alpha': 32771,
'one minus constant alpha': 32772,
'src alpha saturate': 776
}
// There are invalid values for srcRGB and dstRGB. See:
// https://www.khronos.org/registry/webgl/specs/1.0/#6.13
// https://github.com/KhronosGroup/WebGL/blob/0d3201f5f7ec3c0060bc1f04077461541f1987b9/conformance-suites/1.0.3/conformance/misc/webgl-specific.html#L56
var invalidBlendCombinations = [
'constant color, constant alpha',
'one minus constant color, constant alpha',
'constant color, one minus constant alpha',
'one minus constant color, one minus constant alpha',
'constant alpha, constant color',
'constant alpha, one minus constant color',
'one minus constant alpha, constant color',
'one minus constant alpha, one minus constant color'
]
var compareFuncs = {
'never': 512,
'less': 513,
'<': 513,
'equal': 514,
'=': 514,
'==': 514,
'===': 514,
'lequal': 515,
'<=': 515,
'greater': 516,
'>': 516,
'notequal': 517,
'!=': 517,
'!==': 517,
'gequal': 518,
'>=': 518,
'always': 519
}
var stencilOps = {
'0': 0,
'zero': 0,
'keep': 7680,
'replace': 7681,
'increment': 7682,
'decrement': 7683,
'increment wrap': 34055,
'decrement wrap': 34056,
'invert': 5386
}
var shaderType = {
'frag': GL_FRAGMENT_SHADER,
'vert': GL_VERTEX_SHADER
}
var orientationType = {
'cw': GL_CW,
'ccw': GL_CCW
}
function isBufferArgs (x) {
return Array.isArray(x) ||
isTypedArray(x) ||
isNDArray(x)
}
// Make sure viewport is processed first
function sortState (state) {
return state.sort(function (a, b) {
if (a === S_VIEWPORT) {
return -1
} else if (b === S_VIEWPORT) {
return 1
}
return (a < b) ? -1 : 1
})
}
function Declaration (thisDep, contextDep, propDep, append) {
this.thisDep = thisDep
this.contextDep = contextDep
this.propDep = propDep
this.append = append
}
function isStatic (decl) {
return decl && !(decl.thisDep || decl.contextDep || decl.propDep)
}
function createStaticDecl (append) {
return new Declaration(false, false, false, append)
}
function createDynamicDecl (dyn, append) {
var type = dyn.type
if (type === DYN_FUNC) {
var numArgs = dyn.data.length
return new Declaration(
true,
numArgs >= 1,
numArgs >= 2,
append)
} else if (type === DYN_THUNK) {
var data = dyn.data
return new Declaration(
data.thisDep,
data.contextDep,
data.propDep,
append)
} else {
return new Declaration(
type === DYN_STATE,
type === DYN_CONTEXT,
type === DYN_PROP,
append)
}
}
var SCOPE_DECL = new Declaration(false, false, false, function () {})
module.exports = function reglCore (
gl,
stringStore,
extensions,
limits,
bufferState,
elementState,
textureState,
framebufferState,
uniformState,
attributeState,
shaderState,
drawState,
contextState,
timer,
config) {
var AttributeRecord = attributeState.Record
var blendEquations = {
'add': 32774,
'subtract': 32778,
'reverse subtract': 32779
}
if (extensions.ext_blend_minmax) {
blendEquations.min = GL_MIN_EXT
blendEquations.max = GL_MAX_EXT
}
var extInstancing = extensions.angle_instanced_arrays
var extDrawBuffers = extensions.webgl_draw_buffers
// ===================================================
// ===================================================
// WEBGL STATE
// ===================================================
// ===================================================
var currentState = {
dirty: true,
profile: config.profile
}
var nextState = {}
var GL_STATE_NAMES = []
var GL_FLAGS = {}
var GL_VARIABLES = {}
function propName (name) {
return name.replace('.', '_')
}
function stateFlag (sname, cap, init) {
var name = propName(sname)
GL_STATE_NAMES.push(sname)
nextState[name] = currentState[name] = !!init
GL_FLAGS[name] = cap
}
function stateVariable (sname, func, init) {
var name = propName(sname)
GL_STATE_NAMES.push(sname)
if (Array.isArray(init)) {
currentState[name] = init.slice()
nextState[name] = init.slice()
} else {
currentState[name] = nextState[name] = init
}
GL_VARIABLES[name] = func
}
// Dithering
stateFlag(S_DITHER, GL_DITHER)
// Blending
stateFlag(S_BLEND_ENABLE, GL_BLEND)
stateVariable(S_BLEND_COLOR, 'blendColor', [0, 0, 0, 0])
stateVariable(S_BLEND_EQUATION, 'blendEquationSeparate',
[GL_FUNC_ADD, GL_FUNC_ADD])
stateVariable(S_BLEND_FUNC, 'blendFuncSeparate',
[GL_ONE, GL_ZERO, GL_ONE, GL_ZERO])
// Depth
stateFlag(S_DEPTH_ENABLE, GL_DEPTH_TEST, true)
stateVariable(S_DEPTH_FUNC, 'depthFunc', GL_LESS)
stateVariable(S_DEPTH_RANGE, 'depthRange', [0, 1])
stateVariable(S_DEPTH_MASK, 'depthMask', true)
// Color mask
stateVariable(S_COLOR_MASK, S_COLOR_MASK, [true, true, true, true])
// Face culling
stateFlag(S_CULL_ENABLE, GL_CULL_FACE)
stateVariable(S_CULL_FACE, 'cullFace', GL_BACK)
// Front face orientation
stateVariable(S_FRONT_FACE, S_FRONT_FACE, GL_CCW)
// Line width
stateVariable(S_LINE_WIDTH, S_LINE_WIDTH, 1)
// Polygon offset
stateFlag(S_POLYGON_OFFSET_ENABLE, GL_POLYGON_OFFSET_FILL)
stateVariable(S_POLYGON_OFFSET_OFFSET, 'polygonOffset', [0, 0])
// Sample coverage
stateFlag(S_SAMPLE_ALPHA, GL_SAMPLE_ALPHA_TO_COVERAGE)
stateFlag(S_SAMPLE_ENABLE, GL_SAMPLE_COVERAGE)
stateVariable(S_SAMPLE_COVERAGE, 'sampleCoverage', [1, false])
// Stencil
stateFlag(S_STENCIL_ENABLE, GL_STENCIL_TEST)
stateVariable(S_STENCIL_MASK, 'stencilMask', -1)
stateVariable(S_STENCIL_FUNC, 'stencilFunc', [GL_ALWAYS, 0, -1])
stateVariable(S_STENCIL_OPFRONT, 'stencilOpSeparate',
[GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP])
stateVariable(S_STENCIL_OPBACK, 'stencilOpSeparate',
[GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP])
// Scissor
stateFlag(S_SCISSOR_ENABLE, GL_SCISSOR_TEST)
stateVariable(S_SCISSOR_BOX, 'scissor',
[0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight])
// Viewport
stateVariable(S_VIEWPORT, S_VIEWPORT,
[0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight])
// ===================================================
// ===================================================
// ENVIRONMENT
// ===================================================
// ===================================================
var sharedState = {
gl: gl,
context: contextState,
strings: stringStore,
next: nextState,
current: currentState,
draw: drawState,
elements: elementState,
buffer: bufferState,
shader: shaderState,
attributes: attributeState.state,
uniforms: uniformState,
framebuffer: framebufferState,
extensions: extensions,
timer: timer,
isBufferArgs: isBufferArgs
}
var sharedConstants = {
primTypes: primTypes,
compareFuncs: compareFuncs,
blendFuncs: blendFuncs,
blendEquations: blendEquations,
stencilOps: stencilOps,
glTypes: glTypes,
orientationType: orientationType
}
check.optional(function () {
sharedState.isArrayLike = isArrayLike
})
if (extDrawBuffers) {
sharedConstants.backBuffer = [GL_BACK]
sharedConstants.drawBuffer = loop(limits.maxDrawbuffers, function (i) {
if (i === 0) {
return [0]
}
return loop(i, function (j) {
return GL_COLOR_ATTACHMENT0 + j
})
})
}
var drawCallCounter = 0
function createREGLEnvironment () {
var env = createEnvironment()
var link = env.link
var global = env.global
env.id = drawCallCounter++
env.batchId = '0'
// link shared state
var SHARED = link(sharedState)
var shared = env.shared = {
props: 'a0'
}
Object.keys(sharedState).forEach(function (prop) {
shared[prop] = global.def(SHARED, '.', prop)
})
// Inject runtime assertion stuff for debug builds
check.optional(function () {
env.CHECK = link(check)
env.commandStr = check.guessCommand()
env.command = link(env.commandStr)
env.assert = function (block, pred, message) {
block(
'if(!(', pred, '))',
this.CHECK, '.commandRaise(', link(message), ',', this.command, ');')
}
sharedConstants.invalidBlendCombinations = invalidBlendCombinations
})
// Copy GL state variables over
var nextVars = env.next = {}
var currentVars = env.current = {}
Object.keys(GL_VARIABLES).forEach(function (variable) {
if (Array.isArray(currentState[variable])) {
nextVars[variable] = global.def(shared.next, '.', variable)
currentVars[variable] = global.def(shared.current, '.', variable)
}
})
// Initialize shared constants
var constants = env.constants = {}
Object.keys(sharedConstants).forEach(function (name) {
constants[name] = global.def(JSON.stringify(sharedConstants[name]))
})
// Helper function for calling a block
env.invoke = function (block, x) {
switch (x.type) {
case DYN_FUNC:
var argList = [
'this',
shared.context,
shared.props,
env.batchId
]
return block.def(
link(x.data), '.call(',
argList.slice(0, Math.max(x.data.length + 1, 4)),
')')
case DYN_PROP:
return block.def(shared.props, x.data)
case DYN_CONTEXT:
return block.def(shared.context, x.data)
case DYN_STATE:
return block.def('this', x.data)
case DYN_THUNK:
x.data.append(env, block)
return x.data.ref
}
}
env.attribCache = {}
var scopeAttribs = {}
env.scopeAttrib = function (name) {
var id = stringStore.id(name)
if (id in scopeAttribs) {
return scopeAttribs[id]
}
var binding = attributeState.scope[id]
if (!binding) {
binding = attributeState.scope[id] = new AttributeRecord()
}
var result = scopeAttribs[id] = link(binding)
return result
}
return env
}
// ===================================================
// ===================================================
// PARSING
// ===================================================
// ===================================================
function parseProfile (options) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
var profileEnable
if (S_PROFILE in staticOptions) {
var value = !!staticOptions[S_PROFILE]
profileEnable = createStaticDecl(function (env, scope) {
return value
})
profileEnable.enable = value
} else if (S_PROFILE in dynamicOptions) {
var dyn = dynamicOptions[S_PROFILE]
profileEnable = createDynamicDecl(dyn, function (env, scope) {
return env.invoke(scope, dyn)
})
}
return profileEnable
}
function parseFramebuffer (options, env) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
if (S_FRAMEBUFFER in staticOptions) {
var framebuffer = staticOptions[S_FRAMEBUFFER]
if (framebuffer) {
framebuffer = framebufferState.getFramebuffer(framebuffer)
check.command(framebuffer, 'invalid framebuffer object')
return createStaticDecl(function (env, block) {
var FRAMEBUFFER = env.link(framebuffer)
var shared = env.shared
block.set(
shared.framebuffer,
'.next',
FRAMEBUFFER)
var CONTEXT = shared.context
block.set(
CONTEXT,
'.' + S_FRAMEBUFFER_WIDTH,
FRAMEBUFFER + '.width')
block.set(
CONTEXT,
'.' + S_FRAMEBUFFER_HEIGHT,
FRAMEBUFFER + '.height')
return FRAMEBUFFER
})
} else {
return createStaticDecl(function (env, scope) {
var shared = env.shared
scope.set(
shared.framebuffer,
'.next',
'null')
var CONTEXT = shared.context
scope.set(
CONTEXT,
'.' + S_FRAMEBUFFER_WIDTH,
CONTEXT + '.' + S_DRAWINGBUFFER_WIDTH)
scope.set(
CONTEXT,
'.' + S_FRAMEBUFFER_HEIGHT,
CONTEXT + '.' + S_DRAWINGBUFFER_HEIGHT)
return 'null'
})
}
} else if (S_FRAMEBUFFER in dynamicOptions) {
var dyn = dynamicOptions[S_FRAMEBUFFER]
return createDynamicDecl(dyn, function (env, scope) {
var FRAMEBUFFER_FUNC = env.invoke(scope, dyn)
var shared = env.shared
var FRAMEBUFFER_STATE = shared.framebuffer
var FRAMEBUFFER = scope.def(
FRAMEBUFFER_STATE, '.getFramebuffer(', FRAMEBUFFER_FUNC, ')')
check.optional(function () {
env.assert(scope,
'!' + FRAMEBUFFER_FUNC + '||' + FRAMEBUFFER,
'invalid framebuffer object')
})
scope.set(
FRAMEBUFFER_STATE,
'.next',
FRAMEBUFFER)
var CONTEXT = shared.context
scope.set(
CONTEXT,
'.' + S_FRAMEBUFFER_WIDTH,
FRAMEBUFFER + '?' + FRAMEBUFFER + '.width:' +
CONTEXT + '.' + S_DRAWINGBUFFER_WIDTH)
scope.set(
CONTEXT,
'.' + S_FRAMEBUFFER_HEIGHT,
FRAMEBUFFER +
'?' + FRAMEBUFFER + '.height:' +
CONTEXT + '.' + S_DRAWINGBUFFER_HEIGHT)
return FRAMEBUFFER
})
} else {
return null
}
}
function parseViewportScissor (options, framebuffer, env) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
function parseBox (param) {
if (param in staticOptions) {
var box = staticOptions[param]
check.commandType(box, 'object', 'invalid ' + param, env.commandStr)
var isStatic = true
var x = box.x | 0
var y = box.y | 0
check.command(x >= 0 && y >= 0, 'invalid ' + param, env.commandStr)
var w, h
if ('width' in box) {
w = box.width | 0
check.command(w > 0, 'invalid ' + param, env.commandStr)
} else {
isStatic = false
}
if ('height' in box) {
h = box.height | 0
check.command(h > 0, 'invalid ' + param, env.commandStr)
} else {
isStatic = false
}
return new Declaration(
!isStatic && framebuffer && framebuffer.thisDep,
!isStatic && framebuffer && framebuffer.contextDep,
!isStatic && framebuffer && framebuffer.propDep,
function (env, scope) {
var CONTEXT = env.shared.context
var BOX_W = w
if (!('width' in box)) {
BOX_W = scope.def(CONTEXT, '.', S_FRAMEBUFFER_WIDTH, '-', x)
} else {
check.command(w > 0, 'invalid ' + param, env.commandStr)
}
var BOX_H = h
if (!('height' in box)) {
BOX_H = scope.def(CONTEXT, '.', S_FRAMEBUFFER_HEIGHT, '-', y)
} else {
check.command(h > 0, 'invalid ' + param, env.commandStr)
}
return [x, y, BOX_W, BOX_H]
})
} else if (param in dynamicOptions) {
var dynBox = dynamicOptions[param]
var result = createDynamicDecl(dynBox, function (env, scope) {
var BOX = env.invoke(scope, dynBox)
check.optional(function () {
env.assert(scope,
BOX + '&&typeof ' + BOX + '==="object"',
'invalid ' + param)
})
var CONTEXT = env.shared.context
var BOX_X = scope.def(BOX, '.x|0')
var BOX_Y = scope.def(BOX, '.y|0')
var BOX_W = scope.def(
'"width" in ', BOX, '?', BOX, '.width|0:',
'(', CONTEXT, '.', S_FRAMEBUFFER_WIDTH, '-', BOX_X, ')')
var BOX_H = scope.def(
'"height" in ', BOX, '?', BOX, '.height|0:',
'(', CONTEXT, '.', S_FRAMEBUFFER_HEIGHT, '-', BOX_Y, ')')
check.optional(function () {
env.assert(scope,
BOX_X + '>=0&&' +
BOX_Y + '>=0&&' +
BOX_W + '>0&&' +
BOX_H + '>0',
'invalid ' + param)
})
return [BOX_X, BOX_Y, BOX_W, BOX_H]
})
if (framebuffer) {
result.thisDep = result.thisDep || framebuffer.thisDep
result.contextDep = result.contextDep || framebuffer.contextDep
result.propDep = result.propDep || framebuffer.propDep
}
return result
} else if (framebuffer) {
return new Declaration(
framebuffer.thisDep,
framebuffer.contextDep,
framebuffer.propDep,
function (env, scope) {
var CONTEXT = env.shared.context
return [
0, 0,
scope.def(CONTEXT, '.', S_FRAMEBUFFER_WIDTH),
scope.def(CONTEXT, '.', S_FRAMEBUFFER_HEIGHT)]
})
} else {
return null
}
}
var viewport = parseBox(S_VIEWPORT)
if (viewport) {
var prevViewport = viewport
viewport = new Declaration(
viewport.thisDep,
viewport.contextDep,
viewport.propDep,
function (env, scope) {
var VIEWPORT = prevViewport.append(env, scope)
var CONTEXT = env.shared.context
scope.set(
CONTEXT,
'.' + S_VIEWPORT_WIDTH,
VIEWPORT[2])
scope.set(
CONTEXT,
'.' + S_VIEWPORT_HEIGHT,
VIEWPORT[3])
return VIEWPORT
})
}
return {
viewport: viewport,
scissor_box: parseBox(S_SCISSOR_BOX)
}
}
function parseProgram (options) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
function parseShader (name) {
if (name in staticOptions) {
var id = stringStore.id(staticOptions[name])
check.optional(function () {
shaderState.shader(shaderType[name], id, check.guessCommand())
})
var result = createStaticDecl(function () {
return id
})
result.id = id
return result
} else if (name in dynamicOptions) {
var dyn = dynamicOptions[name]
return createDynamicDecl(dyn, function (env, scope) {
var str = env.invoke(scope, dyn)
var id = scope.def(env.shared.strings, '.id(', str, ')')
check.optional(function () {
scope(
env.shared.shader, '.shader(',
shaderType[name], ',',
id, ',',
env.command, ');')
})
return id
})
}
return null
}
var frag = parseShader(S_FRAG)
var vert = parseShader(S_VERT)
var program = null
var progVar
if (isStatic(frag) && isStatic(vert)) {
program = shaderState.program(vert.id, frag.id)
progVar = createStaticDecl(function (env, scope) {
return env.link(program)
})
} else {
progVar = new Declaration(
(frag && frag.thisDep) || (vert && vert.thisDep),
(frag && frag.contextDep) || (vert && vert.contextDep),
(frag && frag.propDep) || (vert && vert.propDep),
function (env, scope) {
var SHADER_STATE = env.shared.shader
var fragId
if (frag) {
fragId = frag.append(env, scope)
} else {
fragId = scope.def(SHADER_STATE, '.', S_FRAG)
}
var vertId
if (vert) {
vertId = vert.append(env, scope)
} else {
vertId = scope.def(SHADER_STATE, '.', S_VERT)
}
var progDef = SHADER_STATE + '.program(' + vertId + ',' + fragId
check.optional(function () {
progDef += ',' + env.command
})
return scope.def(progDef + ')')
})
}
return {
frag: frag,
vert: vert,
progVar: progVar,
program: program
}
}
function parseDraw (options, env) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
function parseElements () {
if (S_ELEMENTS in staticOptions) {
var elements = staticOptions[S_ELEMENTS]
if (isBufferArgs(elements)) {
elements = elementState.getElements(elementState.create(elements, true))
} else if (elements) {
elements = elementState.getElements(elements)
check.command(elements, 'invalid elements', env.commandStr)
}
var result = createStaticDecl(function (env, scope) {
if (elements) {
var result = env.link(elements)
env.ELEMENTS = result
return result
}
env.ELEMENTS = null
return null
})
result.value = elements
return result
} else if (S_ELEMENTS in dynamicOptions) {
var dyn = dynamicOptions[S_ELEMENTS]
return createDynamicDecl(dyn, function (env, scope) {
var shared = env.shared
var IS_BUFFER_ARGS = shared.isBufferArgs
var ELEMENT_STATE = shared.elements
var elementDefn = env.invoke(scope, dyn)
var elements = scope.def('null')
var elementStream = scope.def(IS_BUFFER_ARGS, '(', elementDefn, ')')
var ifte = env.cond(elementStream)
.then(elements, '=', ELEMENT_STATE, '.createStream(', elementDefn, ');')
.else(elements, '=', ELEMENT_STATE, '.getElements(', elementDefn, ');')
check.optional(function () {
env.assert(ifte.else,
'!' + elementDefn + '||' + elements,
'invalid elements')
})
scope.entry(ifte)
scope.exit(
env.cond(elementStream)
.then(ELEMENT_STATE, '.destroyStream(', elements, ');'))
env.ELEMENTS = elements
return elements
})
}
return null
}
var elements = parseElements()
function parsePrimitive () {
if (S_PRIMITIVE in staticOptions) {
var primitive = staticOptions[S_PRIMITIVE]
check.commandParameter(primitive, primTypes, 'invalid primitve', env.commandStr)
return createStaticDecl(function (env, scope) {
return primTypes[primitive]
})
} else if (S_PRIMITIVE in dynamicOptions) {
var dynPrimitive = dynamicOptions[S_PRIMITIVE]
return createDynamicDecl(dynPrimitive, function (env, scope) {
var PRIM_TYPES = env.constants.primTypes
var prim = env.invoke(scope, dynPrimitive)
check.optional(function () {
env.assert(scope,
prim + ' in ' + PRIM_TYPES,
'invalid primitive, must be one of ' + Object.keys(primTypes))
})
return scope.def(PRIM_TYPES, '[', prim, ']')
})
} else if (elements) {
if (isStatic(elements)) {
if (elements.value) {
return createStaticDecl(function (env, scope) {
return scope.def(env.ELEMENTS, '.primType')
})
} else {
return createStaticDecl(function () {
return GL_TRIANGLES
})
}
} else {
return new Declaration(
elements.thisDep,
elements.contextDep,
elements.propDep,
function (env, scope) {
var elements = env.ELEMENTS
return scope.def(elements, '?', elements, '.primType:', GL_TRIANGLES)
})
}
}
return null
}
function parseParam (param, isOffset) {
if (param in staticOptions) {
var value = staticOptions[param] | 0
check.command(!isOffset || value >= 0, 'invalid ' + param, env.commandStr)
return createStaticDecl(function (env, scope) {
if (isOffset) {
env.OFFSET = value
}
return value
})
} else if (param in dynamicOptions) {
var dynValue = dynamicOptions[param]
return createDynamicDecl(dynValue, function (env, scope) {
var result = env.invoke(scope, dynValue)
if (isOffset) {
env.OFFSET = result
check.optional(function () {
env.assert(scope,
result + '>=0',
'invalid ' + param)
})
}
return result
})
} else if (isOffset && elements) {
return createStaticDecl(function (env, scope) {
env.OFFSET = '0'
return 0
})
}
return null
}
var OFFSET = parseParam(S_OFFSET, true)
function parseVertCount () {
if (S_COUNT in staticOptions) {
var count = staticOptions[S_COUNT] | 0
check.command(
typeof count === 'number' && count >= 0, 'invalid vertex count', env.commandStr)
return createStaticDecl(function () {
return count
})
} else if (S_COUNT in dynamicOptions) {
var dynCount = dynamicOptions[S_COUNT]
return createDynamicDecl(dynCount, function (env, scope) {
var result = env.invoke(scope, dynCount)
check.optional(function () {
env.assert(scope,
'typeof ' + result + '==="number"&&' +
result + '>=0&&' +
result + '===(' + result + '|0)',
'invalid vertex count')
})
return result
})
} else if (elements) {
if (isStatic(elements)) {
if (elements) {
if (OFFSET) {
return new Declaration(
OFFSET.thisDep,
OFFSET.contextDep,
OFFSET.propDep,
function (env, scope) {
var result = scope.def(
env.ELEMENTS, '.vertCount-', env.OFFSET)
check.optional(function () {
env.assert(scope,
result + '>=0',
'invalid vertex offset/element buffer too small')
})
return result
})
} else {
return createStaticDecl(function (env, scope) {
return scope.def(env.ELEMENTS, '.vertCount')
})
}
} else {
var result = createStaticDecl(function () {
return -1
})
check.optional(function () {
result.MISSING = true
})
return result
}
} else {
var variable = new Declaration(
elements.thisDep || OFFSET.thisDep,
elements.contextDep || OFFSET.contextDep,
elements.propDep || OFFSET.propDep,
function (env, scope) {
var elements = env.ELEMENTS
if (env.OFFSET) {
return scope.def(elements, '?', elements, '.vertCount-',
env.OFFSET, ':-1')
}
return scope.def(elements, '?', elements, '.vertCount:-1')
})
check.optional(function () {
variable.DYNAMIC = true
})
return variable
}
}
return null
}
return {
elements: elements,
primitive: parsePrimitive(),
count: parseVertCount(),
instances: parseParam(S_INSTANCES, false),
offset: OFFSET
}
}
function parseGLState (options, env) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
var STATE = {}
GL_STATE_NAMES.forEach(function (prop) {
var param = propName(prop)
function parseParam (parseStatic, parseDynamic) {
if (prop in staticOptions) {
var value = parseStatic(staticOptions[prop])
STATE[param] = createStaticDecl(function () {
return value
})
} else if (prop in dynamicOptions) {
var dyn = dynamicOptions[prop]
STATE[param] = createDynamicDecl(dyn, function (env, scope) {
return parseDynamic(env, scope, env.invoke(scope, dyn))
})
}
}
switch (prop) {
case S_CULL_ENABLE:
case S_BLEND_ENABLE:
case S_DITHER:
case S_STENCIL_ENABLE:
case S_DEPTH_ENABLE:
case S_SCISSOR_ENABLE:
case S_POLYGON_OFFSET_ENABLE:
case S_SAMPLE_ALPHA:
case S_SAMPLE_ENABLE:
case S_DEPTH_MASK:
return parseParam(
function (value) {
check.commandType(value, 'boolean', prop, env.commandStr)
return value
},
function (env, scope, value) {
check.optional(function () {
env.assert(scope,
'typeof ' + value + '==="boolean"',
'invalid flag ' + prop, env.commandStr)
})
return value
})
case S_DEPTH_FUNC:
return parseParam(
function (value) {
check.commandParameter(value, compareFuncs, 'invalid ' + prop, env.commandStr)
return compareFuncs[value]
},
function (env, scope, value) {
var COMPARE_FUNCS = env.constants.compareFuncs
check.optional(function () {
env.assert(scope,
value + ' in ' + COMPARE_FUNCS,
'invalid ' + prop + ', must be one of ' + Object.keys(compareFuncs))
})
return scope.def(COMPARE_FUNCS, '[', value, ']')
})
case S_DEPTH_RANGE:
return parseParam(
function (value) {
check.command(
isArrayLike(value) &&
value.length === 2 &&
typeof value[0] === 'number' &&
typeof value[1] === 'number' &&
value[0] <= value[1],
'depth range is 2d array',
env.commandStr)
return value
},
function (env, scope, value) {
check.optional(function () {
env.assert(scope,
env.shared.isArrayLike + '(' + value + ')&&' +
value + '.length===2&&' +
'typeof ' + value + '[0]==="number"&&' +
'typeof ' + value + '[1]==="number"&&' +
value + '[0]<=' + value + '[1]',
'depth range must be a 2d array')
})
var Z_NEAR = scope.def('+', value, '[0]')
var Z_FAR = scope.def('+', value, '[1]')
return [Z_NEAR, Z_FAR]
})
case S_BLEND_FUNC:
return parseParam(
function (value) {
check.commandType(value, 'object', 'blend.func', env.commandStr)
var srcRGB = ('srcRGB' in value ? value.srcRGB : value.src)
var srcAlpha = ('srcAlpha' in value ? value.srcAlpha : value.src)
var dstRGB = ('dstRGB' in value ? value.dstRGB : value.dst)
var dstAlpha = ('dstAlpha' in value ? value.dstAlpha : value.dst)
check.commandParameter(srcRGB, blendFuncs, param + '.srcRGB', env.commandStr)
check.commandParameter(srcAlpha, blendFuncs, param + '.srcAlpha', env.commandStr)
check.commandParameter(dstRGB, blendFuncs, param + '.dstRGB', env.commandStr)
check.commandParameter(dstAlpha, blendFuncs, param + '.dstAlpha', env.commandStr)
check.command(
(invalidBlendCombinations.indexOf(srcRGB + ', ' + dstRGB) === -1),
'unallowed blending combination (srcRGB, dstRGB) = (' + srcRGB + ', ' + dstRGB + ')', env.commandStr)
return [
blendFuncs[srcRGB],
blendFuncs[dstRGB],
blendFuncs[srcAlpha],
blendFuncs[dstAlpha]
]
},
function (env, scope, value) {
var BLEND_FUNCS = env.constants.blendFuncs
check.optional(function () {
env.assert(scope,
value + '&&typeof ' + value + '==="object"',
'invalid blend func, must be an object')
})
function read (prefix, suffix) {
var func = scope.def(
'"', prefix, suffix, '" in ', value,
'?', value, '.', prefix, suffix,
':', value, '.', prefix)
check.optional(function () {
env.assert(scope,
func + ' in ' + BLEND_FUNCS,
'invalid ' + prop + '.' + prefix + suffix + ', must be one of ' + Object.keys(blendFuncs))
})
return func
}
var srcRGB = read('src', 'RGB')
var dstRGB = read('dst', 'RGB')
check.optional(function () {
var INVALID_BLEND_COMBINATIONS = env.constants.invalidBlendCombinations
env.assert(scope,
INVALID_BLEND_COMBINATIONS +
'.indexOf(' + srcRGB + '+", "+' + dstRGB + ') === -1 ',
'unallowed blending combination for (srcRGB, dstRGB)'
)
})
var SRC_RGB = scope.def(BLEND_FUNCS, '[', srcRGB, ']')
var SRC_ALPHA = scope.def(BLEND_FUNCS, '[', read('src', 'Alpha'), ']')
var DST_RGB = scope.def(BLEND_FUNCS, '[', dstRGB, ']')
var DST_ALPHA = scope.def(BLEND_FUNCS, '[', read('dst', 'Alpha'), ']')
return [SRC_RGB, DST_RGB, SRC_ALPHA, DST_ALPHA]
})
case S_BLEND_EQUATION:
return parseParam(
function (value) {
if (typeof value === 'string') {
check.commandParameter(value, blendEquations, 'invalid ' + prop, env.commandStr)
return [
blendEquations[value],
blendEquations[value]
]
} else if (typeof value === 'object') {
check.commandParameter(
value.rgb, blendEquations, prop + '.rgb', env.commandStr)
check.commandParameter(
value.alpha, blendEquations, prop + '.alpha', env.commandStr)
return [
blendEquations[value.rgb],
blendEquations[value.alpha]
]
} else {
check.commandRaise('invalid blend.equation', env.commandStr)
}
},
function (env, scope, value) {
var BLEND_EQUATIONS = env.constants.blendEquations
var RGB = scope.def()
var ALPHA = scope.def()
var ifte = env.cond('typeof ', value, '==="string"')
check.optional(function () {
function checkProp (block, name, value) {
env.assert(block,
value + ' in ' + BLEND_EQUATIONS,
'invalid ' + name + ', must be one of ' + Object.keys(blendEquations))
}
checkProp(ifte.then, prop, value)
env.assert(ifte.else,
value + '&&typeof ' + value + '==="object"',
'invalid ' + prop)
checkProp(ifte.else, prop + '.rgb', value + '.rgb')
checkProp(ifte.else, prop + '.alpha', value + '.alpha')
})
ifte.then(
RGB, '=', ALPHA, '=', BLEND_EQUATIONS, '[', value, '];')
ifte.else(
RGB, '=', BLEND_EQUATIONS, '[', value, '.rgb];',
ALPHA, '=', BLEND_EQUATIONS, '[', value, '.alpha];')
scope(ifte)
return [RGB, ALPHA]
})
case S_BLEND_COLOR:
return parseParam(
function (value) {
check.command(
isArrayLike(value) &&
value.length === 4,
'blend.color must be a 4d array', env.commandStr)
return loop(4, function (i) {
return +value[i]
})
},
function (env, scope, value) {
check.optional(function () {
env.assert(scope,
env.shared.isArrayLike + '(' + value + ')&&' +
value + '.length===4',
'blend.color must be a 4d array')
})
return loop(4, function (i) {
return scope.def('+', value, '[', i, ']')
})
})
case S_STENCIL_MASK:
return parseParam(
function (value) {
check.commandType(value, 'number', param, env.commandStr)
return value | 0
},
function (env, scope, value) {
check.optional(function () {
env.assert(scope,
'typeof ' + value + '==="number"',
'invalid stencil.mask')
})
return scope.def(value, '|0')
})
case S_STENCIL_FUNC:
return parseParam(
function (value) {
check.commandType(value, 'object', param, env.commandStr)
var cmp = value.cmp || 'keep'
var ref = value.ref || 0
var mask = 'mask' in value ? value.mask : -1
check.commandParameter(cmp, compareFuncs, prop + '.cmp', env.commandStr)
check.commandType(ref, 'number', prop + '.ref', env.commandStr)
check.commandType(mask, 'number', prop + '.mask', env.commandStr)
return [
compareFuncs[cmp],
ref,
mask
]
},
function (env, scope, value) {
var COMPARE_FUNCS = env.constants.compareFuncs
check.optional(function () {
function assert () {
env.assert(scope,
Array.prototype.join.call(arguments, ''),
'invalid stencil.func')
}
assert(value + '&&typeof ', value, '==="object"')
assert('!("cmp" in ', value, ')||(',
value, '.cmp in ', COMPARE_FUNCS, ')')
})
var cmp = scope.def(
'"cmp" in ', value,
'?', COMPARE_FUNCS, '[', value, '.cmp]',
':', GL_KEEP)
var ref = scope.def(value, '.ref|0')
var mask = scope.def(
'"mask" in ', value,
'?', value, '.mask|0:-1')
return [cmp, ref, mask]
})
case S_STENCIL_OPFRONT:
case S_STENCIL_OPBACK:
return parseParam(
function (value) {
check.commandType(value, 'object', param, env.commandStr)
var fail = value.fail || 'keep'
var zfail = value.zfail || 'keep'
var zpass = value.zpass || 'keep'
check.commandParameter(fail, stencilOps, prop + '.fail', env.commandStr)
check.commandParameter(zfail, stencilOps, prop + '.zfail', env.commandStr)
check.commandParameter(zpass, stencilOps, prop + '.zpass', env.commandStr)
return [
prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT,
stencilOps[fail],
stencilOps[zfail],
stencilOps[zpass]
]
},
function (env, scope, value) {
var STENCIL_OPS = env.constants.stencilOps
check.optional(function () {
env.assert(scope,
value + '&&typeof ' + value + '==="object"',
'invalid ' + prop)
})
function read (name) {
check.optional(function () {
env.assert(scope,
'!("' + name + '" in ' + value + ')||' +
'(' + value + '.' + name + ' in ' + STENCIL_OPS + ')',
'invalid ' + prop + '.' + name + ', must be one of ' + Object.keys(stencilOps))
})
return scope.def(
'"', name, '" in ', value,
'?', STENCIL_OPS, '[', value, '.', name, ']:',
GL_KEEP)
}
return [
prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT,
read('fail'),
read('zfail'),
read('zpass')
]
})
case S_POLYGON_OFFSET_OFFSET:
return parseParam(
function (value) {
check.commandType(value, 'object', param, env.commandStr)
var factor = value.factor | 0
var units = value.units | 0
check.commandType(factor, 'number', param + '.factor', env.commandStr)
check.commandType(units, 'number', param + '.units', env.commandStr)
return [factor, units]
},
function (env, scope, value) {
check.optional(function () {
env.assert(scope,
value + '&&typeof ' + value + '==="object"',
'invalid ' + prop)
})
var FACTOR = scope.def(value, '.factor|0')
var UNITS = scope.def(value, '.units|0')
return [FACTOR, UNITS]
})
case S_CULL_FACE:
return parseParam(
function (value) {
var face = 0
if (value === 'front') {
face = GL_FRONT
} else if (value === 'back') {
face = GL_BACK
}
check.command(!!face, param, env.commandStr)
return face
},
function (env, scope, value) {
check.optional(function () {
env.assert(scope,
value + '==="front"||' +
value + '==="back"',
'invalid cull.face')
})
return scope.def(value, '==="front"?', GL_FRONT, ':', GL_BACK)
})
case S_LINE_WIDTH:
return parseParam(
function (value) {
check.command(
typeof value === 'number' &&
value >= limits.lineWidthDims[0] &&
value <= limits.lineWidthDims[1],
'invalid line width, must positive number between ' +
limits.lineWidthDims[0] + ' and ' + limits.lineWidthDims[1], env.commandStr)
return value
},
function (env, scope, value) {
check.optional(function () {
env.assert(scope,
'typeof ' + value + '==="number"&&' +
value + '>=' + limits.lineWidthDims[0] + '&&' +
value + '<=' + limits.lineWidthDims[1],
'invalid line width')
})
return value
})
case S_FRONT_FACE:
return parseParam(
function (value) {
check.commandParameter(value, orientationType, param, env.commandStr)
return orientationType[value]
},
function (env, scope, value) {
check.optional(function () {
env.assert(scope,
value + '==="cw"||' +
value + '==="ccw"',
'invalid frontFace, must be one of cw,ccw')
})
return scope.def(value + '==="cw"?' + GL_CW + ':' + GL_CCW)
})
case S_COLOR_MASK:
return parseParam(
function (value) {
check.command(
isArrayLike(value) && value.length === 4,
'color.mask must be length 4 array', env.commandStr)
return value.map(function (v) { return !!v })
},
function (env, scope, value) {
check.optional(function () {
env.assert(scope,
env.shared.isArrayLike + '(' + value + ')&&' +
value + '.length===4',
'invalid color.mask')
})
return loop(4, function (i) {
return '!!' + value + '[' + i + ']'
})
})
case S_SAMPLE_COVERAGE:
return parseParam(
function (value) {
check.command(typeof value === 'object' && value, param, env.commandStr)
var sampleValue = 'value' in value ? value.value : 1
var sampleInvert = !!value.invert
check.command(
typeof sampleValue === 'number' &&
sampleValue >= 0 && sampleValue <= 1,
'sample.coverage.value must be a number between 0 and 1', env.commandStr)
return [sampleValue, sampleInvert]
},
function (env, scope, value) {
check.optional(function () {
env.assert(scope,
value + '&&typeof ' + value + '==="object"',
'invalid sample.coverage')
})
var VALUE = scope.def(
'"value" in ', value, '?+', value, '.value:1')
var INVERT = scope.def('!!', value, '.invert')
return [VALUE, INVERT]
})
}
})
return STATE
}
function parseUniforms (uniforms, env) {
var staticUniforms = uniforms.static
var dynamicUniforms = uniforms.dynamic
var UNIFORMS = {}
Object.keys(staticUniforms).forEach(function (name) {
var value = staticUniforms[name]
var result
if (typeof value === 'number' ||
typeof value === 'boolean') {
result = createStaticDecl(function () {
return value
})
} else if (typeof value === 'function') {
var reglType = value._reglType
if (reglType === 'texture2d' ||
reglType === 'textureCube') {
result = createStaticDecl(function (env) {
return env.link(value)
})
} else if (reglType === 'framebuffer' ||
reglType === 'framebufferCube') {
check.command(value.color.length > 0,
'missing color attachment for framebuffer sent to uniform "' + name + '"', env.commandStr)
result = createStaticDecl(function (env) {
return env.link(value.color[0])
})
} else {
check.commandRaise('invalid data for uniform "' + name + '"', env.commandStr)
}
} else if (isArrayLike(value)) {
result = createStaticDecl(function (env) {
var ITEM = env.global.def('[',
loop(value.length, function (i) {
check.command(
typeof value[i] === 'number' ||
typeof value[i] === 'boolean',
'invalid uniform ' + name, env.commandStr)
return value[i]
}), ']')
return ITEM
})
} else {
check.commandRaise('invalid or missing data for uniform "' + name + '"', env.commandStr)
}
result.value = value
UNIFORMS[name] = result
})
Object.keys(dynamicUniforms).forEach(function (key) {
var dyn = dynamicUniforms[key]
UNIFORMS[key] = createDynamicDecl(dyn, function (env, scope) {
return env.invoke(scope, dyn)
})
})
return UNIFORMS
}
function parseAttributes (attributes, env) {
var staticAttributes = attributes.static
var dynamicAttributes = attributes.dynamic
var attributeDefs = {}
Object.keys(staticAttributes).forEach(function (attribute) {
var value = staticAttributes[attribute]
var id = stringStore.id(attribute)
var record = new AttributeRecord()
if (isBufferArgs(value)) {
record.state = ATTRIB_STATE_POINTER
record.buffer = bufferState.getBuffer(
bufferState.create(value, GL_ARRAY_BUFFER, false, true))
record.type = 0
} else {
var buffer = bufferState.getBuffer(value)
if (buffer) {
record.state = ATTRIB_STATE_POINTER
record.buffer = buffer
record.type = 0
} else {
check.command(typeof value === 'object' && value,
'invalid data for attribute ' + attribute, env.commandStr)
if (value.constant) {
var constant = value.constant
record.buffer = 'null'
record.state = ATTRIB_STATE_CONSTANT
if (typeof constant === 'number') {
record.x = constant
} else {
check.command(
isArrayLike(constant) &&
constant.length > 0 &&
constant.length <= 4,
'invalid constant for attribute ' + attribute, env.commandStr)
CUTE_COMPONENTS.forEach(function (c, i) {
if (i < constant.length) {
record[c] = constant[i]
}
})
}
} else {
if (isBufferArgs(value.buffer)) {
buffer = bufferState.getBuffer(
bufferState.create(value.buffer, GL_ARRAY_BUFFER, false, true))
} else {
buffer = bufferState.getBuffer(value.buffer)
}
check.command(!!buffer, 'missing buffer for attribute "' + attribute + '"', env.commandStr)
var offset = value.offset | 0
check.command(offset >= 0,
'invalid offset for attribute "' + attribute + '"', env.commandStr)
var stride = value.stride | 0
check.command(stride >= 0 && stride < 256,
'invalid stride for attribute "' + attribute + '", must be integer betweeen [0, 255]', env.commandStr)
var size = value.size | 0
check.command(!('size' in value) || (size > 0 && size <= 4),
'invalid size for attribute "' + attribute + '", must be 1,2,3,4', env.commandStr)
var normalized = !!value.normalized
var type = 0
if ('type' in value) {
check.commandParameter(
value.type, glTypes,
'invalid type for attribute ' + attribute, env.commandStr)
type = glTypes[value.type]
}
var divisor = value.divisor | 0
if ('divisor' in value) {
check.command(divisor === 0 || extInstancing,
'cannot specify divisor for attribute "' + attribute + '", instancing not supported', env.commandStr)
check.command(divisor >= 0,
'invalid divisor for attribute "' + attribute + '"', env.commandStr)
}
check.optional(function () {
var command = env.commandStr
var VALID_KEYS = [
'buffer',
'offset',
'divisor',
'normalized',
'type',
'size',
'stride'
]
Object.keys(value).forEach(function (prop) {
check.command(
VALID_KEYS.indexOf(prop) >= 0,
'unknown parameter "' + prop + '" for attribute pointer "' + attribute + '" (valid parameters are ' + VALID_KEYS + ')',
command)
})
})
record.buffer = buffer
record.state = ATTRIB_STATE_POINTER
record.size = size
record.normalized = normalized
record.type = type || buffer.dtype
record.offset = offset
record.stride = stride
record.divisor = divisor
}
}
}
attributeDefs[attribute] = createStaticDecl(function (env, scope) {
var cache = env.attribCache
if (id in cache) {
return cache[id]
}
var result = {
isStream: false
}
Object.keys(record).forEach(function (key) {
result[key] = record[key]
})
if (record.buffer) {
result.buffer = env.link(record.buffer)
result.type = result.type || (result.buffer + '.dtype')
}
cache[id] = result
return result
})
})
Object.keys(dynamicAttributes).forEach(function (attribute) {
var dyn = dynamicAttributes[attribute]
function appendAttributeCode (env, block) {
var VALUE = env.invoke(block, dyn)
var shared = env.shared
var IS_BUFFER_ARGS = shared.isBufferArgs
var BUFFER_STATE = shared.buffer
// Perform validation on attribute
check.optional(function () {
env.assert(block,
VALUE + '&&(typeof ' + VALUE + '==="object"||typeof ' +
VALUE + '==="function")&&(' +
IS_BUFFER_ARGS + '(' + VALUE + ')||' +
BUFFER_STATE + '.getBuffer(' + VALUE + ')||' +
BUFFER_STATE + '.getBuffer(' + VALUE + '.buffer)||' +
IS_BUFFER_ARGS + '(' + VALUE + '.buffer)||' +
'("constant" in ' + VALUE +
'&&(typeof ' + VALUE + '.constant==="number"||' +
shared.isArrayLike + '(' + VALUE + '.constant))))',
'invalid dynamic attribute "' + attribute + '"')
})
// allocate names for result
var result = {
isStream: block.def(false)
}
var defaultRecord = new AttributeRecord()
defaultRecord.state = ATTRIB_STATE_POINTER
Object.keys(defaultRecord).forEach(function (key) {
result[key] = block.def('' + defaultRecord[key])
})
var BUFFER = result.buffer
var TYPE = result.type
block(
'if(', IS_BUFFER_ARGS, '(', VALUE, ')){',
result.isStream, '=true;',
BUFFER, '=', BUFFER_STATE, '.createStream(', GL_ARRAY_BUFFER, ',', VALUE, ');',
TYPE, '=', BUFFER, '.dtype;',
'}else{',
BUFFER, '=', BUFFER_STATE, '.getBuffer(', VALUE, ');',
'if(', BUFFER, '){',
TYPE, '=', BUFFER, '.dtype;',
'}else if("constant" in ', VALUE, '){',
result.state, '=', ATTRIB_STATE_CONSTANT, ';',
'if(typeof ' + VALUE + '.constant === "number"){',
result[CUTE_COMPONENTS[0]], '=', VALUE, '.constant;',
CUTE_COMPONENTS.slice(1).map(function (n) {
return result[n]
}).join('='), '=0;',
'}else{',
CUTE_COMPONENTS.map(function (name, i) {
return (
result[name] + '=' + VALUE + '.constant.length>=' + i +
'?' + VALUE + '.constant[' + i + ']:0;'
)
}).join(''),
'}}else{',
'if(', IS_BUFFER_ARGS, '(', VALUE, '.buffer)){',
BUFFER, '=', BUFFER_STATE, '.createStream(', GL_ARRAY_BUFFER, ',', VALUE, '.buffer);',
'}else{',
BUFFER, '=', BUFFER_STATE, '.getBuffer(', VALUE, '.buffer);',
'}',
TYPE, '="type" in ', VALUE, '?',
shared.glTypes, '[', VALUE, '.type]:', BUFFER, '.dtype;',
result.normalized, '=!!', VALUE, '.normalized;')
function emitReadRecord (name) {
block(result[name], '=', VALUE, '.', name, '|0;')
}
emitReadRecord('size')
emitReadRecord('offset')
emitReadRecord('stride')
emitReadRecord('divisor')
block('}}')
block.exit(
'if(', result.isStream, '){',
BUFFER_STATE, '.destroyStream(', BUFFER, ');',
'}')
return result
}
attributeDefs[attribute] = createDynamicDecl(dyn, appendAttributeCode)
})
return attributeDefs
}
function parseContext (context) {
var staticContext = context.static
var dynamicContext = context.dynamic
var result = {}
Object.keys(staticContext).forEach(function (name) {
var value = staticContext[name]
result[name] = createStaticDecl(function (env, scope) {
if (typeof value === 'number' || typeof value === 'boolean') {
return '' + value
} else {
return env.link(value)
}
})
})
Object.keys(dynamicContext).forEach(function (name) {
var dyn = dynamicContext[name]
result[name] = createDynamicDecl(dyn, function (env, scope) {
return env.invoke(scope, dyn)
})
})
return result
}
function parseArguments (options, attributes, uniforms, context, env) {
var staticOptions = options.static
var dynamicOptions = options.dynamic
check.optional(function () {
var KEY_NAMES = [
S_FRAMEBUFFER,
S_VERT,
S_FRAG,
S_ELEMENTS,
S_PRIMITIVE,
S_OFFSET,
S_COUNT,
S_INSTANCES,
S_PROFILE
].concat(GL_STATE_NAMES)
function checkKeys (dict) {
Object.keys(dict).forEach(function (key) {
check.command(
KEY_NAMES.indexOf(key) >= 0,
'unknown parameter "' + key + '"',
env.commandStr)
})
}
checkKeys(staticOptions)
checkKeys(dynamicOptions)
})
var framebuffer = parseFramebuffer(options, env)
var viewportAndScissor = parseViewportScissor(options, framebuffer, env)
var draw = parseDraw(options, env)
var state = parseGLState(options, env)
var shader = parseProgram(options, env)
function copyBox (name) {
var defn = viewportAndScissor[name]
if (defn) {
state[name] = defn
}
}
copyBox(S_VIEWPORT)
copyBox(propName(S_SCISSOR_BOX))
var dirty = Object.keys(state).length > 0
var result = {
framebuffer: framebuffer,
draw: draw,
shader: shader,
state: state,
dirty: dirty
}
result.profile = parseProfile(options, env)
result.uniforms = parseUniforms(uniforms, env)
result.attributes = parseAttributes(attributes, env)
result.context = parseContext(context, env)
return result
}
// ===================================================
// ===================================================
// COMMON UPDATE FUNCTIONS
// ===================================================
// ===================================================
function emitContext (env, scope, context) {
var shared = env.shared
var CONTEXT = shared.context
var contextEnter = env.scope()
Object.keys(context).forEach(function (name) {
scope.save(CONTEXT, '.' + name)
var defn = context[name]
contextEnter(CONTEXT, '.', name, '=', defn.append(env, scope), ';')
})
scope(contextEnter)
}
// ===================================================
// ===================================================
// COMMON DRAWING FUNCTIONS
// ===================================================
// ===================================================
function emitPollFramebuffer (env, scope, framebuffer, skipCheck) {
var shared = env.shared
var GL = shared.gl
var FRAMEBUFFER_STATE = shared.framebuffer
var EXT_DRAW_BUFFERS
if (extDrawBuffers) {
EXT_DRAW_BUFFERS = scope.def(shared.extensions, '.webgl_draw_buffers')
}
var constants = env.constants
var DRAW_BUFFERS = constants.drawBuffer
var BACK_BUFFER = constants.backBuffer
var NEXT
if (framebuffer) {
NEXT = framebuffer.append(env, scope)
} else {
NEXT = scope.def(FRAMEBUFFER_STATE, '.next')
}
if (!skipCheck) {
scope('if(', NEXT, '!==', FRAMEBUFFER_STATE, '.cur){')
}
scope(
'if(', NEXT, '){',
GL, '.bindFramebuffer(', GL_FRAMEBUFFER, ',', NEXT, '.framebuffer);')
if (extDrawBuffers) {
scope(EXT_DRAW_BUFFERS, '.drawBuffersWEBGL(',
DRAW_BUFFERS, '[', NEXT, '.colorAttachments.length]);')
}
scope('}else{',
GL, '.bindFramebuffer(', GL_FRAMEBUFFER, ',null);')
if (extDrawBuffers) {
scope(EXT_DRAW_BUFFERS, '.drawBuffersWEBGL(', BACK_BUFFER, ');')
}
scope(
'}',
FRAMEBUFFER_STATE, '.cur=', NEXT, ';')
if (!skipCheck) {
scope('}')
}
}
function emitPollState (env, scope, args) {
var shared = env.shared
var GL = shared.gl
var CURRENT_VARS = env.current
var NEXT_VARS = env.next
var CURRENT_STATE = shared.current
var NEXT_STATE = shared.next
var block = env.cond(CURRENT_STATE, '.dirty')
GL_STATE_NAMES.forEach(function (prop) {
var param = propName(prop)
if (param in args.state) {
return
}
var NEXT, CURRENT
if (param in NEXT_VARS) {
NEXT = NEXT_VARS[param]
CURRENT = CURRENT_VARS[param]
var parts = loop(currentState[param].length, function (i) {
return block.def(NEXT, '[', i, ']')
})
block(env.cond(parts.map(function (p, i) {
return p + '!==' + CURRENT + '[' + i + ']'
}).join('||'))
.then(
GL, '.', GL_VARIABLES[param], '(', parts, ');',
parts.map(function (p, i) {
return CURRENT + '[' + i + ']=' + p
}).join(';'), ';'))
} else {
NEXT = block.def(NEXT_STATE, '.', param)
var ifte = env.cond(NEXT, '!==', CURRENT_STATE, '.', param)
block(ifte)
if (param in GL_FLAGS) {
ifte(
env.cond(NEXT)
.then(GL, '.enable(', GL_FLAGS[param], ');')
.else(GL, '.disable(', GL_FLAGS[param], ');'),
CURRENT_STATE, '.', param, '=', NEXT, ';')
} else {
ifte(
GL, '.', GL_VARIABLES[param], '(', NEXT, ');',
CURRENT_STATE, '.', param, '=', NEXT, ';')
}
}
})
if (Object.keys(args.state).length === 0) {
block(CURRENT_STATE, '.dirty=false;')
}
scope(block)
}
function emitSetOptions (env, scope, options, filter) {
var shared = env.shared
var CURRENT_VARS = env.current
var CURRENT_STATE = shared.current
var GL = shared.gl
sortState(Object.keys(options)).forEach(function (param) {
var defn = options[param]
if (filter && !filter(defn)) {
return
}
var variable = defn.append(env, scope)
if (GL_FLAGS[param]) {
var flag = GL_FLAGS[param]
if (isStatic(defn)) {
if (variable) {
scope(GL, '.enable(', flag, ');')
} else {
scope(GL, '.disable(', flag, ');')
}
} else {
scope(env.cond(variable)
.then(GL, '.enable(', flag, ');')
.else(GL, '.disable(', flag, ');'))
}
scope(CURRENT_STATE, '.', param, '=', variable, ';')
} else if (isArrayLike(variable)) {
var CURRENT = CURRENT_VARS[param]
scope(
GL, '.', GL_VARIABLES[param], '(', variable, ');',
variable.map(function (v, i) {
return CURRENT + '[' + i + ']=' + v
}).join(';'), ';')
} else {
scope(
GL, '.', GL_VARIABLES[param], '(', variable, ');',
CURRENT_STATE, '.', param, '=', variable, ';')
}
})
}
function injectExtensions (env, scope) {
if (extInstancing) {
env.instancing = scope.def(
env.shared.extensions, '.angle_instanced_arrays')
}
}
function emitProfile (env, scope, args, useScope, incrementCounter) {
var shared = env.shared
var STATS = env.stats
var CURRENT_STATE = shared.current
var TIMER = shared.timer
var profileArg = args.profile
function perfCounter () {
if (typeof performance === 'undefined') {
return 'Date.now()'
} else {
return 'performance.now()'
}
}
var CPU_START, QUERY_COUNTER
function emitProfileStart (block) {
CPU_START = scope.def()
block(CPU_START, '=', perfCounter(), ';')
if (typeof incrementCounter === 'string') {
block(STATS, '.count+=', incrementCounter, ';')
} else {
block(STATS, '.count++;')
}
if (timer) {
if (useScope) {
QUERY_COUNTER = scope.def()
block(QUERY_COUNTER, '=', TIMER, '.getNumPendingQueries();')
} else {
block(TIMER, '.beginQuery(', STATS, ');')
}
}
}
function emitProfileEnd (block) {
block(STATS, '.cpuTime+=', perfCounter(), '-', CPU_START, ';')
if (timer) {
if (useScope) {
block(TIMER, '.pushScopeStats(',
QUERY_COUNTER, ',',
TIMER, '.getNumPendingQueries(),',
STATS, ');')
} else {
block(TIMER, '.endQuery();')
}
}
}
function scopeProfile (value) {
var prev = scope.def(