From 4b44244fc29abe062603b584a63eaabb85df3304 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Thu, 29 Mar 2018 18:01:11 +0800 Subject: [PATCH 01/35] support canvas label --- cocos2d/core/components/CCLabel.js | 45 ++++-- cocos2d/core/components/CCSprite.js | 18 ++- .../{graphics-assembler.js => index.js} | 0 cocos2d/core/renderer/assemblers/index.js | 6 +- .../core/renderer/assemblers/label/bmfont.js | 135 ++++++++++++++++++ .../label/{label-assembler.js => index.js} | 51 +++---- cocos2d/core/renderer/assemblers/label/ttf.js | 110 ++++++++++++++ .../renderer/assemblers/mask-assembler.js | 2 +- .../sprite/{sprite-assembler.js => index.js} | 4 - .../core/renderer/canvas/renderers/index.js | 3 +- .../renderer/canvas/renderers/label/bmfont.js | 88 ++++++++++++ .../renderer/canvas/renderers/label/index.js | 54 +++++++ .../renderer/canvas/renderers/label/ttf.js | 61 ++++++++ .../core/renderer/canvas/renderers/utils.js | 6 +- .../label/bmfont.js} | 102 ------------- .../ttf-assembler.js => utils/label/ttf.js} | 91 ++---------- 16 files changed, 533 insertions(+), 243 deletions(-) rename cocos2d/core/renderer/assemblers/graphics/{graphics-assembler.js => index.js} (100%) create mode 100644 cocos2d/core/renderer/assemblers/label/bmfont.js rename cocos2d/core/renderer/assemblers/label/{label-assembler.js => index.js} (65%) create mode 100644 cocos2d/core/renderer/assemblers/label/ttf.js rename cocos2d/core/renderer/assemblers/sprite/{sprite-assembler.js => index.js} (97%) create mode 100644 cocos2d/core/renderer/canvas/renderers/label/bmfont.js create mode 100644 cocos2d/core/renderer/canvas/renderers/label/index.js create mode 100644 cocos2d/core/renderer/canvas/renderers/label/ttf.js rename cocos2d/core/renderer/{assemblers/label/bmfont-assembler.js => utils/label/bmfont.js} (88%) rename cocos2d/core/renderer/{assemblers/label/ttf-assembler.js => utils/label/ttf.js} (87%) diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index a262d53d6e..967ed35ee2 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -164,6 +164,7 @@ var Label = cc.Class({ } this._actualFontSize = 0; + this._assemblerData = null; }, editor: CC_EDITOR && { @@ -357,6 +358,7 @@ var Label = cc.Class({ } this._fontAtlas = null; this._material = null; + this._updateAssembler(); this._activateMaterial(); this._updateRenderData(); }, @@ -442,12 +444,30 @@ var Label = cc.Class({ onEnable: function () { this._super(); + + this._updateAssembler(); this._activateMaterial(); }, + _updateAssembler () { + let assembler = Label._assembler.getAssembler(this); + + if (this._assembler !== assembler) { + this._assembler = assembler; + this._renderData = null; + } + + if (!this._renderData) { + this._renderData = this._assembler.createData(this); + this._renderData.worldMatDirty = true; + } + }, + _activateMaterial: function () { if (this._material) return; + this._assemblerData = null; + let material; let font = this.font; if (font instanceof cc.BitmapFont) { @@ -459,21 +479,28 @@ var Label = cc.Class({ material = new SpriteMaterial(); // TODO: old texture in material have been released by loader - material.texture = spriteFrame.getTexture(); + material.texture = this._texture = spriteFrame._texture; } else { - material = new SpriteMaterial(); - this._texture = new cc.Texture2D(); - this._canvas = document.createElement("canvas"); - // create canvas with size so that the default texture impl can be created and don't need activate material again - this._canvas.width = this._canvas.height = 1; - this._texture.initWithElement(this._canvas); - this._texture.handleLoadedTexture(); - this._context = this._canvas.getContext("2d"); + let assemblerData = this._assemblerData = {}; + assemblerData._canvas = document.createElement("canvas"); + // create canvas with size so that the default texture impl can be created and don't need activate material again + assemblerData._canvas.width = assemblerData._canvas.height = 1; + assemblerData._context = assemblerData._canvas.getContext("2d"); + + this._texture = new cc.Texture2D(); + this._texture.initWithElement(assemblerData._canvas); + this._texture.handleLoadedTexture(); + + material = new SpriteMaterial(); material.texture = this._texture; } + if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { + this._texture.url = this.uuid + '_texture'; + } + this.setMaterial(material); }, diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 2519254aed..1df91fd658 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -480,12 +480,6 @@ var Sprite = cc.Class({ this._super(); this._updateAssembler(); - - let renderData = this._renderData; - if (!renderData) { - renderData = this._renderData = Sprite._assembler.createData(this); - renderData.worldMatDirty = true; - } this._activateMaterial(); @@ -515,7 +509,17 @@ var Sprite = cc.Class({ }, _updateAssembler: function () { - this._assembler = Sprite._assembler.getAssembler(this); + let assembler = Sprite._assembler.getAssembler(this); + + if (this._assembler !== assembler) { + this._assembler = assembler; + this._renderData = null; + } + + if (!this._renderData) { + this._renderData = this._assembler.createData(this); + this._renderData.worldMatDirty = true; + } }, _activateMaterial: function () { diff --git a/cocos2d/core/renderer/assemblers/graphics/graphics-assembler.js b/cocos2d/core/renderer/assemblers/graphics/index.js similarity index 100% rename from cocos2d/core/renderer/assemblers/graphics/graphics-assembler.js rename to cocos2d/core/renderer/assemblers/graphics/index.js diff --git a/cocos2d/core/renderer/assemblers/index.js b/cocos2d/core/renderer/assemblers/index.js index 1feed16147..55f9daabd7 100644 --- a/cocos2d/core/renderer/assemblers/index.js +++ b/cocos2d/core/renderer/assemblers/index.js @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -require('./sprite/sprite-assembler'); +require('./sprite'); require('./mask-assembler'); -require('./graphics/graphics-assembler'); -require('./label/label-assembler'); +require('./graphics'); +require('./label'); diff --git a/cocos2d/core/renderer/assemblers/label/bmfont.js b/cocos2d/core/renderer/assemblers/label/bmfont.js new file mode 100644 index 0000000000..862023629e --- /dev/null +++ b/cocos2d/core/renderer/assemblers/label/bmfont.js @@ -0,0 +1,135 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +const macro = require('../../../platform/CCMacro'); +const renderEngine = require('../../render-engine'); + +const js = require('../../../platform/js'); +const bmfontUtls = require('../../utils/label/bmfont'); + +module.exports = js.addon({ + createData (comp) { + return comp.requestRenderData(); + }, + + fillVertexBuffer (comp, off, vbuf, uintbuf) { + let node = comp.node; + let renderData = comp._renderData; + let data = renderData._data; + let z = node._position.z; + let color = node.color._val; + + node._updateWorldMatrix(); + let matrix = node._worldMatrix; + let a = matrix.m00, + b = matrix.m01, + c = matrix.m04, + d = matrix.m05, + tx = matrix.m12, + ty = matrix.m13; + + let vert; + let length = renderData.dataLength; + for (let i = 0; i < length; i++) { + vert = data[i]; + vbuf[off + 0] = vert.x * a + vert.y * c + tx; + vbuf[off + 1] = vert.x * b + vert.y * d + ty; + vbuf[off + 2] = z; + vbuf[off + 4] = vert.u; + vbuf[off + 5] = vert.v; + uintbuf[off + 3] = color; + off += 6; + } + }, + + fillIndexBuffer (comp, offset, vertexId, ibuf) { + let renderData = comp._renderData; + let length = renderData.indiceCount; + for (let i = 0; i < length; i+=6) { + ibuf[offset++] = vertexId; + ibuf[offset++] = vertexId+1; + ibuf[offset++] = vertexId+2; + ibuf[offset++] = vertexId+1; + ibuf[offset++] = vertexId+3; + ibuf[offset++] = vertexId+2; + vertexId += 4; + } + }, + + appendQuad (renderData, texture, rect, rotated, x, y, scale) { + let dataOffset = renderData.dataLength; + + renderData.dataLength += 4; + renderData.vertexCount = renderData.dataLength; + renderData.indiceCount = renderData.dataLength / 2 * 3; + + let data = renderData._data; + let texw = texture.width, + texh = texture.height; + + let rectWidth = rect.width, + rectHeight = rect.height; + + let l, b, r, t; + if (!rotated) { + l = (rect.x) / texw; + r = (rect.x + rectWidth) / texw; + b = (rect.y + rectHeight) / texh; + t = (rect.y) / texh; + + data[dataOffset].u = l; + data[dataOffset].v = b; + data[dataOffset+1].u = r; + data[dataOffset+1].v = b; + data[dataOffset+2].u = l; + data[dataOffset+2].v = t; + data[dataOffset+3].u = r; + data[dataOffset+3].v = t; + } else { + l = (rect.x) / texw; + r = (rect.x + rectHeight) / texw; + b = (rect.y + rectWidth) / texh; + t = (rect.y) / texh; + + data[dataOffset].u = l; + data[dataOffset].v = t; + data[dataOffset+1].u = l; + data[dataOffset+1].v = b; + data[dataOffset+2].u = r; + data[dataOffset+2].v = t; + data[dataOffset+3].u = r; + data[dataOffset+3].v = b; + } + + data[dataOffset].x = x; + data[dataOffset].y = y - rectHeight * scale; + data[dataOffset+1].x = x + rectWidth * scale; + data[dataOffset+1].y = y - rectHeight * scale; + data[dataOffset+2].x = x; + data[dataOffset+2].y = y; + data[dataOffset+3].x = x + rectWidth * scale; + data[dataOffset+3].y = y; + }, +}, bmfontUtls); diff --git a/cocos2d/core/renderer/assemblers/label/label-assembler.js b/cocos2d/core/renderer/assemblers/label/index.js similarity index 65% rename from cocos2d/core/renderer/assemblers/label/label-assembler.js rename to cocos2d/core/renderer/assemblers/label/index.js index f7b7bb80f1..a4bcc390b0 100644 --- a/cocos2d/core/renderer/assemblers/label/label-assembler.js +++ b/cocos2d/core/renderer/assemblers/label/index.js @@ -26,31 +26,31 @@ const js = require('../../../platform/js'); const assembler = require('../assembler'); const Label = require('../../../components/CCLabel'); -const ttfAssembler = require('./ttf-assembler'); -const bmfontAssembler = require('./bmfont-assembler'); +const ttfAssembler = require('./ttf'); +const bmfontAssembler = require('./bmfont'); var labelAssembler = js.addon({ + + getAssembler (comp) { + let assembler = ttfAssembler; + + if (comp.font instanceof cc.BitmapFont) { + assembler = bmfontAssembler; + } + + return assembler; + }, + updateRenderData (comp) { this.datas.length = 0; if (comp.string !== undefined && comp.string !== null && comp.string !== "") { - let assembler; - if (comp.font instanceof cc.BitmapFont) { - assembler = bmfontAssembler; - } - else { - assembler = ttfAssembler; - } - let renderData = comp._renderData; - if (!renderData) { - renderData = comp._renderData = assembler.createData(comp); - } - let size = comp.node._contentSize; - let anchor = comp.node._anchorPoint; - renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); + // let size = comp.node._contentSize; + // let anchor = comp.node._anchorPoint; + // renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); - assembler.update(comp); + comp._assembler.update(comp); renderData.material = comp.getMaterial(); this.datas.push(renderData); @@ -62,21 +62,8 @@ var labelAssembler = js.addon({ let vertexOffset = batchData.byteOffset / 4, indiceOffset = batchData.indiceOffset; - // vertex buffer - if (comp.font instanceof cc.BitmapFont) { - bmfontAssembler.fillVertexBuffer(comp, vertexOffset, vbuf, uintbuf); - } - else { - ttfAssembler.fillVertexBuffer(comp, vertexOffset, vbuf, uintbuf); - } - - // index buffer - if (comp.font instanceof cc.BitmapFont) { - bmfontAssembler.fillIndexBuffer(comp, indiceOffset, vertexId, ibuf); - } - else { - ttfAssembler.fillIndexBuffer(comp, indiceOffset, vertexId, ibuf); - } + comp._assembler.fillVertexBuffer(comp, vertexOffset, vbuf, uintbuf); + comp._assembler.fillIndexBuffer(comp, indiceOffset, vertexId, ibuf); } }, assembler); diff --git a/cocos2d/core/renderer/assemblers/label/ttf.js b/cocos2d/core/renderer/assemblers/label/ttf.js new file mode 100644 index 0000000000..c458aebdc6 --- /dev/null +++ b/cocos2d/core/renderer/assemblers/label/ttf.js @@ -0,0 +1,110 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +const macro = require('../../../platform/CCMacro'); +const renderEngine = require('../../render-engine'); + +const js = require('../../../platform/js'); +const ttfUtls = require('../../utils/label/ttf'); + +module.exports = js.addon({ + createData (comp) { + let renderData = comp.requestRenderData(); + + renderData.dataLength = 4; + renderData.vertexCount = 4; + renderData.indiceCount = 6; + + let data = renderData._data; + data[0].u = 0; + data[0].v = 1; + data[1].u = 1; + data[1].v = 1; + data[2].u = 0; + data[2].v = 0; + data[3].u = 1; + data[3].v = 0; + return renderData; + }, + + fillVertexBuffer (comp, off, vbuf, uintbuf) { + let node = comp.node; + let renderData = comp._renderData; + let data = renderData._data; + let z = node._position.z; + let color = cc.Color.WHITE._val; + + node._updateWorldMatrix(); + let matrix = node._worldMatrix; + let a = matrix.m00, + b = matrix.m01, + c = matrix.m04, + d = matrix.m05, + tx = matrix.m12, + ty = matrix.m13; + + let vert; + let length = renderData.dataLength; + for (let i = 0; i < length; i++) { + vert = data[i]; + vbuf[off + 0] = vert.x * a + vert.y * c + tx; + vbuf[off + 1] = vert.x * b + vert.y * d + ty; + vbuf[off + 2] = z; + vbuf[off + 4] = vert.u; + vbuf[off + 5] = vert.v; + uintbuf[off + 3] = color; + off += 6; + } + }, + + fillIndexBuffer (comp, offset, vertexId, ibuf) { + ibuf[offset + 0] = vertexId; + ibuf[offset + 1] = vertexId + 1; + ibuf[offset + 2] = vertexId + 2; + ibuf[offset + 3] = vertexId + 1; + ibuf[offset + 4] = vertexId + 3; + ibuf[offset + 5] = vertexId + 2; + }, + + _updateVerts (comp) { + let renderData = comp._renderData; + + let node = comp.node, + width = node.width, + height = node.height, + appx = node.anchorX * width, + appy = node.anchorY * height; + + let data = renderData._data; + data[0].x = -appx; + data[0].y = -appy; + data[1].x = width - appx; + data[1].y = -appy; + data[2].x = -appx; + data[2].y = height - appy; + data[3].x = width - appx; + data[3].y = height - appy; + } +}, ttfUtls); diff --git a/cocos2d/core/renderer/assemblers/mask-assembler.js b/cocos2d/core/renderer/assemblers/mask-assembler.js index 1e162b3bc0..56365d61e1 100644 --- a/cocos2d/core/renderer/assemblers/mask-assembler.js +++ b/cocos2d/core/renderer/assemblers/mask-assembler.js @@ -32,7 +32,7 @@ const js = require('../../platform/js'); const assembler = require('./assembler'); const spriteAssembler = require('./sprite/simple'); const Graphics = require('../../graphics/graphics'); -const graphicsAssembler = require('./graphics/graphics-assembler'); +const graphicsAssembler = require('./graphics'); let _stencilMgr = StencilManager.sharedManager; let _color = cc.color(255, 255, 255, 0); diff --git a/cocos2d/core/renderer/assemblers/sprite/sprite-assembler.js b/cocos2d/core/renderer/assemblers/sprite/index.js similarity index 97% rename from cocos2d/core/renderer/assemblers/sprite/sprite-assembler.js rename to cocos2d/core/renderer/assemblers/sprite/index.js index b2918883a5..b745844428 100644 --- a/cocos2d/core/renderer/assemblers/sprite/sprite-assembler.js +++ b/cocos2d/core/renderer/assemblers/sprite/index.js @@ -63,10 +63,6 @@ let spriteAssembler = js.addon({ return util; }, - createData (sprite) { - return sprite._assembler.createData(sprite); - }, - updateRenderData (sprite) { let datas = sprite.__allocedDatas; if (!sprite.spriteFrame) { diff --git a/cocos2d/core/renderer/canvas/renderers/index.js b/cocos2d/core/renderer/canvas/renderers/index.js index 7a807b5abd..36b701183d 100644 --- a/cocos2d/core/renderer/canvas/renderers/index.js +++ b/cocos2d/core/renderer/canvas/renderers/index.js @@ -37,6 +37,7 @@ let RichText = require('../../../components/CCRichText'); // let Armature = require('../../../../../extensions/dragonbones/ArmatureDisplay'); let spriteRenderer = require('./sprite/'); +let labelRenderer = require('./label/'); let map = {}; let postMap = {}; @@ -52,7 +53,7 @@ function addRenderer (Component, handler, postHandler) { } addRenderer(Sprite, spriteRenderer); -addRenderer(Label, null); +addRenderer(Label, labelRenderer); addRenderer(Mask, null); addRenderer(RichText, null); diff --git a/cocos2d/core/renderer/canvas/renderers/label/bmfont.js b/cocos2d/core/renderer/canvas/renderers/label/bmfont.js new file mode 100644 index 0000000000..5dd09388e5 --- /dev/null +++ b/cocos2d/core/renderer/canvas/renderers/label/bmfont.js @@ -0,0 +1,88 @@ +const bmfontUtils = require('../../../utils/label/bmfont') +const js = require('../../../../platform/js'); +const utils = require('../utils'); + +module.exports = js.addon({ + createData (comp) { + return comp.requestRenderData(); + }, + + appendQuad (renderData, texture, rect, rotated, x, y, scale) { + let dataOffset = renderData.dataLength; + + renderData.dataLength += 2; + + let data = renderData._data; + let texw = texture.width, + texh = texture.height; + + let rectWidth = rect.width, + rectHeight = rect.height; + + let l, b, r, t; + if (!rotated) { + l = rect.x; + r = rect.x + rectWidth; + b = rect.y; + t = rect.y + rectHeight; + + data[dataOffset].u = l; + data[dataOffset].v = b; + data[dataOffset+1].u = r; + data[dataOffset+1].v = t; + } else { + l = rect.x; + r = rect.x + rectHeight; + b = rect.y; + t = rect.y + rectWidth; + + data[dataOffset].u = l; + data[dataOffset].v = t; + data[dataOffset+1].u = l; + data[dataOffset+1].v = b; + } + + data[dataOffset].x = x; + data[dataOffset].y = y - rectHeight * scale; + data[dataOffset+1].x = x + rectWidth * scale; + data[dataOffset+1].y = y; + }, + + draw (ctx, comp) { + let node = comp.node; + // Transform + let matrix = node._worldMatrix; + let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, + tx = matrix.m12, ty = matrix.m13; + ctx.transform(a, b, c, d, tx, -ty); + + // TODO: handle blend function + + // opacity + ctx.glphaAlpha = node.opacity / 255; + + let tex = comp._texture, + data = comp._renderData._data; + + let image = utils.getColorizedImage(tex, node.color); + + for (let i = 0, l = data.length; i < l; i+=2) { + let x = data[i].x; + let y = data[i].y; + let w = data[i+1].x - x; + let h = data[i+1].y - y; + y = - y - h; + + let sx = data[i].u; + let sy = data[i].v; + let sw = data[i+1].u - sx; + let sh = data[i+1].v - sy; + + ctx.drawImage(image, + sx, sy, sw, sh, + x, y, w, h); + } + + return 1; + } +}, bmfontUtils); diff --git a/cocos2d/core/renderer/canvas/renderers/label/index.js b/cocos2d/core/renderer/canvas/renderers/label/index.js new file mode 100644 index 0000000000..2e4fb2f3cb --- /dev/null +++ b/cocos2d/core/renderer/canvas/renderers/label/index.js @@ -0,0 +1,54 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +const ttf = require('./ttf'); +const bmfont = require('./bmfont'); + +module.exports = { + getAssembler (comp) { + let assembler = ttf; + + if (comp.font instanceof cc.BitmapFont) { + assembler = bmfont; + } + + return assembler; + }, + + createData (comp) { + return comp._assembler.createData(comp); + }, + + draw (ctx, comp) { + // Check whether need to render + if (!comp._texture) { + return 0; + } + + let assembler = comp._assembler; + assembler.update(comp); + return assembler.draw(ctx, comp); + } +}; \ No newline at end of file diff --git a/cocos2d/core/renderer/canvas/renderers/label/ttf.js b/cocos2d/core/renderer/canvas/renderers/label/ttf.js new file mode 100644 index 0000000000..6f2d89ac28 --- /dev/null +++ b/cocos2d/core/renderer/canvas/renderers/label/ttf.js @@ -0,0 +1,61 @@ +const ttfUtils = require('../../../utils/label/ttf') +const js = require('../../../../platform/js'); +const utils = require('../utils'); + +module.exports = js.addon({ + createData (sprite) { + let renderData = sprite.requestRenderData(); + // 0 for bottom left, 1 for top right + renderData.dataLength = 2; + return renderData; + }, + + _updateVerts (comp) { + let renderData = comp._renderData; + + let node = comp.node, + width = node.width, + height = node.height, + appx = node.anchorX * width, + appy = node.anchorY * height; + + let data = renderData._data; + data[0].x = -appx; + data[0].y = -appy; + data[1].x = width - appx; + data[1].y = height - appy; + }, + + _updateTexture (comp) { + ttfUtils._updateTexture(comp); + utils.dropImage(comp._texture, comp.node.color); + }, + + draw (ctx, comp) { + let node = comp.node; + // Transform + let matrix = node._worldMatrix; + let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, + tx = matrix.m12, ty = matrix.m13; + ctx.transform(a, b, c, d, tx, -ty); + + // TODO: handle blend function + + // opacity + ctx.glphaAlpha = node.opacity / 255; + + let tex = comp._texture, + data = comp._renderData._data; + + let image = utils.getColorizedImage(tex, node.color); + + let x = data[0].x; + let y = data[0].y; + let w = data[1].x - x; + let h = data[1].y - y; + y = - y - h; + + ctx.drawImage(image, x, y, w, h); + return 1; + } +}, ttfUtils); diff --git a/cocos2d/core/renderer/canvas/renderers/utils.js b/cocos2d/core/renderer/canvas/renderers/utils.js index 242b98a404..7d9d1e7dcf 100644 --- a/cocos2d/core/renderer/canvas/renderers/utils.js +++ b/cocos2d/core/renderer/canvas/renderers/utils.js @@ -81,7 +81,7 @@ let textureColorizer = { // Draw color ctx.globalCompositeOperation = 'source-over'; - ctx.fillStyle = 'rgba(' + color.r + ',' + color.g + ',' + color.b + ')'; + ctx.fillStyle = `rgb(${color.r}, ${color.g}, ${color.b}`; ctx.fillRect(x, y, w, h); // Multiply color with texture @@ -111,5 +111,9 @@ let textureColorizer = { module.exports = { getColorizedImage (texture, color) { return textureColorizer.getImage(texture, color); + }, + + dropImage (texture, color) { + textureColorizer.dropImage(texture, color); } }; \ No newline at end of file diff --git a/cocos2d/core/renderer/assemblers/label/bmfont-assembler.js b/cocos2d/core/renderer/utils/label/bmfont.js similarity index 88% rename from cocos2d/core/renderer/assemblers/label/bmfont-assembler.js rename to cocos2d/core/renderer/utils/label/bmfont.js index 3628974e6c..b66af614a2 100644 --- a/cocos2d/core/renderer/assemblers/label/bmfont-assembler.js +++ b/cocos2d/core/renderer/utils/label/bmfont.js @@ -31,8 +31,6 @@ const Overflow = Label.Overflow; const TextUtils = require('../../../utils/text-utils').TextUtils; -const ttf = require('./ttf-assembler'); - let FontLetterDefinition = function() { this._u = 0; this._v = 0; @@ -136,10 +134,6 @@ let _labelHeight = 0; let _maxLineWidth = 0; module.exports = { - createData (comp) { - return comp.requestRenderData(); - }, - update (comp) { if (!comp._renderData.vertDirty) return; @@ -158,50 +152,6 @@ module.exports = { this._resetProperties(); }, - fillVertexBuffer (comp, off, vbuf, uintbuf) { - let node = comp.node; - let renderData = comp._renderData; - let data = renderData._data; - let z = node._position.z; - let color = node.color._val; - - node._updateWorldMatrix(); - let matrix = node._worldMatrix; - let a = matrix.m00, - b = matrix.m01, - c = matrix.m04, - d = matrix.m05, - tx = matrix.m12, - ty = matrix.m13; - - let vert; - let length = renderData.dataLength; - for (let i = 0; i < length; i++) { - vert = data[i]; - vbuf[off + 0] = vert.x * a + vert.y * c + tx; - vbuf[off + 1] = vert.x * b + vert.y * d + ty; - vbuf[off + 2] = z; - vbuf[off + 4] = vert.u; - vbuf[off + 5] = vert.v; - uintbuf[off + 3] = color; - off += 6; - } - }, - - fillIndexBuffer (comp, offset, vertexId, ibuf) { - let renderData = comp._renderData; - let length = renderData.indiceCount; - for (let i = 0; i < length; i+=6) { - ibuf[offset++] = vertexId; - ibuf[offset++] = vertexId+1; - ibuf[offset++] = vertexId+2; - ibuf[offset++] = vertexId+1; - ibuf[offset++] = vertexId+3; - ibuf[offset++] = vertexId+2; - vertexId += 4; - } - }, - _updateFontScale () { _bmfontScale = _fontSize / _originFontSize; }, @@ -724,58 +674,6 @@ module.exports = { }, appendQuad (renderData, texture, rect, rotated, x, y, scale) { - let dataOffset = renderData.dataLength; - - renderData.dataLength += 4; - renderData.vertexCount = renderData.dataLength; - renderData.indiceCount = renderData.dataLength / 2 * 3; - - let data = renderData._data; - let texw = texture.width, - texh = texture.height; - - let rectWidth = rect.width, - rectHeight = rect.height; - - let l, b, r, t; - if (!rotated) { - l = (rect.x) / texw; - r = (rect.x + rectWidth) / texw; - b = (rect.y + rectHeight) / texh; - t = (rect.y) / texh; - - data[dataOffset].u = l; - data[dataOffset].v = b; - data[dataOffset+1].u = r; - data[dataOffset+1].v = b; - data[dataOffset+2].u = l; - data[dataOffset+2].v = t; - data[dataOffset+3].u = r; - data[dataOffset+3].v = t; - } else { - l = (rect.x) / texw; - r = (rect.x + rectHeight) / texw; - b = (rect.y + rectWidth) / texh; - t = (rect.y) / texh; - - data[dataOffset].u = l; - data[dataOffset].v = t; - data[dataOffset+1].u = l; - data[dataOffset+1].v = b; - data[dataOffset+2].u = r; - data[dataOffset+2].v = t; - data[dataOffset+3].u = r; - data[dataOffset+3].v = b; - } - - data[dataOffset].x = x; - data[dataOffset].y = y - rectHeight * scale; - data[dataOffset+1].x = x + rectWidth * scale; - data[dataOffset+1].y = y - rectHeight * scale; - data[dataOffset+2].x = x; - data[dataOffset+2].y = y; - data[dataOffset+3].x = x + rectWidth * scale; - data[dataOffset+3].y = y; }, _computeAlignmentOffset: function() { diff --git a/cocos2d/core/renderer/assemblers/label/ttf-assembler.js b/cocos2d/core/renderer/utils/label/ttf.js similarity index 87% rename from cocos2d/core/renderer/assemblers/label/ttf-assembler.js rename to cocos2d/core/renderer/utils/label/ttf.js index bc632397fb..fd5b89eef9 100644 --- a/cocos2d/core/renderer/assemblers/label/ttf-assembler.js +++ b/cocos2d/core/renderer/utils/label/ttf.js @@ -33,8 +33,6 @@ const Overflow = Label.Overflow; const TextUtils = utils.TextUtils; const CustomFontLoader = utils.CustomFontLoader; -const spriteAssembler = require('../sprite/simple'); - let _comp = null; let _context = null; @@ -72,64 +70,6 @@ let _isItalic = false; let _isUnderline = false; module.exports = { - createData (comp) { - let renderData = comp.requestRenderData(); - - renderData.dataLength = 4; - renderData.vertexCount = 4; - renderData.indiceCount = 6; - - let data = renderData._data; - data[0].u = 0; - data[0].v = 1; - data[1].u = 1; - data[1].v = 1; - data[2].u = 0; - data[2].v = 0; - data[3].u = 1; - data[3].v = 0; - return renderData; - }, - - fillVertexBuffer (comp, off, vbuf, uintbuf) { - let node = comp.node; - let renderData = comp._renderData; - let data = renderData._data; - let z = node._position.z; - let color = cc.Color.WHITE._val; - - node._updateWorldMatrix(); - let matrix = node._worldMatrix; - let a = matrix.m00, - b = matrix.m01, - c = matrix.m04, - d = matrix.m05, - tx = matrix.m12, - ty = matrix.m13; - - let vert; - let length = renderData.dataLength; - for (let i = 0; i < length; i++) { - vert = data[i]; - vbuf[off + 0] = vert.x * a + vert.y * c + tx; - vbuf[off + 1] = vert.x * b + vert.y * d + ty; - vbuf[off + 2] = z; - vbuf[off + 4] = vert.u; - vbuf[off + 5] = vert.v; - uintbuf[off + 3] = color; - off += 6; - } - }, - - fillIndexBuffer (comp, offset, vertexId, ibuf) { - ibuf[offset + 0] = vertexId; - ibuf[offset + 1] = vertexId + 1; - ibuf[offset + 2] = vertexId + 2; - ibuf[offset + 3] = vertexId + 1; - ibuf[offset + 4] = vertexId + 3; - ibuf[offset + 5] = vertexId + 2; - }, - update (comp) { if (!comp._renderData.vertDirty) return; @@ -141,13 +81,13 @@ module.exports = { this._calculateSplitedStrings(); this._updateLabelDimensions(); this._calculateTextBaseline(); - this._updateTexture(); - - this._updateVerts(); - + this._updateTexture(_comp); + _comp._actualFontSize = _fontSize; _comp.node.setContentSize(_canvasSize); + this._updateVerts(_comp); + _comp._renderData.vertDirty = _comp._renderData.uvDirty = false; _context = null; @@ -159,22 +99,6 @@ module.exports = { }, _updateVerts () { - let renderData = _comp._renderData; - - let width = _canvasSize.width, - height = _canvasSize.height, - appx = renderData._pivotX * width, - appy = renderData._pivotY * height; - - let data = renderData._data; - data[0].x = -appx; - data[0].y = -appy; - data[1].x = width - appx; - data[1].y = -appy; - data[2].x = -appx; - data[2].y = height - appy; - data[3].x = width - appx; - data[3].y = height - appy; }, _updateFontFamly () { @@ -197,8 +121,9 @@ module.exports = { }, _updateProperties () { - _context = _comp._context; - _canvas = _comp._canvas; + let assemblerData = _comp._assemblerData; + _context = assemblerData._context; + _canvas = assemblerData._canvas; _texture = _comp._texture; _string = _comp.string.toString(); @@ -267,7 +192,7 @@ module.exports = { return cc.v2(labelX, firstLinelabelY); }, - _updateTexture () { + _updateTexture (comp) { _context.clearRect(0, 0, _canvas.width, _canvas.height); _context.font = _fontDesc; From 6f746a322a211cba31c981dab6369dcd4db10e6a Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Fri, 30 Mar 2018 09:53:27 +0800 Subject: [PATCH 02/35] fixed get label assembler --- .../core/renderer/assemblers/label/index.js | 31 ++++++++++++------- .../renderer/canvas/renderers/label/index.js | 2 ++ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/cocos2d/core/renderer/assemblers/label/index.js b/cocos2d/core/renderer/assemblers/label/index.js index a4bcc390b0..00639c4e26 100644 --- a/cocos2d/core/renderer/assemblers/label/index.js +++ b/cocos2d/core/renderer/assemblers/label/index.js @@ -43,27 +43,36 @@ var labelAssembler = js.addon({ updateRenderData (comp) { this.datas.length = 0; - if (comp.string !== undefined && comp.string !== null && comp.string !== "") { - let renderData = comp._renderData; - // let size = comp.node._contentSize; - // let anchor = comp.node._anchorPoint; - // renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); + if (comp.string === undefined || + comp.string === null || + comp.string === "" || + !comp._assembler) { + return this.datas; + } - comp._assembler.update(comp); + let renderData = comp._renderData; - renderData.material = comp.getMaterial(); - this.datas.push(renderData); - } + // let size = comp.node._contentSize; + // let anchor = comp.node._anchorPoint; + // renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); + + comp._assembler.update(comp); + + renderData.material = comp.getMaterial(); + this.datas.push(renderData); return this.datas; }, fillBuffers (comp, batchData, vertexId, vbuf, uintbuf, ibuf) { + let assembler = comp._assembler; + if (!assembler) return; + let vertexOffset = batchData.byteOffset / 4, indiceOffset = batchData.indiceOffset; - comp._assembler.fillVertexBuffer(comp, vertexOffset, vbuf, uintbuf); - comp._assembler.fillIndexBuffer(comp, indiceOffset, vertexId, ibuf); + assembler.fillVertexBuffer(comp, vertexOffset, vbuf, uintbuf); + assembler.fillIndexBuffer(comp, indiceOffset, vertexId, ibuf); } }, assembler); diff --git a/cocos2d/core/renderer/canvas/renderers/label/index.js b/cocos2d/core/renderer/canvas/renderers/label/index.js index 2e4fb2f3cb..368ec246a2 100644 --- a/cocos2d/core/renderer/canvas/renderers/label/index.js +++ b/cocos2d/core/renderer/canvas/renderers/label/index.js @@ -48,6 +48,8 @@ module.exports = { } let assembler = comp._assembler; + if (!assembler) return 0; + assembler.update(comp); return assembler.draw(ctx, comp); } From 51639a158acaade48d4cc4f2590ad7fa4b4cc880 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 30 Mar 2018 14:11:51 +0800 Subject: [PATCH 03/35] Fix bug reported from ye man ren --- cocos2d/core/components/CCLabel.js | 1 - cocos2d/core/components/CCRichText.js | 4 + cocos2d/core/renderer/render-engine.js | 8 +- cocos2d/core/renderer/render-engine.jsb.js | 19963 +++++++++---------- cocos2d/deprecated.js | 7 + 5 files changed, 9996 insertions(+), 9987 deletions(-) diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index a262d53d6e..9998857c99 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -342,7 +342,6 @@ var Label = cc.Class({ if (value && this._isSystemFontUsed) this._isSystemFontUsed = false; - if ( typeof value === 'string' ) { cc.warnID(4000); } diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 3eebd4d011..13153a5e0a 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -65,6 +65,10 @@ var pool = new js.Pool(function (node) { if (CC_DEV) { cc.assert(!node._parent, 'Recycling node\'s parent should be null!'); } + let Flags = cc.Object.Flags; + if (node._objFlags & Flags.Destroyed || node._objFlags & Flags.Destroying) { + return false; + } if (node.getComponent(cc.LabelOutline)) { return false; } diff --git a/cocos2d/core/renderer/render-engine.js b/cocos2d/core/renderer/render-engine.js index 7f1f530ef0..e13d544a30 100644 --- a/cocos2d/core/renderer/render-engine.js +++ b/cocos2d/core/renderer/render-engine.js @@ -14600,7 +14600,7 @@ var SpriteMaterial = (function (Material$$1) { }; SpriteMaterial.prototype.clone = function clone () { - var copy = new SpriteMaterial(values); + var copy = new SpriteMaterial(); copy.texture = this.texture; copy.useTexture = this.useTexture; copy.useModel = this.useModel; @@ -14672,7 +14672,7 @@ var GraySpriteMaterial = (function (Material$$1) { }; GraySpriteMaterial.prototype.clone = function clone () { - var copy = new GraySpriteMaterial(values); + var copy = new GraySpriteMaterial(); copy.texture = this.texture; copy.updateHash(); return copy; @@ -14762,7 +14762,7 @@ var StencilMaterial = (function (Material$$1) { }; StencilMaterial.prototype.clone = function clone () { - var copy = new StencilMaterial(values); + var copy = new StencilMaterial(); copy.useTexture = this.useTexture; copy.texture = this.texture; copy.alphaThreshold = this.alphaThreshold; @@ -14903,7 +14903,7 @@ var ParticleMaterial = (function (Material$$1) { }; ParticleMaterial.prototype.clone = function clone () { - var copy = new ParticleMaterial(values); + var copy = new ParticleMaterial(); copy.texture = this.texture; copy.stateMap = this.stateMap; copy.quadMap = this.quadMap; diff --git a/cocos2d/core/renderer/render-engine.jsb.js b/cocos2d/core/renderer/render-engine.jsb.js index 2c83c4a46c..06416dcbc0 100644 --- a/cocos2d/core/renderer/render-engine.jsb.js +++ b/cocos2d/core/renderer/render-engine.jsb.js @@ -27,5134 +27,5669 @@ var renderEngine = (function () { - 'use strict'; - - var _d2r = Math.PI / 180.0; - var _r2d = 180.0 / Math.PI; - - /** - * @property {number} EPSILON - */ - var EPSILON = 0.000001; - - /** - * Tests whether or not the arguments have approximately the same value, within an absolute - * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less - * than or equal to 1.0, and a relative tolerance is used for larger values) - * - * @param {Number} a The first number to test. - * @param {Number} b The second number to test. - * @returns {Boolean} True if the numbers are approximately equal, false otherwise. - */ - function equals(a, b) { - return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); - } - - /** - * Tests whether or not the arguments have approximately the same value by given maxDiff - * - * @param {Number} a The first number to test. - * @param {Number} b The second number to test. - * @param {Number} maxDiff Maximum difference. - * @returns {Boolean} True if the numbers are approximately equal, false otherwise. - */ - function approx(a, b, maxDiff) { - maxDiff = maxDiff || EPSILON; - return Math.abs(a - b) <= maxDiff; - } - - /** - * Clamps a value between a minimum float and maximum float value. - * - * @method clamp - * @param {number} val - * @param {number} min - * @param {number} max - * @return {number} - */ - function clamp(val, min, max) { - return val < min ? min : val > max ? max : val; - } - - /** - * Clamps a value between 0 and 1. - * - * @method clamp01 - * @param {number} val - * @return {number} - */ - function clamp01(val) { - return val < 0 ? 0 : val > 1 ? 1 : val; - } - - /** - * @method lerp - * @param {number} from - * @param {number} to - * @param {number} ratio - the interpolation coefficient - * @return {number} - */ - function lerp(from, to, ratio) { - return from + (to - from) * ratio; - } - - /** - * Convert Degree To Radian - * - * @param {Number} a Angle in Degrees - */ - function toRadian(a) { - return a * _d2r; - } - - /** - * Convert Radian To Degree - * - * @param {Number} a Angle in Radian - */ - function toDegree(a) { - return a * _r2d; - } - - /** - * @method random - */ - var random = Math.random; - - /** - * Returns a floating-point random number between min (inclusive) and max (exclusive). - * - * @method randomRange - * @param {number} min - * @param {number} max - * @return {number} the random number - */ - function randomRange(min, max) { - return Math.random() * (max - min) + min; - } - - /** - * Returns a random integer between min (inclusive) and max (exclusive). - * - * @method randomRangeInt - * @param {number} min - * @param {number} max - * @return {number} the random integer - */ - function randomRangeInt(min, max) { - return Math.floor(randomRange(min, max)); - } - - /** - * Returns the next power of two for the value - * - * @method nextPow2 - * @param {number} val - * @return {number} the the next power of two - */ - function nextPow2(val) { - --val; - val = (val >> 1) | val; - val = (val >> 2) | val; - val = (val >> 4) | val; - val = (val >> 8) | val; - val = (val >> 16) | val; - ++val; - - return val; - } - - /** - * Bit twiddling hacks for JavaScript. - * - * Author: Mikola Lysenko - * - * Ported from Stanford bit twiddling hack library: - * http://graphics.stanford.edu/~seander/bithacks.html - */ - - // Number of bits in an integer - var INT_BITS = 32; - var INT_MAX = 0x7fffffff; - var INT_MIN = -1<<(INT_BITS-1); - - /** - * Returns -1, 0, +1 depending on sign of x - * - * @param {number} v - * @returns {number} - */ - function sign(v) { - return (v > 0) - (v < 0); - } - - /** - * Computes absolute value of integer - * - * @param {number} v - * @returns {number} - */ - function abs(v) { - var mask = v >> (INT_BITS-1); - return (v ^ mask) - mask; - } - - /** - * Computes minimum of integers x and y - * - * @param {number} x - * @param {number} y - * @returns {number} - */ - function min(x, y) { - return y ^ ((x ^ y) & -(x < y)); - } - - /** - * Computes maximum of integers x and y - * - * @param {number} x - * @param {number} y - * @returns {number} - */ - function max(x, y) { - return x ^ ((x ^ y) & -(x < y)); - } - - /** - * Checks if a number is a power of two - * - * @param {number} v - * @returns {boolean} - */ - function isPow2(v) { - return !(v & (v-1)) && (!!v); - } - - /** - * Computes log base 2 of v - * - * @param {number} v - * @returns {number} - */ - function log2(v) { - var r, shift; - r = (v > 0xFFFF) << 4; v >>>= r; - shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; - shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; - shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; - return r | (v >> 1); - } - - /** - * Computes log base 10 of v - * - * @param {number} v - * @returns {number} - */ - function log10(v) { - return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : - (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : - (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; - } - - /** - * Counts number of bits - * - * @param {number} v - * @returns {number} - */ - function popCount(v) { - v = v - ((v >>> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); - return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; - } - - /** - * Counts number of trailing zeros - * - * @param {number} v - * @returns {number} - */ - function countTrailingZeros(v) { - var c = 32; - v &= -v; - if (v) { c--; } - if (v & 0x0000FFFF) { c -= 16; } - if (v & 0x00FF00FF) { c -= 8; } - if (v & 0x0F0F0F0F) { c -= 4; } - if (v & 0x33333333) { c -= 2; } - if (v & 0x55555555) { c -= 1; } - return c; - } - - /** - * Rounds to next power of 2 - * - * @param {number} v - * @returns {number} - */ - function nextPow2$1(v) { - v += v === 0; - --v; - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v + 1; - } - - /** - * Rounds down to previous power of 2 - * - * @param {number} v - * @returns {number} - */ - function prevPow2(v) { - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v - (v>>>1); - } - - /** - * Computes parity of word - * - * @param {number} v - * @returns {number} - */ - function parity(v) { - v ^= v >>> 16; - v ^= v >>> 8; - v ^= v >>> 4; - v &= 0xf; - return (0x6996 >>> v) & 1; - } - - var REVERSE_TABLE = new Array(256); - - (function(tab) { - for(var i=0; i<256; ++i) { - var v = i, r = i, s = 7; - for (v >>>= 1; v; v >>>= 1) { - r <<= 1; - r |= v & 1; - --s; - } - tab[i] = (r << s) & 0xff; +'use strict'; + +var _d2r = Math.PI / 180.0; +var _r2d = 180.0 / Math.PI; + +/** + * @property {number} EPSILON + */ +var EPSILON = 0.000001; + +/** + * Tests whether or not the arguments have approximately the same value, within an absolute + * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less + * than or equal to 1.0, and a relative tolerance is used for larger values) + * + * @param {Number} a The first number to test. + * @param {Number} b The second number to test. + * @returns {Boolean} True if the numbers are approximately equal, false otherwise. + */ +function equals(a, b) { + return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); +} + +/** + * Tests whether or not the arguments have approximately the same value by given maxDiff + * + * @param {Number} a The first number to test. + * @param {Number} b The second number to test. + * @param {Number} maxDiff Maximum difference. + * @returns {Boolean} True if the numbers are approximately equal, false otherwise. + */ +function approx(a, b, maxDiff) { + maxDiff = maxDiff || EPSILON; + return Math.abs(a - b) <= maxDiff; +} + +/** + * Clamps a value between a minimum float and maximum float value. + * + * @method clamp + * @param {number} val + * @param {number} min + * @param {number} max + * @return {number} + */ +function clamp(val, min, max) { + return val < min ? min : val > max ? max : val; +} + +/** + * Clamps a value between 0 and 1. + * + * @method clamp01 + * @param {number} val + * @return {number} + */ +function clamp01(val) { + return val < 0 ? 0 : val > 1 ? 1 : val; +} + +/** + * @method lerp + * @param {number} from + * @param {number} to + * @param {number} ratio - the interpolation coefficient + * @return {number} + */ +function lerp(from, to, ratio) { + return from + (to - from) * ratio; +} + +/** +* Convert Degree To Radian +* +* @param {Number} a Angle in Degrees +*/ +function toRadian(a) { + return a * _d2r; +} + +/** +* Convert Radian To Degree +* +* @param {Number} a Angle in Radian +*/ +function toDegree(a) { + return a * _r2d; +} + +/** +* @method random +*/ +var random = Math.random; + +/** + * Returns a floating-point random number between min (inclusive) and max (exclusive). + * + * @method randomRange + * @param {number} min + * @param {number} max + * @return {number} the random number + */ +function randomRange(min, max) { + return Math.random() * (max - min) + min; +} + +/** + * Returns a random integer between min (inclusive) and max (exclusive). + * + * @method randomRangeInt + * @param {number} min + * @param {number} max + * @return {number} the random integer + */ +function randomRangeInt(min, max) { + return Math.floor(randomRange(min, max)); +} + +/** + * Returns the next power of two for the value + * + * @method nextPow2 + * @param {number} val + * @return {number} the the next power of two + */ +function nextPow2(val) { + --val; + val = (val >> 1) | val; + val = (val >> 2) | val; + val = (val >> 4) | val; + val = (val >> 8) | val; + val = (val >> 16) | val; + ++val; + + return val; +} + +/** + * Bit twiddling hacks for JavaScript. + * + * Author: Mikola Lysenko + * + * Ported from Stanford bit twiddling hack library: + * http://graphics.stanford.edu/~seander/bithacks.html + */ + +// Number of bits in an integer +var INT_BITS = 32; +var INT_MAX = 0x7fffffff; +var INT_MIN = -1<<(INT_BITS-1); + +/** + * Returns -1, 0, +1 depending on sign of x + * + * @param {number} v + * @returns {number} + */ +function sign(v) { + return (v > 0) - (v < 0); +} + +/** + * Computes absolute value of integer + * + * @param {number} v + * @returns {number} + */ +function abs(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +/** + * Computes minimum of integers x and y + * + * @param {number} x + * @param {number} y + * @returns {number} + */ +function min(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +/** + * Computes maximum of integers x and y + * + * @param {number} x + * @param {number} y + * @returns {number} + */ +function max(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +/** + * Checks if a number is a power of two + * + * @param {number} v + * @returns {boolean} + */ +function isPow2(v) { + return !(v & (v-1)) && (!!v); +} + +/** + * Computes log base 2 of v + * + * @param {number} v + * @returns {number} + */ +function log2(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +/** + * Computes log base 10 of v + * + * @param {number} v + * @returns {number} + */ +function log10(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +/** + * Counts number of bits + * + * @param {number} v + * @returns {number} + */ +function popCount(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +/** + * Counts number of trailing zeros + * + * @param {number} v + * @returns {number} + */ +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) { c--; } + if (v & 0x0000FFFF) { c -= 16; } + if (v & 0x00FF00FF) { c -= 8; } + if (v & 0x0F0F0F0F) { c -= 4; } + if (v & 0x33333333) { c -= 2; } + if (v & 0x55555555) { c -= 1; } + return c; +} + +/** + * Rounds to next power of 2 + * + * @param {number} v + * @returns {number} + */ +function nextPow2$1(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +/** + * Rounds down to previous power of 2 + * + * @param {number} v + * @returns {number} + */ +function prevPow2(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +/** + * Computes parity of word + * + * @param {number} v + * @returns {number} + */ +function parity(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; } - })(REVERSE_TABLE); - - /** - * Reverse bits in a 32 bit word - * - * @param {number} v - * @returns {number} - */ - function reverse(v) { - return (REVERSE_TABLE[v & 0xff] << 24) | - (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | - (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | - REVERSE_TABLE[(v >>> 24) & 0xff]; + tab[i] = (r << s) & 0xff; } - - /** - * Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes - * - * @param {number} x - * @param {number} y - * @returns {number} - */ - function interleave2(x, y) { - x &= 0xFFFF; - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; - - y &= 0xFFFF; - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; - - return x | (y << 1); +})(REVERSE_TABLE); + +/** + * Reverse bits in a 32 bit word + * + * @param {number} v + * @returns {number} + */ +function reverse(v) { + return (REVERSE_TABLE[v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +/** + * Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes + * + * @param {number} x + * @param {number} y + * @returns {number} + */ +function interleave2(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +/** + * Extracts the nth interleaved component + * + * @param {number} v + * @param {number} n + * @returns {number} + */ +function deinterleave2(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + +/** + * Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes + * + * @param {number} x + * @param {number} y + * @param {number} z + * @returns {number} + */ +function interleave3(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +/** + * Extracts nth interleaved component of a 3-tuple + * + * @param {number} v + * @param {number} n + * @returns {number} + */ +function deinterleave3(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +/** + * Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) + * + * @param {number} v + * @returns {number} + */ +function nextCombination(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + +var bits_ = Object.freeze({ + INT_BITS: INT_BITS, + INT_MAX: INT_MAX, + INT_MIN: INT_MIN, + sign: sign, + abs: abs, + min: min, + max: max, + isPow2: isPow2, + log2: log2, + log10: log10, + popCount: popCount, + countTrailingZeros: countTrailingZeros, + nextPow2: nextPow2$1, + prevPow2: prevPow2, + parity: parity, + reverse: reverse, + interleave2: interleave2, + deinterleave2: deinterleave2, + interleave3: interleave3, + deinterleave3: deinterleave3, + nextCombination: nextCombination +}); + +var _tmp = new Array(2); + +var _vec2 = function _vec2(x, y) { + this.x = x; + this.y = y; +}; + +_vec2.prototype.toJSON = function toJSON () { + _tmp[0] = this.x; + _tmp[1] = this.y; + + return _tmp; +}; + +/** + * @class 2 Dimensional Vector + * @name vec2 + */ +var vec2 = {}; + +/** + * Creates a new, empty vec2 + * + * @returns {vec2} a new 2D vector + */ +vec2.create = function () { + return new _vec2(0, 0); +}; + +/** + * Creates a new vec2 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} a new 2D vector + */ +vec2.new = function (x, y) { + return new _vec2(x, y); +}; + +/** + * Creates a new vec2 initialized with values from an existing vector + * + * @param {vec2} a vector to clone + * @returns {vec2} a new 2D vector + */ +vec2.clone = function (a) { + return new _vec2(a.x, a.y); +}; + +/** + * Copy the values from one vec2 to another + * + * @param {vec2} out the receiving vector + * @param {vec2} a the source vector + * @returns {vec2} out + */ +vec2.copy = function (out, a) { + out.x = a.x; + out.y = a.y; + return out; +}; + +/** + * Set the components of a vec2 to the given values + * + * @param {vec2} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} out + */ +vec2.set = function (out, x, y) { + out.x = x; + out.y = y; + return out; +}; + +/** + * Adds two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.add = function (out, a, b) { + out.x = a.x + b.x; + out.y = a.y + b.y; + return out; +}; + +/** + * Subtracts vector b from vector a + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.subtract = function (out, a, b) { + out.x = a.x - b.x; + out.y = a.y - b.y; + return out; +}; + +/** + * Alias for {@link vec2.subtract} + * @function + */ +vec2.sub = vec2.subtract; + +/** + * Multiplies two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.multiply = function (out, a, b) { + out.x = a.x * b.x; + out.y = a.y * b.y; + return out; +}; + +/** + * Alias for {@link vec2.multiply} + * @function + */ +vec2.mul = vec2.multiply; + +/** + * Divides two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.divide = function (out, a, b) { + out.x = a.x / b.x; + out.y = a.y / b.y; + return out; +}; + +/** + * Alias for {@link vec2.divide} + * @function + */ +vec2.div = vec2.divide; + +/** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to ceil + * @returns {vec2} out + */ +vec2.ceil = function (out, a) { + out.x = Math.ceil(a.x); + out.y = Math.ceil(a.y); + return out; +}; + +/** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to floor + * @returns {vec2} out + */ +vec2.floor = function (out, a) { + out.x = Math.floor(a.x); + out.y = Math.floor(a.y); + return out; +}; + +/** + * Returns the minimum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.min = function (out, a, b) { + out.x = Math.min(a.x, b.x); + out.y = Math.min(a.y, b.y); + return out; +}; + +/** + * Returns the maximum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.max = function (out, a, b) { + out.x = Math.max(a.x, b.x); + out.y = Math.max(a.y, b.y); + return out; +}; + +/** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to round + * @returns {vec2} out + */ +vec2.round = function (out, a) { + out.x = Math.round(a.x); + out.y = Math.round(a.y); + return out; +}; + +/** + * Scales a vec2 by a scalar number + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec2} out + */ +vec2.scale = function (out, a, b) { + out.x = a.x * b; + out.y = a.y * b; + return out; +}; + +/** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec2} out + */ +vec2.scaleAndAdd = function (out, a, b, scale) { + out.x = a.x + (b.x * scale); + out.y = a.y + (b.y * scale); + return out; +}; + +/** + * Calculates the euclidian distance between two vec2's + * + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {Number} distance between a and b + */ +vec2.distance = function (a, b) { + var x = b.x - a.x, + y = b.y - a.y; + return Math.sqrt(x * x + y * y); +}; + +/** + * Alias for {@link vec2.distance} + * @function + */ +vec2.dist = vec2.distance; + +/** + * Calculates the squared euclidian distance between two vec2's + * + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {Number} squared distance between a and b + */ +vec2.squaredDistance = function (a, b) { + var x = b.x - a.x, + y = b.y - a.y; + return x * x + y * y; +}; + +/** + * Alias for {@link vec2.squaredDistance} + * @function + */ +vec2.sqrDist = vec2.squaredDistance; + +/** + * Calculates the length of a vec2 + * + * @param {vec2} a vector to calculate length of + * @returns {Number} length of a + */ +vec2.length = function (a) { + var x = a.x, + y = a.y; + return Math.sqrt(x * x + y * y); +}; + +/** + * Alias for {@link vec2.length} + * @function + */ +vec2.len = vec2.length; + +/** + * Calculates the squared length of a vec2 + * + * @param {vec2} a vector to calculate squared length of + * @returns {Number} squared length of a + */ +vec2.squaredLength = function (a) { + var x = a.x, + y = a.y; + return x * x + y * y; +}; + +/** + * Alias for {@link vec2.squaredLength} + * @function + */ +vec2.sqrLen = vec2.squaredLength; + +/** + * Negates the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to negate + * @returns {vec2} out + */ +vec2.negate = function (out, a) { + out.x = -a.x; + out.y = -a.y; + return out; +}; + +/** + * Returns the inverse of the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to invert + * @returns {vec2} out + */ +vec2.inverse = function (out, a) { + out.x = 1.0 / a.x; + out.y = 1.0 / a.y; + return out; +}; + +/** + * Returns the inverse of the components of a vec2 safely + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to invert + * @returns {vec2} out + */ +vec2.inverseSafe = function (out, a) { + var x = a.x, + y = a.y; + + if (Math.abs(x) < EPSILON) { + out.x = 0; + } else { + out.x = 1.0 / x; } - - /** - * Extracts the nth interleaved component - * - * @param {number} v - * @param {number} n - * @returns {number} - */ - function deinterleave2(v, n) { - v = (v >>> n) & 0x55555555; - v = (v | (v >>> 1)) & 0x33333333; - v = (v | (v >>> 2)) & 0x0F0F0F0F; - v = (v | (v >>> 4)) & 0x00FF00FF; - v = (v | (v >>> 16)) & 0x000FFFF; - return (v << 16) >> 16; - } - - /** - * Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes - * - * @param {number} x - * @param {number} y - * @param {number} z - * @returns {number} - */ - function interleave3(x, y, z) { - x &= 0x3FF; - x = (x | (x<<16)) & 4278190335; - x = (x | (x<<8)) & 251719695; - x = (x | (x<<4)) & 3272356035; - x = (x | (x<<2)) & 1227133513; - - y &= 0x3FF; - y = (y | (y<<16)) & 4278190335; - y = (y | (y<<8)) & 251719695; - y = (y | (y<<4)) & 3272356035; - y = (y | (y<<2)) & 1227133513; - x |= (y << 1); - - z &= 0x3FF; - z = (z | (z<<16)) & 4278190335; - z = (z | (z<<8)) & 251719695; - z = (z | (z<<4)) & 3272356035; - z = (z | (z<<2)) & 1227133513; - - return x | (z << 2); - } - - /** - * Extracts nth interleaved component of a 3-tuple - * - * @param {number} v - * @param {number} n - * @returns {number} - */ - function deinterleave3(v, n) { - v = (v >>> n) & 1227133513; - v = (v | (v>>>2)) & 3272356035; - v = (v | (v>>>4)) & 251719695; - v = (v | (v>>>8)) & 4278190335; - v = (v | (v>>>16)) & 0x3FF; - return (v<<22)>>22; - } - - /** - * Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) - * - * @param {number} v - * @returns {number} - */ - function nextCombination(v) { - var t = v | (v - 1); - return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); - } - - var bits_ = Object.freeze({ - INT_BITS: INT_BITS, - INT_MAX: INT_MAX, - INT_MIN: INT_MIN, - sign: sign, - abs: abs, - min: min, - max: max, - isPow2: isPow2, - log2: log2, - log10: log10, - popCount: popCount, - countTrailingZeros: countTrailingZeros, - nextPow2: nextPow2$1, - prevPow2: prevPow2, - parity: parity, - reverse: reverse, - interleave2: interleave2, - deinterleave2: deinterleave2, - interleave3: interleave3, - deinterleave3: deinterleave3, - nextCombination: nextCombination - }); - - var _tmp = new Array(2); - - var _vec2 = function _vec2(x, y) { - this.x = x; - this.y = y; - }; - - _vec2.prototype.toJSON = function toJSON () { - _tmp[0] = this.x; - _tmp[1] = this.y; - - return _tmp; - }; - - /** - * @class 2 Dimensional Vector - * @name vec2 - */ - var vec2 = {}; - - /** - * Creates a new, empty vec2 - * - * @returns {vec2} a new 2D vector - */ - vec2.create = function () { - return new _vec2(0, 0); - }; - - /** - * Creates a new vec2 initialized with the given values - * - * @param {Number} x X component - * @param {Number} y Y component - * @returns {vec2} a new 2D vector - */ - vec2.new = function (x, y) { - return new _vec2(x, y); - }; - - /** - * Creates a new vec2 initialized with values from an existing vector - * - * @param {vec2} a vector to clone - * @returns {vec2} a new 2D vector - */ - vec2.clone = function (a) { - return new _vec2(a.x, a.y); - }; - - /** - * Copy the values from one vec2 to another - * - * @param {vec2} out the receiving vector - * @param {vec2} a the source vector - * @returns {vec2} out - */ - vec2.copy = function (out, a) { - out.x = a.x; - out.y = a.y; - return out; - }; - - /** - * Set the components of a vec2 to the given values - * - * @param {vec2} out the receiving vector - * @param {Number} x X component - * @param {Number} y Y component - * @returns {vec2} out - */ - vec2.set = function (out, x, y) { - out.x = x; - out.y = y; - return out; - }; - - /** - * Adds two vec2's - * - * @param {vec2} out the receiving vector - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @returns {vec2} out - */ - vec2.add = function (out, a, b) { - out.x = a.x + b.x; - out.y = a.y + b.y; - return out; - }; - - /** - * Subtracts vector b from vector a - * - * @param {vec2} out the receiving vector - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @returns {vec2} out - */ - vec2.subtract = function (out, a, b) { - out.x = a.x - b.x; - out.y = a.y - b.y; - return out; - }; - - /** - * Alias for {@link vec2.subtract} - * @function - */ - vec2.sub = vec2.subtract; - - /** - * Multiplies two vec2's - * - * @param {vec2} out the receiving vector - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @returns {vec2} out - */ - vec2.multiply = function (out, a, b) { - out.x = a.x * b.x; - out.y = a.y * b.y; - return out; - }; - - /** - * Alias for {@link vec2.multiply} - * @function - */ - vec2.mul = vec2.multiply; - - /** - * Divides two vec2's - * - * @param {vec2} out the receiving vector - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @returns {vec2} out - */ - vec2.divide = function (out, a, b) { - out.x = a.x / b.x; - out.y = a.y / b.y; - return out; - }; - - /** - * Alias for {@link vec2.divide} - * @function - */ - vec2.div = vec2.divide; - - /** - * Math.ceil the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to ceil - * @returns {vec2} out - */ - vec2.ceil = function (out, a) { - out.x = Math.ceil(a.x); - out.y = Math.ceil(a.y); - return out; - }; - - /** - * Math.floor the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to floor - * @returns {vec2} out - */ - vec2.floor = function (out, a) { - out.x = Math.floor(a.x); - out.y = Math.floor(a.y); - return out; - }; - - /** - * Returns the minimum of two vec2's - * - * @param {vec2} out the receiving vector - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @returns {vec2} out - */ - vec2.min = function (out, a, b) { - out.x = Math.min(a.x, b.x); - out.y = Math.min(a.y, b.y); - return out; - }; - - /** - * Returns the maximum of two vec2's - * - * @param {vec2} out the receiving vector - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @returns {vec2} out - */ - vec2.max = function (out, a, b) { - out.x = Math.max(a.x, b.x); - out.y = Math.max(a.y, b.y); - return out; - }; - - /** - * Math.round the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to round - * @returns {vec2} out - */ - vec2.round = function (out, a) { - out.x = Math.round(a.x); - out.y = Math.round(a.y); - return out; - }; - - /** - * Scales a vec2 by a scalar number - * - * @param {vec2} out the receiving vector - * @param {vec2} a the vector to scale - * @param {Number} b amount to scale the vector by - * @returns {vec2} out - */ - vec2.scale = function (out, a, b) { - out.x = a.x * b; - out.y = a.y * b; - return out; - }; - - /** - * Adds two vec2's after scaling the second operand by a scalar value - * - * @param {vec2} out the receiving vector - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @param {Number} scale the amount to scale b by before adding - * @returns {vec2} out - */ - vec2.scaleAndAdd = function (out, a, b, scale) { - out.x = a.x + (b.x * scale); - out.y = a.y + (b.y * scale); - return out; - }; - - /** - * Calculates the euclidian distance between two vec2's - * - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @returns {Number} distance between a and b - */ - vec2.distance = function (a, b) { - var x = b.x - a.x, - y = b.y - a.y; - return Math.sqrt(x * x + y * y); - }; - - /** - * Alias for {@link vec2.distance} - * @function - */ - vec2.dist = vec2.distance; - - /** - * Calculates the squared euclidian distance between two vec2's - * - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @returns {Number} squared distance between a and b - */ - vec2.squaredDistance = function (a, b) { - var x = b.x - a.x, - y = b.y - a.y; - return x * x + y * y; - }; - - /** - * Alias for {@link vec2.squaredDistance} - * @function - */ - vec2.sqrDist = vec2.squaredDistance; - - /** - * Calculates the length of a vec2 - * - * @param {vec2} a vector to calculate length of - * @returns {Number} length of a - */ - vec2.length = function (a) { - var x = a.x, - y = a.y; - return Math.sqrt(x * x + y * y); - }; - - /** - * Alias for {@link vec2.length} - * @function - */ - vec2.len = vec2.length; - - /** - * Calculates the squared length of a vec2 - * - * @param {vec2} a vector to calculate squared length of - * @returns {Number} squared length of a - */ - vec2.squaredLength = function (a) { - var x = a.x, - y = a.y; - return x * x + y * y; - }; - - /** - * Alias for {@link vec2.squaredLength} - * @function - */ - vec2.sqrLen = vec2.squaredLength; - - /** - * Negates the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to negate - * @returns {vec2} out - */ - vec2.negate = function (out, a) { - out.x = -a.x; - out.y = -a.y; - return out; - }; - - /** - * Returns the inverse of the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to invert - * @returns {vec2} out - */ - vec2.inverse = function (out, a) { - out.x = 1.0 / a.x; + + if (Math.abs(y) < EPSILON) { + out.y = 0; + } else { out.y = 1.0 / a.y; - return out; - }; - - /** - * Returns the inverse of the components of a vec2 safely - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to invert - * @returns {vec2} out - */ - vec2.inverseSafe = function (out, a) { - var x = a.x, - y = a.y; - - if (Math.abs(x) < EPSILON) { - out.x = 0; + } + + return out; +}; + +/** + * Normalize a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to normalize + * @returns {vec2} out + */ +vec2.normalize = function (out, a) { + var x = a.x, + y = a.y; + var len = x * x + y * y; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out.x = a.x * len; + out.y = a.y * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec2's + * + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {Number} dot product of a and b + */ +vec2.dot = function (a, b) { + return a.x * b.x + a.y * b.y; +}; + +/** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param {vec3} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec3} out + */ +vec2.cross = function (out, a, b) { + var z = a.x * b.y - a.y * b.x; + out.x = out.y = 0; + out.z = z; + return out; +}; + +/** + * Performs a linear interpolation between two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {vec2} out + */ +vec2.lerp = function (out, a, b, t) { + var ax = a.x, + ay = a.y; + out.x = ax + t * (b.x - ax); + out.y = ay + t * (b.y - ay); + return out; +}; + +/** + * Generates a random vector with the given scale + * + * @param {vec2} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec2} out + */ +vec2.random = function (out, scale) { + scale = scale || 1.0; + var r = random() * 2.0 * Math.PI; + out.x = Math.cos(r) * scale; + out.y = Math.sin(r) * scale; + return out; +}; + +/** + * Transforms the vec2 with a mat2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat2} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat2 = function (out, a, m) { + var x = a.x, + y = a.y; + out.x = m.m00 * x + m.m02 * y; + out.y = m.m01 * x + m.m03 * y; + return out; +}; + +/** + * Transforms the vec2 with a mat23 + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat23} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat23 = function (out, a, m) { + var x = a.x, + y = a.y; + out.x = m.m00 * x + m.m02 * y + m.m04; + out.y = m.m01 * x + m.m03 * y + m.m05; + return out; +}; + +/** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat3} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat3 = function (out, a, m) { + var x = a.x, + y = a.y; + out.x = m.m00 * x + m.m03 * y + m.m06; + out.y = m.m01 * x + m.m04 * y + m.m07; + return out; +}; + +/** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat4} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat4 = function (out, a, m) { + var x = a.x, + y = a.y; + out.x = m.m00 * x + m.m04 * y + m.m12; + out.y = m.m01 * x + m.m05 * y + m.m13; + return out; +}; + +/** + * Perform some operation over an array of vec2s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ +vec2.forEach = (function () { + var vec = vec2.create(); + + return function (a, stride, offset, count, fn, arg) { + var i, l; + if (!stride) { + stride = 2; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min((count * stride) + offset, a.length); } else { - out.x = 1.0 / x; + l = a.length; } - - if (Math.abs(y) < EPSILON) { - out.y = 0; - } else { - out.y = 1.0 / a.y; + + for (i = offset; i < l; i += stride) { + vec.x = a[i]; vec.y = a[i + 1]; + fn(vec, vec, arg); + a[i] = vec.x; a[i + 1] = vec.y; } - - return out; + + return a; }; - - /** - * Normalize a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to normalize - * @returns {vec2} out - */ - vec2.normalize = function (out, a) { - var x = a.x, - y = a.y; - var len = x * x + y * y; - if (len > 0) { - //TODO: evaluate use of glm_invsqrt here? - len = 1 / Math.sqrt(len); - out.x = a.x * len; - out.y = a.y * len; - } - return out; - }; - - /** - * Calculates the dot product of two vec2's - * - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @returns {Number} dot product of a and b - */ - vec2.dot = function (a, b) { - return a.x * b.x + a.y * b.y; - }; - - /** - * Computes the cross product of two vec2's - * Note that the cross product must by definition produce a 3D vector - * - * @param {vec3} out the receiving vector - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @returns {vec3} out - */ - vec2.cross = function (out, a, b) { - var z = a.x * b.y - a.y * b.x; - out.x = out.y = 0; - out.z = z; - return out; - }; - - /** - * Performs a linear interpolation between two vec2's - * - * @param {vec2} out the receiving vector - * @param {vec2} a the first operand - * @param {vec2} b the second operand - * @param {Number} t interpolation amount between the two inputs - * @returns {vec2} out - */ - vec2.lerp = function (out, a, b, t) { - var ax = a.x, - ay = a.y; - out.x = ax + t * (b.x - ax); - out.y = ay + t * (b.y - ay); - return out; - }; - - /** - * Generates a random vector with the given scale - * - * @param {vec2} out the receiving vector - * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned - * @returns {vec2} out - */ - vec2.random = function (out, scale) { - scale = scale || 1.0; - var r = random() * 2.0 * Math.PI; - out.x = Math.cos(r) * scale; - out.y = Math.sin(r) * scale; - return out; - }; - - /** - * Transforms the vec2 with a mat2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a the vector to transform - * @param {mat2} m matrix to transform with - * @returns {vec2} out - */ - vec2.transformMat2 = function (out, a, m) { - var x = a.x, - y = a.y; - out.x = m.m00 * x + m.m02 * y; - out.y = m.m01 * x + m.m03 * y; - return out; - }; - - /** - * Transforms the vec2 with a mat23 - * - * @param {vec2} out the receiving vector - * @param {vec2} a the vector to transform - * @param {mat23} m matrix to transform with - * @returns {vec2} out - */ - vec2.transformMat23 = function (out, a, m) { - var x = a.x, - y = a.y; - out.x = m.m00 * x + m.m02 * y + m.m04; - out.y = m.m01 * x + m.m03 * y + m.m05; - return out; - }; - - /** - * Transforms the vec2 with a mat3 - * 3rd vector component is implicitly '1' - * - * @param {vec2} out the receiving vector - * @param {vec2} a the vector to transform - * @param {mat3} m matrix to transform with - * @returns {vec2} out - */ - vec2.transformMat3 = function (out, a, m) { - var x = a.x, - y = a.y; - out.x = m.m00 * x + m.m03 * y + m.m06; - out.y = m.m01 * x + m.m04 * y + m.m07; - return out; - }; - - /** - * Transforms the vec2 with a mat4 - * 3rd vector component is implicitly '0' - * 4th vector component is implicitly '1' - * - * @param {vec2} out the receiving vector - * @param {vec2} a the vector to transform - * @param {mat4} m matrix to transform with - * @returns {vec2} out - */ - vec2.transformMat4 = function (out, a, m) { - var x = a.x, - y = a.y; - out.x = m.m00 * x + m.m04 * y + m.m12; - out.y = m.m01 * x + m.m05 * y + m.m13; - return out; - }; - - /** - * Perform some operation over an array of vec2s. - * - * @param {Array} a the array of vectors to iterate over - * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed - * @param {Number} offset Number of elements to skip at the beginning of the array - * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array - * @param {Function} fn Function to call for each vector in the array - * @param {Object} [arg] additional argument to pass to fn - * @returns {Array} a - * @function - */ - vec2.forEach = (function () { - var vec = vec2.create(); - - return function (a, stride, offset, count, fn, arg) { - var i, l; - if (!stride) { - stride = 2; - } - - if (!offset) { - offset = 0; - } - - if (count) { - l = Math.min((count * stride) + offset, a.length); - } else { - l = a.length; - } - - for (i = offset; i < l; i += stride) { - vec.x = a[i]; vec.y = a[i + 1]; - fn(vec, vec, arg); - a[i] = vec.x; a[i + 1] = vec.y; - } - - return a; - }; - })(); - - /** - * Returns a string representation of a vector - * - * @param {vec2} a vector to represent as a string - * @returns {String} string representation of the vector - */ - vec2.str = function (a) { - return ("vec2(" + (a.x) + ", " + (a.y) + ")"); - }; - - /** - * Returns typed array - * - * @param {array} out - * @param {vec2} v - * @returns {array} - */ - vec2.array = function (out, v) { - out[0] = v.x; - out[1] = v.y; - - return out; - }; - - /** - * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) - * - * @param {vec2} a The first vector. - * @param {vec2} b The second vector. - * @returns {Boolean} True if the vectors are equal, false otherwise. - */ - vec2.exactEquals = function (a, b) { - return a.x === b.x && a.y === b.y; - }; - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec2} a The first vector. - * @param {vec2} b The second vector. - * @returns {Boolean} True if the vectors are equal, false otherwise. - */ - vec2.equals = function (a, b) { - var a0 = a.x, a1 = a.y; - var b0 = b.x, b1 = b.y; - return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && - Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1))); - }; - - var _tmp$1 = new Array(3); - - var _vec3 = function _vec3(x, y, z) { - this.x = x; - this.y = y; - this.z = z; - }; - - _vec3.prototype.toJSON = function toJSON () { - _tmp$1[0] = this.x; - _tmp$1[1] = this.y; - _tmp$1[2] = this.z; - - return _tmp$1; - }; - - /** - * @class 3 Dimensional Vector - * @name vec3 - */ - var vec3 = {}; - - /** - * Creates a new, empty vec3 - * - * @returns {vec3} a new 3D vector - */ - vec3.create = function () { - return new _vec3(0, 0, 0); - }; - - /** - * Creates a new vec3 initialized with the given values - * - * @param {Number} x X component - * @param {Number} y Y component - * @param {Number} z Z component - * @returns {vec3} a new 3D vector - */ - vec3.new = function (x, y, z) { - return new _vec3(x, y, z); - }; - - /** - * Creates a new vec3 initialized with values from an existing vector - * - * @param {vec3} a vector to clone - * @returns {vec3} a new 3D vector - */ - vec3.clone = function (a) { - return new _vec3(a.x, a.y, a.z); - }; - - /** - * Copy the values from one vec3 to another - * - * @param {vec3} out the receiving vector - * @param {vec3} a the source vector - * @returns {vec3} out - */ - vec3.copy = function (out, a) { - out.x = a.x; - out.y = a.y; - out.z = a.z; - return out; - }; - - /** - * Set the components of a vec3 to the given values - * - * @param {vec3} out the receiving vector - * @param {Number} x X component - * @param {Number} y Y component - * @param {Number} z Z component - * @returns {vec3} out - */ - vec3.set = function (out, x, y, z) { - out.x = x; - out.y = y; - out.z = z; - return out; - }; - - /** - * Adds two vec3's - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @returns {vec3} out - */ - vec3.add = function (out, a, b) { - out.x = a.x + b.x; - out.y = a.y + b.y; - out.z = a.z + b.z; - return out; - }; - - /** - * Subtracts vector b from vector a - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @returns {vec3} out - */ - vec3.subtract = function (out, a, b) { - out.x = a.x - b.x; - out.y = a.y - b.y; - out.z = a.z - b.z; - return out; - }; - - /** - * Alias for {@link vec3.subtract} - * @function - */ - vec3.sub = vec3.subtract; - - /** - * Multiplies two vec3's - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @returns {vec3} out - */ - vec3.multiply = function (out, a, b) { - out.x = a.x * b.x; - out.y = a.y * b.y; - out.z = a.z * b.z; - return out; - }; - - /** - * Alias for {@link vec3.multiply} - * @function - */ - vec3.mul = vec3.multiply; - - /** - * Divides two vec3's - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @returns {vec3} out - */ - vec3.divide = function (out, a, b) { - out.x = a.x / b.x; - out.y = a.y / b.y; - out.z = a.z / b.z; - return out; - }; - - /** - * Alias for {@link vec3.divide} - * @function - */ - vec3.div = vec3.divide; - - /** - * Math.ceil the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to ceil - * @returns {vec3} out - */ - vec3.ceil = function (out, a) { - out.x = Math.ceil(a.x); - out.y = Math.ceil(a.y); - out.z = Math.ceil(a.z); - return out; - }; - - /** - * Math.floor the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to floor - * @returns {vec3} out - */ - vec3.floor = function (out, a) { - out.x = Math.floor(a.x); - out.y = Math.floor(a.y); - out.z = Math.floor(a.z); - return out; - }; - - /** - * Returns the minimum of two vec3's - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @returns {vec3} out - */ - vec3.min = function (out, a, b) { - out.x = Math.min(a.x, b.x); - out.y = Math.min(a.y, b.y); - out.z = Math.min(a.z, b.z); - return out; - }; - - /** - * Returns the maximum of two vec3's - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @returns {vec3} out - */ - vec3.max = function (out, a, b) { - out.x = Math.max(a.x, b.x); - out.y = Math.max(a.y, b.y); - out.z = Math.max(a.z, b.z); - return out; - }; - - /** - * Math.round the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to round - * @returns {vec3} out - */ - vec3.round = function (out, a) { - out.x = Math.round(a.x); - out.y = Math.round(a.y); - out.z = Math.round(a.z); - return out; - }; - - /** - * Scales a vec3 by a scalar number - * - * @param {vec3} out the receiving vector - * @param {vec3} a the vector to scale - * @param {Number} b amount to scale the vector by - * @returns {vec3} out - */ - vec3.scale = function (out, a, b) { - out.x = a.x * b; - out.y = a.y * b; - out.z = a.z * b; - return out; - }; - - /** - * Adds two vec3's after scaling the second operand by a scalar value - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {Number} scale the amount to scale b by before adding - * @returns {vec3} out - */ - vec3.scaleAndAdd = function (out, a, b, scale) { - out.x = a.x + (b.x * scale); - out.y = a.y + (b.y * scale); - out.z = a.z + (b.z * scale); - return out; - }; - - /** - * Calculates the euclidian distance between two vec3's - * - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @returns {Number} distance between a and b - */ - vec3.distance = function (a, b) { - var x = b.x - a.x, +})(); + +/** + * Returns a string representation of a vector + * + * @param {vec2} a vector to represent as a string + * @returns {String} string representation of the vector + */ +vec2.str = function (a) { + return ("vec2(" + (a.x) + ", " + (a.y) + ")"); +}; + +/** + * Returns typed array + * + * @param {array} out + * @param {vec2} v + * @returns {array} + */ +vec2.array = function (out, v) { + out[0] = v.x; + out[1] = v.y; + + return out; +}; + +/** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ +vec2.exactEquals = function (a, b) { + return a.x === b.x && a.y === b.y; +}; + +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ +vec2.equals = function (a, b) { + var a0 = a.x, a1 = a.y; + var b0 = b.x, b1 = b.y; + return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && + Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1))); +}; + +var _tmp$1 = new Array(3); + +var _vec3 = function _vec3(x, y, z) { + this.x = x; + this.y = y; + this.z = z; +}; + +_vec3.prototype.toJSON = function toJSON () { + _tmp$1[0] = this.x; + _tmp$1[1] = this.y; + _tmp$1[2] = this.z; + + return _tmp$1; +}; + +/** + * @class 3 Dimensional Vector + * @name vec3 + */ +var vec3 = {}; + +/** + * Creates a new, empty vec3 + * + * @returns {vec3} a new 3D vector + */ +vec3.create = function () { + return new _vec3(0, 0, 0); +}; + +/** + * Creates a new vec3 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} a new 3D vector + */ +vec3.new = function (x, y, z) { + return new _vec3(x, y, z); +}; + +/** + * Creates a new vec3 initialized with values from an existing vector + * + * @param {vec3} a vector to clone + * @returns {vec3} a new 3D vector + */ +vec3.clone = function (a) { + return new _vec3(a.x, a.y, a.z); +}; + +/** + * Copy the values from one vec3 to another + * + * @param {vec3} out the receiving vector + * @param {vec3} a the source vector + * @returns {vec3} out + */ +vec3.copy = function (out, a) { + out.x = a.x; + out.y = a.y; + out.z = a.z; + return out; +}; + +/** + * Set the components of a vec3 to the given values + * + * @param {vec3} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} out + */ +vec3.set = function (out, x, y, z) { + out.x = x; + out.y = y; + out.z = z; + return out; +}; + +/** + * Adds two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.add = function (out, a, b) { + out.x = a.x + b.x; + out.y = a.y + b.y; + out.z = a.z + b.z; + return out; +}; + +/** + * Subtracts vector b from vector a + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.subtract = function (out, a, b) { + out.x = a.x - b.x; + out.y = a.y - b.y; + out.z = a.z - b.z; + return out; +}; + +/** + * Alias for {@link vec3.subtract} + * @function + */ +vec3.sub = vec3.subtract; + +/** + * Multiplies two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.multiply = function (out, a, b) { + out.x = a.x * b.x; + out.y = a.y * b.y; + out.z = a.z * b.z; + return out; +}; + +/** + * Alias for {@link vec3.multiply} + * @function + */ +vec3.mul = vec3.multiply; + +/** + * Divides two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.divide = function (out, a, b) { + out.x = a.x / b.x; + out.y = a.y / b.y; + out.z = a.z / b.z; + return out; +}; + +/** + * Alias for {@link vec3.divide} + * @function + */ +vec3.div = vec3.divide; + +/** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to ceil + * @returns {vec3} out + */ +vec3.ceil = function (out, a) { + out.x = Math.ceil(a.x); + out.y = Math.ceil(a.y); + out.z = Math.ceil(a.z); + return out; +}; + +/** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to floor + * @returns {vec3} out + */ +vec3.floor = function (out, a) { + out.x = Math.floor(a.x); + out.y = Math.floor(a.y); + out.z = Math.floor(a.z); + return out; +}; + +/** + * Returns the minimum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.min = function (out, a, b) { + out.x = Math.min(a.x, b.x); + out.y = Math.min(a.y, b.y); + out.z = Math.min(a.z, b.z); + return out; +}; + +/** + * Returns the maximum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.max = function (out, a, b) { + out.x = Math.max(a.x, b.x); + out.y = Math.max(a.y, b.y); + out.z = Math.max(a.z, b.z); + return out; +}; + +/** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to round + * @returns {vec3} out + */ +vec3.round = function (out, a) { + out.x = Math.round(a.x); + out.y = Math.round(a.y); + out.z = Math.round(a.z); + return out; +}; + +/** + * Scales a vec3 by a scalar number + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec3} out + */ +vec3.scale = function (out, a, b) { + out.x = a.x * b; + out.y = a.y * b; + out.z = a.z * b; + return out; +}; + +/** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec3} out + */ +vec3.scaleAndAdd = function (out, a, b, scale) { + out.x = a.x + (b.x * scale); + out.y = a.y + (b.y * scale); + out.z = a.z + (b.z * scale); + return out; +}; + +/** + * Calculates the euclidian distance between two vec3's + * + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {Number} distance between a and b + */ +vec3.distance = function (a, b) { + var x = b.x - a.x, + y = b.y - a.y, + z = b.z - a.z; + return Math.sqrt(x * x + y * y + z * z); +}; + +/** + * Alias for {@link vec3.distance} + * @function + */ +vec3.dist = vec3.distance; + +/** + * Calculates the squared euclidian distance between two vec3's + * + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {Number} squared distance between a and b + */ +vec3.squaredDistance = function (a, b) { + var x = b.x - a.x, y = b.y - a.y, z = b.z - a.z; - return Math.sqrt(x * x + y * y + z * z); - }; - - /** - * Alias for {@link vec3.distance} - * @function - */ - vec3.dist = vec3.distance; - - /** - * Calculates the squared euclidian distance between two vec3's - * - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @returns {Number} squared distance between a and b - */ - vec3.squaredDistance = function (a, b) { - var x = b.x - a.x, - y = b.y - a.y, - z = b.z - a.z; - return x * x + y * y + z * z; - }; - - /** - * Alias for {@link vec3.squaredDistance} - * @function - */ - vec3.sqrDist = vec3.squaredDistance; - - /** - * Calculates the length of a vec3 - * - * @param {vec3} a vector to calculate length of - * @returns {Number} length of a - */ - vec3.length = function (a) { - var x = a.x, - y = a.y, - z = a.z; - return Math.sqrt(x * x + y * y + z * z); - }; - - /** - * Alias for {@link vec3.length} - * @function - */ - vec3.len = vec3.length; - - /** - * Calculates the squared length of a vec3 - * - * @param {vec3} a vector to calculate squared length of - * @returns {Number} squared length of a - */ - vec3.squaredLength = function (a) { - var x = a.x, - y = a.y, - z = a.z; - return x * x + y * y + z * z; - }; - - /** - * Alias for {@link vec3.squaredLength} - * @function - */ - vec3.sqrLen = vec3.squaredLength; - - /** - * Negates the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to negate - * @returns {vec3} out - */ - vec3.negate = function (out, a) { - out.x = -a.x; - out.y = -a.y; - out.z = -a.z; - return out; - }; - - /** - * Returns the inverse of the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to invert - * @returns {vec3} out - */ - vec3.inverse = function (out, a) { - out.x = 1.0 / a.x; - out.y = 1.0 / a.y; - out.z = 1.0 / a.z; - return out; - }; - - /** - * Returns the inverse of the components of a vec3 safely - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to invert - * @returns {vec3} out - */ - vec3.inverseSafe = function (out, a) { - var x = a.x, - y = a.y, - z = a.z; - - if (Math.abs(x) < EPSILON) { - out.x = 0; + return x * x + y * y + z * z; +}; + +/** + * Alias for {@link vec3.squaredDistance} + * @function + */ +vec3.sqrDist = vec3.squaredDistance; + +/** + * Calculates the length of a vec3 + * + * @param {vec3} a vector to calculate length of + * @returns {Number} length of a + */ +vec3.length = function (a) { + var x = a.x, + y = a.y, + z = a.z; + return Math.sqrt(x * x + y * y + z * z); +}; + +/** + * Alias for {@link vec3.length} + * @function + */ +vec3.len = vec3.length; + +/** + * Calculates the squared length of a vec3 + * + * @param {vec3} a vector to calculate squared length of + * @returns {Number} squared length of a + */ +vec3.squaredLength = function (a) { + var x = a.x, + y = a.y, + z = a.z; + return x * x + y * y + z * z; +}; + +/** + * Alias for {@link vec3.squaredLength} + * @function + */ +vec3.sqrLen = vec3.squaredLength; + +/** + * Negates the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to negate + * @returns {vec3} out + */ +vec3.negate = function (out, a) { + out.x = -a.x; + out.y = -a.y; + out.z = -a.z; + return out; +}; + +/** + * Returns the inverse of the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to invert + * @returns {vec3} out + */ +vec3.inverse = function (out, a) { + out.x = 1.0 / a.x; + out.y = 1.0 / a.y; + out.z = 1.0 / a.z; + return out; +}; + +/** + * Returns the inverse of the components of a vec3 safely + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to invert + * @returns {vec3} out + */ +vec3.inverseSafe = function (out, a) { + var x = a.x, + y = a.y, + z = a.z; + + if (Math.abs(x) < EPSILON) { + out.x = 0; + } else { + out.x = 1.0 / x; + } + + if (Math.abs(y) < EPSILON) { + out.y = 0; + } else { + out.y = 1.0 / y; + } + + if (Math.abs(z) < EPSILON) { + out.z = 0; + } else { + out.z = 1.0 / z; + } + + return out; +}; + +/** + * Normalize a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to normalize + * @returns {vec3} out + */ +vec3.normalize = function (out, a) { + var x = a.x, + y = a.y, + z = a.z; + + var len = x * x + y * y + z * z; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out.x = x * len; + out.y = y * len; + out.z = z * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec3's + * + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {Number} dot product of a and b + */ +vec3.dot = function (a, b) { + return a.x * b.x + a.y * b.y + a.z * b.z; +}; + +/** + * Computes the cross product of two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.cross = function (out, a, b) { + var ax = a.x, ay = a.y, az = a.z, + bx = b.x, by = b.y, bz = b.z; + + out.x = ay * bz - az * by; + out.y = az * bx - ax * bz; + out.z = ax * by - ay * bx; + return out; +}; + +/** + * Performs a linear interpolation between two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {vec3} out + */ +vec3.lerp = function (out, a, b, t) { + var ax = a.x, + ay = a.y, + az = a.z; + out.x = ax + t * (b.x - ax); + out.y = ay + t * (b.y - ay); + out.z = az + t * (b.z - az); + return out; +}; + +/** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {Number} t interpolation amount between the two inputs + * @returns {vec3} out + */ +vec3.hermite = function (out, a, b, c, d, t) { + var factorTimes2 = t * t, + factor1 = factorTimes2 * (2 * t - 3) + 1, + factor2 = factorTimes2 * (t - 2) + t, + factor3 = factorTimes2 * (t - 1), + factor4 = factorTimes2 * (3 - 2 * t); + + out.x = a.x * factor1 + b.x * factor2 + c.x * factor3 + d.x * factor4; + out.y = a.y * factor1 + b.y * factor2 + c.y * factor3 + d.y * factor4; + out.z = a.z * factor1 + b.z * factor2 + c.z * factor3 + d.z * factor4; + + return out; +}; + +/** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {Number} t interpolation amount between the two inputs + * @returns {vec3} out + */ +vec3.bezier = function (out, a, b, c, d, t) { + var inverseFactor = 1 - t, + inverseFactorTimesTwo = inverseFactor * inverseFactor, + factorTimes2 = t * t, + factor1 = inverseFactorTimesTwo * inverseFactor, + factor2 = 3 * t * inverseFactorTimesTwo, + factor3 = 3 * factorTimes2 * inverseFactor, + factor4 = factorTimes2 * t; + + out.x = a.x * factor1 + b.x * factor2 + c.x * factor3 + d.x * factor4; + out.y = a.y * factor1 + b.y * factor2 + c.y * factor3 + d.y * factor4; + out.z = a.z * factor1 + b.z * factor2 + c.z * factor3 + d.z * factor4; + + return out; +}; + +/** + * Generates a random vector with the given scale + * + * @param {vec3} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec3} out + */ +vec3.random = function (out, scale) { + scale = scale || 1.0; + + var r = random() * 2.0 * Math.PI; + var z = (random() * 2.0) - 1.0; + var zScale = Math.sqrt(1.0 - z * z) * scale; + + out.x = Math.cos(r) * zScale; + out.y = Math.sin(r) * zScale; + out.z = z * scale; + return out; +}; + +/** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to transform + * @param {mat4} m matrix to transform with + * @returns {vec3} out + */ +vec3.transformMat4 = function (out, a, m) { + var x = a.x, y = a.y, z = a.z, + w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15; + w = w || 1.0; + out.x = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) / w; + out.y = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) / w; + out.z = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) / w; + return out; +}; + +/** + * Transforms the vec3 with a mat3. + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to transform + * @param {mat4} m the 3x3 matrix to transform with + * @returns {vec3} out + */ +vec3.transformMat3 = function (out, a, m) { + var x = a.x, y = a.y, z = a.z; + out.x = x * m.m00 + y * m.m03 + z * m.m06; + out.y = x * m.m01 + y * m.m04 + z * m.m07; + out.z = x * m.m02 + y * m.m05 + z * m.m08; + return out; +}; + +/** + * Transforms the vec3 with a quat + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to transform + * @param {quat} q quaternion to transform with + * @returns {vec3} out + */ +vec3.transformQuat = function (out, a, q) { + // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations + + var x = a.x, y = a.y, z = a.z; + var qx = q.x, qy = q.y, qz = q.z, qw = q.w; + + // calculate quat * vec + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = -qx * x - qy * y - qz * z; + + // calculate result * inverse quat + out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; + out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; + out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; + return out; +}; + +/** + * Rotate a 3D vector around the x-axis + * @param {vec3} out The receiving vec3 + * @param {vec3} a The vec3 point to rotate + * @param {vec3} b The origin of the rotation + * @param {Number} c The angle of rotation + * @returns {vec3} out + */ +vec3.rotateX = function (out, a, b, c) { + var p = [], r = []; + // Translate point to the origin + p.x = a.x - b.x; + p.y = a.y - b.y; + p.z = a.z - b.z; + + //perform rotation + r.x = p.x; + r.y = p.y * Math.cos(c) - p.z * Math.sin(c); + r.z = p.y * Math.sin(c) + p.z * Math.cos(c); + + //translate to correct position + out.x = r.x + b.x; + out.y = r.y + b.y; + out.z = r.z + b.z; + + return out; +}; + +/** + * Rotate a 3D vector around the y-axis + * @param {vec3} out The receiving vec3 + * @param {vec3} a The vec3 point to rotate + * @param {vec3} b The origin of the rotation + * @param {Number} c The angle of rotation + * @returns {vec3} out + */ +vec3.rotateY = function (out, a, b, c) { + var p = [], r = []; + //Translate point to the origin + p.x = a.x - b.x; + p.y = a.y - b.y; + p.z = a.z - b.z; + + //perform rotation + r.x = p.z * Math.sin(c) + p.x * Math.cos(c); + r.y = p.y; + r.z = p.z * Math.cos(c) - p.x * Math.sin(c); + + //translate to correct position + out.x = r.x + b.x; + out.y = r.y + b.y; + out.z = r.z + b.z; + + return out; +}; + +/** + * Rotate a 3D vector around the z-axis + * @param {vec3} out The receiving vec3 + * @param {vec3} a The vec3 point to rotate + * @param {vec3} b The origin of the rotation + * @param {Number} c The angle of rotation + * @returns {vec3} out + */ +vec3.rotateZ = function (out, a, b, c) { + var p = [], r = []; + //Translate point to the origin + p.x = a.x - b.x; + p.y = a.y - b.y; + p.z = a.z - b.z; + + //perform rotation + r.x = p.x * Math.cos(c) - p.y * Math.sin(c); + r.y = p.x * Math.sin(c) + p.y * Math.cos(c); + r.z = p.z; + + //translate to correct position + out.x = r.x + b.x; + out.y = r.y + b.y; + out.z = r.z + b.z; + + return out; +}; + +/** + * Perform some operation over an array of vec3s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ +vec3.forEach = (function () { + var vec = vec3.create(); + + return function (a, stride, offset, count, fn, arg) { + var i, l; + if (!stride) { + stride = 3; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min((count * stride) + offset, a.length); } else { - out.x = 1.0 / x; + l = a.length; } - - if (Math.abs(y) < EPSILON) { - out.y = 0; - } else { - out.y = 1.0 / y; + + for (i = offset; i < l; i += stride) { + vec.x = a[i]; vec.y = a[i + 1]; vec.z = a[i + 2]; + fn(vec, vec, arg); + a[i] = vec.x; a[i + 1] = vec.y; a[i + 2] = vec.z; } - - if (Math.abs(z) < EPSILON) { - out.z = 0; - } else { - out.z = 1.0 / z; + + return a; + }; +})(); + +/** + * Get the angle between two 3D vectors + * @param {vec3} a The first operand + * @param {vec3} b The second operand + * @returns {Number} The angle in radians + */ +vec3.angle = (function () { + var tempA = vec3.create(); + var tempB = vec3.create(); + + return function (a, b) { + vec3.copy(tempA, a); + vec3.copy(tempB, b); + + vec3.normalize(tempA, tempA); + vec3.normalize(tempB, tempB); + + var cosine = vec3.dot(tempA, tempB); + + if (cosine > 1.0) { + return 0; } - - return out; - }; - - /** - * Normalize a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to normalize - * @returns {vec3} out - */ - vec3.normalize = function (out, a) { - var x = a.x, - y = a.y, - z = a.z; - - var len = x * x + y * y + z * z; - if (len > 0) { - //TODO: evaluate use of glm_invsqrt here? - len = 1 / Math.sqrt(len); - out.x = x * len; - out.y = y * len; - out.z = z * len; + + if (cosine < -1.0) { + return Math.PI; } - return out; + + return Math.acos(cosine); }; - - /** - * Calculates the dot product of two vec3's - * - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @returns {Number} dot product of a and b - */ - vec3.dot = function (a, b) { - return a.x * b.x + a.y * b.y + a.z * b.z; - }; - - /** - * Computes the cross product of two vec3's - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @returns {vec3} out - */ - vec3.cross = function (out, a, b) { - var ax = a.x, ay = a.y, az = a.z, - bx = b.x, by = b.y, bz = b.z; - - out.x = ay * bz - az * by; - out.y = az * bx - ax * bz; - out.z = ax * by - ay * bx; - return out; - }; - - /** - * Performs a linear interpolation between two vec3's - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {Number} t interpolation amount between the two inputs - * @returns {vec3} out - */ - vec3.lerp = function (out, a, b, t) { - var ax = a.x, - ay = a.y, - az = a.z; - out.x = ax + t * (b.x - ax); - out.y = ay + t * (b.y - ay); - out.z = az + t * (b.z - az); - return out; - }; - - /** - * Performs a hermite interpolation with two control points - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {vec3} c the third operand - * @param {vec3} d the fourth operand - * @param {Number} t interpolation amount between the two inputs - * @returns {vec3} out - */ - vec3.hermite = function (out, a, b, c, d, t) { - var factorTimes2 = t * t, - factor1 = factorTimes2 * (2 * t - 3) + 1, - factor2 = factorTimes2 * (t - 2) + t, - factor3 = factorTimes2 * (t - 1), - factor4 = factorTimes2 * (3 - 2 * t); - - out.x = a.x * factor1 + b.x * factor2 + c.x * factor3 + d.x * factor4; - out.y = a.y * factor1 + b.y * factor2 + c.y * factor3 + d.y * factor4; - out.z = a.z * factor1 + b.z * factor2 + c.z * factor3 + d.z * factor4; - - return out; - }; - - /** - * Performs a bezier interpolation with two control points - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {vec3} c the third operand - * @param {vec3} d the fourth operand - * @param {Number} t interpolation amount between the two inputs - * @returns {vec3} out - */ - vec3.bezier = function (out, a, b, c, d, t) { - var inverseFactor = 1 - t, - inverseFactorTimesTwo = inverseFactor * inverseFactor, - factorTimes2 = t * t, - factor1 = inverseFactorTimesTwo * inverseFactor, - factor2 = 3 * t * inverseFactorTimesTwo, - factor3 = 3 * factorTimes2 * inverseFactor, - factor4 = factorTimes2 * t; - - out.x = a.x * factor1 + b.x * factor2 + c.x * factor3 + d.x * factor4; - out.y = a.y * factor1 + b.y * factor2 + c.y * factor3 + d.y * factor4; - out.z = a.z * factor1 + b.z * factor2 + c.z * factor3 + d.z * factor4; - - return out; - }; - - /** - * Generates a random vector with the given scale - * - * @param {vec3} out the receiving vector - * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned - * @returns {vec3} out - */ - vec3.random = function (out, scale) { - scale = scale || 1.0; - - var r = random() * 2.0 * Math.PI; - var z = (random() * 2.0) - 1.0; - var zScale = Math.sqrt(1.0 - z * z) * scale; - - out.x = Math.cos(r) * zScale; - out.y = Math.sin(r) * zScale; - out.z = z * scale; - return out; - }; - - /** - * Transforms the vec3 with a mat4. - * 4th vector component is implicitly '1' - * - * @param {vec3} out the receiving vector - * @param {vec3} a the vector to transform - * @param {mat4} m matrix to transform with - * @returns {vec3} out - */ - vec3.transformMat4 = function (out, a, m) { - var x = a.x, y = a.y, z = a.z, - w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15; - w = w || 1.0; - out.x = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) / w; - out.y = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) / w; - out.z = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) / w; - return out; - }; - - /** - * Transforms the vec3 with a mat3. - * - * @param {vec3} out the receiving vector - * @param {vec3} a the vector to transform - * @param {mat4} m the 3x3 matrix to transform with - * @returns {vec3} out - */ - vec3.transformMat3 = function (out, a, m) { - var x = a.x, y = a.y, z = a.z; - out.x = x * m.m00 + y * m.m03 + z * m.m06; - out.y = x * m.m01 + y * m.m04 + z * m.m07; - out.z = x * m.m02 + y * m.m05 + z * m.m08; - return out; - }; - - /** - * Transforms the vec3 with a quat - * - * @param {vec3} out the receiving vector - * @param {vec3} a the vector to transform - * @param {quat} q quaternion to transform with - * @returns {vec3} out - */ - vec3.transformQuat = function (out, a, q) { - // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations - - var x = a.x, y = a.y, z = a.z; - var qx = q.x, qy = q.y, qz = q.z, qw = q.w; - - // calculate quat * vec - var ix = qw * x + qy * z - qz * y; - var iy = qw * y + qz * x - qx * z; - var iz = qw * z + qx * y - qy * x; - var iw = -qx * x - qy * y - qz * z; - - // calculate result * inverse quat - out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; - out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; - out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; - return out; - }; - - /** - * Rotate a 3D vector around the x-axis - * @param {vec3} out The receiving vec3 - * @param {vec3} a The vec3 point to rotate - * @param {vec3} b The origin of the rotation - * @param {Number} c The angle of rotation - * @returns {vec3} out - */ - vec3.rotateX = function (out, a, b, c) { - var p = [], r = []; - // Translate point to the origin - p.x = a.x - b.x; - p.y = a.y - b.y; - p.z = a.z - b.z; - - //perform rotation - r.x = p.x; - r.y = p.y * Math.cos(c) - p.z * Math.sin(c); - r.z = p.y * Math.sin(c) + p.z * Math.cos(c); - - //translate to correct position - out.x = r.x + b.x; - out.y = r.y + b.y; - out.z = r.z + b.z; - - return out; - }; - - /** - * Rotate a 3D vector around the y-axis - * @param {vec3} out The receiving vec3 - * @param {vec3} a The vec3 point to rotate - * @param {vec3} b The origin of the rotation - * @param {Number} c The angle of rotation - * @returns {vec3} out - */ - vec3.rotateY = function (out, a, b, c) { - var p = [], r = []; - //Translate point to the origin - p.x = a.x - b.x; - p.y = a.y - b.y; - p.z = a.z - b.z; - - //perform rotation - r.x = p.z * Math.sin(c) + p.x * Math.cos(c); - r.y = p.y; - r.z = p.z * Math.cos(c) - p.x * Math.sin(c); - - //translate to correct position - out.x = r.x + b.x; - out.y = r.y + b.y; - out.z = r.z + b.z; - - return out; - }; - - /** - * Rotate a 3D vector around the z-axis - * @param {vec3} out The receiving vec3 - * @param {vec3} a The vec3 point to rotate - * @param {vec3} b The origin of the rotation - * @param {Number} c The angle of rotation - * @returns {vec3} out - */ - vec3.rotateZ = function (out, a, b, c) { - var p = [], r = []; - //Translate point to the origin - p.x = a.x - b.x; - p.y = a.y - b.y; - p.z = a.z - b.z; - - //perform rotation - r.x = p.x * Math.cos(c) - p.y * Math.sin(c); - r.y = p.x * Math.sin(c) + p.y * Math.cos(c); - r.z = p.z; - - //translate to correct position - out.x = r.x + b.x; - out.y = r.y + b.y; - out.z = r.z + b.z; - - return out; - }; - - /** - * Perform some operation over an array of vec3s. - * - * @param {Array} a the array of vectors to iterate over - * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed - * @param {Number} offset Number of elements to skip at the beginning of the array - * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array - * @param {Function} fn Function to call for each vector in the array - * @param {Object} [arg] additional argument to pass to fn - * @returns {Array} a - * @function - */ - vec3.forEach = (function () { - var vec = vec3.create(); - - return function (a, stride, offset, count, fn, arg) { - var i, l; - if (!stride) { - stride = 3; - } - - if (!offset) { - offset = 0; - } - - if (count) { - l = Math.min((count * stride) + offset, a.length); - } else { - l = a.length; - } - - for (i = offset; i < l; i += stride) { - vec.x = a[i]; vec.y = a[i + 1]; vec.z = a[i + 2]; - fn(vec, vec, arg); - a[i] = vec.x; a[i + 1] = vec.y; a[i + 2] = vec.z; - } - - return a; - }; - })(); - - /** - * Get the angle between two 3D vectors - * @param {vec3} a The first operand - * @param {vec3} b The second operand - * @returns {Number} The angle in radians - */ - vec3.angle = (function () { - var tempA = vec3.create(); - var tempB = vec3.create(); - - return function (a, b) { - vec3.copy(tempA, a); - vec3.copy(tempB, b); - - vec3.normalize(tempA, tempA); - vec3.normalize(tempB, tempB); - - var cosine = vec3.dot(tempA, tempB); - - if (cosine > 1.0) { - return 0; - } - - if (cosine < -1.0) { - return Math.PI; - } - - return Math.acos(cosine); - }; - })(); - - /** - * Returns a string representation of a vector - * - * @param {vec3} a vector to represent as a string - * @returns {String} string representation of the vector - */ - vec3.str = function (a) { - return ("vec3(" + (a.x) + ", " + (a.y) + ", " + (a.z) + ")"); - }; - - /** - * Returns typed array - * - * @param {array} out - * @param {vec3} v - * @returns {array} - */ - vec3.array = function (out, v) { - out[0] = v.x; - out[1] = v.y; - out[2] = v.z; - - return out; - }; - - /** - * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) - * - * @param {vec3} a The first vector. - * @param {vec3} b The second vector. - * @returns {Boolean} True if the vectors are equal, false otherwise. - */ - vec3.exactEquals = function (a, b) { - return a.x === b.x && a.y === b.y && a.z === b.z; - }; - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec3} a The first vector. - * @param {vec3} b The second vector. - * @returns {Boolean} True if the vectors are equal, false otherwise. - */ - vec3.equals = function (a, b) { - var a0 = a.x, a1 = a.y, a2 = a.z; - var b0 = b.x, b1 = b.y, b2 = b.z; - return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && - Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && - Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2))); - }; - - var _tmp$2 = new Array(4); - - var _vec4 = function _vec4(x, y, z, w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - }; - - _vec4.prototype.toJSON = function toJSON () { - _tmp$2[0] = this.x; - _tmp$2[1] = this.y; - _tmp$2[2] = this.z; - _tmp$2[3] = this.w; - - return _tmp$2; - }; - - /** - * @class 4 Dimensional Vector - * @name vec4 - */ - var vec4 = {}; - - /** - * Creates a new, empty vec4 - * - * @returns {vec4} a new 4D vector - */ - vec4.create = function () { - return new _vec4(0, 0, 0, 0); - }; - - /** - * Creates a new vec4 initialized with the given values - * - * @param {Number} x X component - * @param {Number} y Y component - * @param {Number} z Z component - * @param {Number} w W component - * @returns {vec4} a new 4D vector - */ - vec4.new = function (x, y, z, w) { - return new _vec4(x, y, z, w); - }; - - /** - * Creates a new vec4 initialized with values from an existing vector - * - * @param {vec4} a vector to clone - * @returns {vec4} a new 4D vector - */ - vec4.clone = function (a) { - return new _vec4(a.x, a.y, a.z, a.w); - }; - - /** - * Copy the values from one vec4 to another - * - * @param {vec4} out the receiving vector - * @param {vec4} a the source vector - * @returns {vec4} out - */ - vec4.copy = function (out, a) { - out.x = a.x; - out.y = a.y; - out.z = a.z; - out.w = a.w; - return out; - }; - - /** - * Set the components of a vec4 to the given values - * - * @param {vec4} out the receiving vector - * @param {Number} x X component - * @param {Number} y Y component - * @param {Number} z Z component - * @param {Number} w W component - * @returns {vec4} out - */ - vec4.set = function (out, x, y, z, w) { - out.x = x; - out.y = y; - out.z = z; - out.w = w; - return out; - }; - - /** - * Adds two vec4's - * - * @param {vec4} out the receiving vector - * @param {vec4} a the first operand - * @param {vec4} b the second operand - * @returns {vec4} out - */ - vec4.add = function (out, a, b) { - out.x = a.x + b.x; - out.y = a.y + b.y; - out.z = a.z + b.z; - out.w = a.w + b.w; - return out; - }; - - /** - * Subtracts vector b from vector a - * - * @param {vec4} out the receiving vector - * @param {vec4} a the first operand - * @param {vec4} b the second operand - * @returns {vec4} out - */ - vec4.subtract = function (out, a, b) { - out.x = a.x - b.x; - out.y = a.y - b.y; - out.z = a.z - b.z; - out.w = a.w - b.w; - return out; - }; - - /** - * Alias for {@link vec4.subtract} - * @function - */ - vec4.sub = vec4.subtract; - - /** - * Multiplies two vec4's - * - * @param {vec4} out the receiving vector - * @param {vec4} a the first operand - * @param {vec4} b the second operand - * @returns {vec4} out - */ - vec4.multiply = function (out, a, b) { - out.x = a.x * b.x; - out.y = a.y * b.y; - out.z = a.z * b.z; - out.w = a.w * b.w; - return out; - }; - - /** - * Alias for {@link vec4.multiply} - * @function - */ - vec4.mul = vec4.multiply; - - /** - * Divides two vec4's - * - * @param {vec4} out the receiving vector - * @param {vec4} a the first operand - * @param {vec4} b the second operand - * @returns {vec4} out - */ - vec4.divide = function (out, a, b) { - out.x = a.x / b.x; - out.y = a.y / b.y; - out.z = a.z / b.z; - out.w = a.w / b.w; - return out; - }; - - /** - * Alias for {@link vec4.divide} - * @function - */ - vec4.div = vec4.divide; - - /** - * Math.ceil the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to ceil - * @returns {vec4} out - */ - vec4.ceil = function (out, a) { - out.x = Math.ceil(a.x); - out.y = Math.ceil(a.y); - out.z = Math.ceil(a.z); - out.w = Math.ceil(a.w); - return out; - }; - - /** - * Math.floor the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to floor - * @returns {vec4} out - */ - vec4.floor = function (out, a) { - out.x = Math.floor(a.x); - out.y = Math.floor(a.y); - out.z = Math.floor(a.z); - out.w = Math.floor(a.w); - return out; - }; - - /** - * Returns the minimum of two vec4's - * - * @param {vec4} out the receiving vector - * @param {vec4} a the first operand - * @param {vec4} b the second operand - * @returns {vec4} out - */ - vec4.min = function (out, a, b) { - out.x = Math.min(a.x, b.x); - out.y = Math.min(a.y, b.y); - out.z = Math.min(a.z, b.z); - out.w = Math.min(a.w, b.w); - return out; - }; - - /** - * Returns the maximum of two vec4's - * - * @param {vec4} out the receiving vector - * @param {vec4} a the first operand - * @param {vec4} b the second operand - * @returns {vec4} out - */ - vec4.max = function (out, a, b) { - out.x = Math.max(a.x, b.x); - out.y = Math.max(a.y, b.y); - out.z = Math.max(a.z, b.z); - out.w = Math.max(a.w, b.w); - return out; - }; - - /** - * Math.round the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to round - * @returns {vec4} out - */ - vec4.round = function (out, a) { - out.x = Math.round(a.x); - out.y = Math.round(a.y); - out.z = Math.round(a.z); - out.w = Math.round(a.w); - return out; - }; - - /** - * Scales a vec4 by a scalar number - * - * @param {vec4} out the receiving vector - * @param {vec4} a the vector to scale - * @param {Number} b amount to scale the vector by - * @returns {vec4} out - */ - vec4.scale = function (out, a, b) { - out.x = a.x * b; - out.y = a.y * b; - out.z = a.z * b; - out.w = a.w * b; - return out; - }; - - /** - * Adds two vec4's after scaling the second operand by a scalar value - * - * @param {vec4} out the receiving vector - * @param {vec4} a the first operand - * @param {vec4} b the second operand - * @param {Number} scale the amount to scale b by before adding - * @returns {vec4} out - */ - vec4.scaleAndAdd = function (out, a, b, scale) { - out.x = a.x + (b.x * scale); - out.y = a.y + (b.y * scale); - out.z = a.z + (b.z * scale); - out.w = a.w + (b.w * scale); - return out; - }; - - /** - * Calculates the euclidian distance between two vec4's - * - * @param {vec4} a the first operand - * @param {vec4} b the second operand - * @returns {Number} distance between a and b - */ - vec4.distance = function (a, b) { - var x = b.x - a.x, +})(); + +/** + * Returns a string representation of a vector + * + * @param {vec3} a vector to represent as a string + * @returns {String} string representation of the vector + */ +vec3.str = function (a) { + return ("vec3(" + (a.x) + ", " + (a.y) + ", " + (a.z) + ")"); +}; + +/** + * Returns typed array + * + * @param {array} out + * @param {vec3} v + * @returns {array} + */ +vec3.array = function (out, v) { + out[0] = v.x; + out[1] = v.y; + out[2] = v.z; + + return out; +}; + +/** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ +vec3.exactEquals = function (a, b) { + return a.x === b.x && a.y === b.y && a.z === b.z; +}; + +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ +vec3.equals = function (a, b) { + var a0 = a.x, a1 = a.y, a2 = a.z; + var b0 = b.x, b1 = b.y, b2 = b.z; + return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && + Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && + Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2))); +}; + +var _tmp$2 = new Array(4); + +var _vec4 = function _vec4(x, y, z, w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; +}; + +_vec4.prototype.toJSON = function toJSON () { + _tmp$2[0] = this.x; + _tmp$2[1] = this.y; + _tmp$2[2] = this.z; + _tmp$2[3] = this.w; + + return _tmp$2; +}; + +/** + * @class 4 Dimensional Vector + * @name vec4 + */ +var vec4 = {}; + +/** + * Creates a new, empty vec4 + * + * @returns {vec4} a new 4D vector + */ +vec4.create = function () { + return new _vec4(0, 0, 0, 0); +}; + +/** + * Creates a new vec4 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} a new 4D vector + */ +vec4.new = function (x, y, z, w) { + return new _vec4(x, y, z, w); +}; + +/** + * Creates a new vec4 initialized with values from an existing vector + * + * @param {vec4} a vector to clone + * @returns {vec4} a new 4D vector + */ +vec4.clone = function (a) { + return new _vec4(a.x, a.y, a.z, a.w); +}; + +/** + * Copy the values from one vec4 to another + * + * @param {vec4} out the receiving vector + * @param {vec4} a the source vector + * @returns {vec4} out + */ +vec4.copy = function (out, a) { + out.x = a.x; + out.y = a.y; + out.z = a.z; + out.w = a.w; + return out; +}; + +/** + * Set the components of a vec4 to the given values + * + * @param {vec4} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} out + */ +vec4.set = function (out, x, y, z, w) { + out.x = x; + out.y = y; + out.z = z; + out.w = w; + return out; +}; + +/** + * Adds two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.add = function (out, a, b) { + out.x = a.x + b.x; + out.y = a.y + b.y; + out.z = a.z + b.z; + out.w = a.w + b.w; + return out; +}; + +/** + * Subtracts vector b from vector a + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.subtract = function (out, a, b) { + out.x = a.x - b.x; + out.y = a.y - b.y; + out.z = a.z - b.z; + out.w = a.w - b.w; + return out; +}; + +/** + * Alias for {@link vec4.subtract} + * @function + */ +vec4.sub = vec4.subtract; + +/** + * Multiplies two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.multiply = function (out, a, b) { + out.x = a.x * b.x; + out.y = a.y * b.y; + out.z = a.z * b.z; + out.w = a.w * b.w; + return out; +}; + +/** + * Alias for {@link vec4.multiply} + * @function + */ +vec4.mul = vec4.multiply; + +/** + * Divides two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.divide = function (out, a, b) { + out.x = a.x / b.x; + out.y = a.y / b.y; + out.z = a.z / b.z; + out.w = a.w / b.w; + return out; +}; + +/** + * Alias for {@link vec4.divide} + * @function + */ +vec4.div = vec4.divide; + +/** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to ceil + * @returns {vec4} out + */ +vec4.ceil = function (out, a) { + out.x = Math.ceil(a.x); + out.y = Math.ceil(a.y); + out.z = Math.ceil(a.z); + out.w = Math.ceil(a.w); + return out; +}; + +/** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to floor + * @returns {vec4} out + */ +vec4.floor = function (out, a) { + out.x = Math.floor(a.x); + out.y = Math.floor(a.y); + out.z = Math.floor(a.z); + out.w = Math.floor(a.w); + return out; +}; + +/** + * Returns the minimum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.min = function (out, a, b) { + out.x = Math.min(a.x, b.x); + out.y = Math.min(a.y, b.y); + out.z = Math.min(a.z, b.z); + out.w = Math.min(a.w, b.w); + return out; +}; + +/** + * Returns the maximum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.max = function (out, a, b) { + out.x = Math.max(a.x, b.x); + out.y = Math.max(a.y, b.y); + out.z = Math.max(a.z, b.z); + out.w = Math.max(a.w, b.w); + return out; +}; + +/** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to round + * @returns {vec4} out + */ +vec4.round = function (out, a) { + out.x = Math.round(a.x); + out.y = Math.round(a.y); + out.z = Math.round(a.z); + out.w = Math.round(a.w); + return out; +}; + +/** + * Scales a vec4 by a scalar number + * + * @param {vec4} out the receiving vector + * @param {vec4} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec4} out + */ +vec4.scale = function (out, a, b) { + out.x = a.x * b; + out.y = a.y * b; + out.z = a.z * b; + out.w = a.w * b; + return out; +}; + +/** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec4} out + */ +vec4.scaleAndAdd = function (out, a, b, scale) { + out.x = a.x + (b.x * scale); + out.y = a.y + (b.y * scale); + out.z = a.z + (b.z * scale); + out.w = a.w + (b.w * scale); + return out; +}; + +/** + * Calculates the euclidian distance between two vec4's + * + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {Number} distance between a and b + */ +vec4.distance = function (a, b) { + var x = b.x - a.x, + y = b.y - a.y, + z = b.z - a.z, + w = b.w - a.w; + return Math.sqrt(x * x + y * y + z * z + w * w); +}; + +/** + * Alias for {@link vec4.distance} + * @function + */ +vec4.dist = vec4.distance; + +/** + * Calculates the squared euclidian distance between two vec4's + * + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {Number} squared distance between a and b + */ +vec4.squaredDistance = function (a, b) { + var x = b.x - a.x, y = b.y - a.y, z = b.z - a.z, w = b.w - a.w; - return Math.sqrt(x * x + y * y + z * z + w * w); - }; - - /** - * Alias for {@link vec4.distance} - * @function - */ - vec4.dist = vec4.distance; - - /** - * Calculates the squared euclidian distance between two vec4's - * - * @param {vec4} a the first operand - * @param {vec4} b the second operand - * @returns {Number} squared distance between a and b - */ - vec4.squaredDistance = function (a, b) { - var x = b.x - a.x, - y = b.y - a.y, - z = b.z - a.z, - w = b.w - a.w; - return x * x + y * y + z * z + w * w; - }; - - /** - * Alias for {@link vec4.squaredDistance} - * @function - */ - vec4.sqrDist = vec4.squaredDistance; - - /** - * Calculates the length of a vec4 - * - * @param {vec4} a vector to calculate length of - * @returns {Number} length of a - */ - vec4.length = function (a) { - var x = a.x, - y = a.y, - z = a.z, - w = a.w; - return Math.sqrt(x * x + y * y + z * z + w * w); - }; - - /** - * Alias for {@link vec4.length} - * @function - */ - vec4.len = vec4.length; - - /** - * Calculates the squared length of a vec4 - * - * @param {vec4} a vector to calculate squared length of - * @returns {Number} squared length of a - */ - vec4.squaredLength = function (a) { - var x = a.x, - y = a.y, - z = a.z, - w = a.w; - return x * x + y * y + z * z + w * w; - }; - - /** - * Alias for {@link vec4.squaredLength} - * @function - */ - vec4.sqrLen = vec4.squaredLength; - - /** - * Negates the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to negate - * @returns {vec4} out - */ - vec4.negate = function (out, a) { - out.x = -a.x; - out.y = -a.y; - out.z = -a.z; - out.w = -a.w; - return out; - }; - - /** - * Returns the inverse of the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to invert - * @returns {vec4} out - */ - vec4.inverse = function (out, a) { - out.x = 1.0 / a.x; - out.y = 1.0 / a.y; - out.z = 1.0 / a.z; - out.w = 1.0 / a.w; - return out; - }; - - /** - * Returns the inverse of the components of a vec4 safely - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to invert - * @returns {vec4} out - */ - vec4.inverseSafe = function (out, a) { - var x = a.x, - y = a.y, - z = a.z, - w = a.w; - - if (Math.abs(x) < EPSILON) { - out.x = 0; - } else { - out.x = 1.0 / x; - } - - if (Math.abs(y) < EPSILON) { - out.y = 0; - } else { - out.y = 1.0 / y; - } - - if (Math.abs(z) < EPSILON) { - out.z = 0; - } else { - out.z = 1.0 / z; - } - - if (Math.abs(w) < EPSILON) { - out.w = 0; - } else { - out.w = 1.0 / w; - } - - return out; - }; - - /** - * Normalize a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to normalize - * @returns {vec4} out - */ - vec4.normalize = function (out, a) { - var x = a.x, - y = a.y, - z = a.z, - w = a.w; - var len = x * x + y * y + z * z + w * w; - if (len > 0) { - len = 1 / Math.sqrt(len); - out.x = x * len; - out.y = y * len; - out.z = z * len; - out.w = w * len; - } - return out; - }; - - /** - * Calculates the dot product of two vec4's - * - * @param {vec4} a the first operand - * @param {vec4} b the second operand - * @returns {Number} dot product of a and b - */ - vec4.dot = function (a, b) { - return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; - }; - - /** - * Performs a linear interpolation between two vec4's - * - * @param {vec4} out the receiving vector - * @param {vec4} a the first operand - * @param {vec4} b the second operand - * @param {Number} t interpolation amount between the two inputs - * @returns {vec4} out - */ - vec4.lerp = function (out, a, b, t) { - var ax = a.x, - ay = a.y, - az = a.z, - aw = a.w; - out.x = ax + t * (b.x - ax); - out.y = ay + t * (b.y - ay); - out.z = az + t * (b.z - az); - out.w = aw + t * (b.w - aw); - return out; - }; - - /** - * Generates a random vector with the given scale - * - * @param {vec4} out the receiving vector - * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned - * @returns {vec4} out - */ - vec4.random = function (out, scale) { - scale = scale || 1.0; - - //TODO: This is a pretty awful way of doing this. Find something better. - out.x = random(); - out.y = random(); - out.z = random(); - out.w = random(); - vec4.normalize(out, out); - vec4.scale(out, out, scale); - return out; - }; - - /** - * Transforms the vec4 with a mat4. - * - * @param {vec4} out the receiving vector - * @param {vec4} a the vector to transform - * @param {mat4} m matrix to transform with - * @returns {vec4} out - */ - vec4.transformMat4 = function (out, a, m) { - var x = a.x, y = a.y, z = a.z, w = a.w; - out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12 * w; - out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13 * w; - out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14 * w; - out.w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15 * w; - return out; - }; - - /** - * Transforms the vec4 with a quat - * - * @param {vec4} out the receiving vector - * @param {vec4} a the vector to transform - * @param {quat} q quaternion to transform with - * @returns {vec4} out - */ - vec4.transformQuat = function (out, a, q) { - var x = a.x, y = a.y, z = a.z; - var qx = q.x, qy = q.y, qz = q.z, qw = q.w; - - // calculate quat * vec - var ix = qw * x + qy * z - qz * y; - var iy = qw * y + qz * x - qx * z; - var iz = qw * z + qx * y - qy * x; - var iw = -qx * x - qy * y - qz * z; - - // calculate result * inverse quat - out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; - out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; - out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; - out.w = a.w; - return out; - }; - - /** - * Perform some operation over an array of vec4s. - * - * @param {Array} a the array of vectors to iterate over - * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed - * @param {Number} offset Number of elements to skip at the beginning of the array - * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array - * @param {Function} fn Function to call for each vector in the array - * @param {Object} [arg] additional argument to pass to fn - * @returns {Array} a - * @function - */ - vec4.forEach = (function () { - var vec = vec4.create(); - - return function (a, stride, offset, count, fn, arg) { - var i, l; - if (!stride) { - stride = 4; - } - - if (!offset) { - offset = 0; - } - - if (count) { - l = Math.min((count * stride) + offset, a.length); - } else { - l = a.length; - } - - for (i = offset; i < l; i += stride) { - vec.x = a[i]; vec.y = a[i + 1]; vec.z = a[i + 2]; vec.w = a[i + 3]; - fn(vec, vec, arg); - a[i] = vec.x; a[i + 1] = vec.y; a[i + 2] = vec.z; a[i + 3] = vec.w; - } - - return a; - }; - })(); - - /** - * Returns a string representation of a vector - * - * @param {vec4} a vector to represent as a string - * @returns {String} string representation of the vector - */ - vec4.str = function (a) { - return ("vec4(" + (a.x) + ", " + (a.y) + ", " + (a.z) + ", " + (a.w) + ")"); - }; - - /** - * Returns typed array - * - * @param {array} out - * @param {vec4} v - * @returns {array} - */ - vec4.array = function (out, v) { - out[0] = v.x; - out[1] = v.y; - out[2] = v.z; - out[3] = v.w; - - return out; - }; - - /** - * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) - * - * @param {vec4} a The first vector. - * @param {vec4} b The second vector. - * @returns {Boolean} True if the vectors are equal, false otherwise. - */ - vec4.exactEquals = function (a, b) { - return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w; - }; - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec4} a The first vector. - * @param {vec4} b The second vector. - * @returns {Boolean} True if the vectors are equal, false otherwise. - */ - vec4.equals = function (a, b) { - var a0 = a.x, a1 = a.y, a2 = a.z, a3 = a.w; - var b0 = b.x, b1 = b.y, b2 = b.z, b3 = b.w; - return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && - Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && - Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && - Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3))); - }; - - var _tmp$3 = new Array(9); - - var _mat3 = function _mat3(m00, m01, m02, m03, m04, m05, m06, m07, m08) { - this.m00 = m00; - this.m01 = m01; - this.m02 = m02; - this.m03 = m03; - this.m04 = m04; - this.m05 = m05; - this.m06 = m06; - this.m07 = m07; - this.m08 = m08; - }; - - _mat3.prototype.toJSON = function toJSON () { - _tmp$3[0] = this.m00; - _tmp$3[1] = this.m01; - _tmp$3[2] = this.m02; - _tmp$3[3] = this.m03; - _tmp$3[4] = this.m04; - _tmp$3[5] = this.m05; - _tmp$3[6] = this.m06; - _tmp$3[7] = this.m07; - _tmp$3[8] = this.m08; - - return _tmp$3; - }; - - /** - * @class 3x3 Matrix - * @name mat3 - * - * NOTE: we use column-major matrix for all matrix calculation. - * - * This may lead to some confusion when referencing OpenGL documentation, - * however, which represents out all matricies in column-major format. - * This means that while in code a matrix may be typed out as: - * - * [1, 0, 0, 0, - * 0, 1, 0, 0, - * 0, 0, 1, 0, - * x, y, z, 0] - * - * The same matrix in the [OpenGL documentation](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml) - * is written as: - * - * 1 0 0 x - * 0 1 0 y - * 0 0 1 z - * 0 0 0 0 - * - * Please rest assured, however, that they are the same thing! - * This is not unique to glMatrix, either, as OpenGL developers have long been confused by the - * apparent lack of consistency between the memory layout and the documentation. - */ - var mat3 = {}; - - /** - * Creates a new identity mat3 - * - * @returns {mat3} a new 3x3 matrix - */ - mat3.create = function () { - return new _mat3( - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ); - }; - - /** - * Create a new mat3 with the given values - * - * @param {Number} m00 Component in column 0, row 0 position (index 0) - * @param {Number} m01 Component in column 0, row 1 position (index 1) - * @param {Number} m02 Component in column 0, row 2 position (index 2) - * @param {Number} m10 Component in column 1, row 0 position (index 3) - * @param {Number} m11 Component in column 1, row 1 position (index 4) - * @param {Number} m12 Component in column 1, row 2 position (index 5) - * @param {Number} m20 Component in column 2, row 0 position (index 6) - * @param {Number} m21 Component in column 2, row 1 position (index 7) - * @param {Number} m22 Component in column 2, row 2 position (index 8) - * @returns {mat3} A new mat3 - */ - mat3.new = function (m00, m01, m02, m10, m11, m12, m20, m21, m22) { - return new _mat3( - m00, m01, m02, - m10, m11, m12, - m20, m21, m22 - ); - }; - - /** - * Creates a new mat3 initialized with values from an existing matrix - * - * @param {mat3} a matrix to clone - * @returns {mat3} a new 3x3 matrix - */ - mat3.clone = function (a) { - return new _mat3( - a.m00, a.m01, a.m02, - a.m03, a.m04, a.m05, - a.m06, a.m07, a.m08 - ); - }; - - /** - * Copy the values from one mat3 to another - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the source matrix - * @returns {mat3} out - */ - mat3.copy = function (out, a) { - out.m00 = a.m00; - out.m01 = a.m01; - out.m02 = a.m02; - out.m03 = a.m03; - out.m04 = a.m04; - out.m05 = a.m05; - out.m06 = a.m06; - out.m07 = a.m07; - out.m08 = a.m08; - return out; - }; - - /** - * Set the components of a mat3 to the given values - * - * @param {mat3} out the receiving matrix - * @param {Number} m00 Component in column 0, row 0 position (index 0) - * @param {Number} m01 Component in column 0, row 1 position (index 1) - * @param {Number} m02 Component in column 0, row 2 position (index 2) - * @param {Number} m10 Component in column 1, row 0 position (index 3) - * @param {Number} m11 Component in column 1, row 1 position (index 4) - * @param {Number} m12 Component in column 1, row 2 position (index 5) - * @param {Number} m20 Component in column 2, row 0 position (index 6) - * @param {Number} m21 Component in column 2, row 1 position (index 7) - * @param {Number} m22 Component in column 2, row 2 position (index 8) - * @returns {mat3} out - */ - mat3.set = function (out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { - out.m00 = m00; - out.m01 = m01; - out.m02 = m02; - out.m03 = m10; - out.m04 = m11; - out.m05 = m12; - out.m06 = m20; - out.m07 = m21; - out.m08 = m22; - return out; - }; - - /** - * Set a mat3 to the identity matrix - * - * @param {mat3} out the receiving matrix - * @returns {mat3} out - */ - mat3.identity = function (out) { - out.m00 = 1; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 1; - out.m05 = 0; - out.m06 = 0; - out.m07 = 0; - out.m08 = 1; - return out; - }; - - /** - * Transpose the values of a mat3 - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the source matrix - * @returns {mat3} out - */ - mat3.transpose = function (out, a) { - // If we are transposing ourselves we can skip a few steps but have to cache some values - if (out === a) { - var a01 = a.m01, a02 = a.m02, a12 = a.m05; - out.m01 = a.m03; - out.m02 = a.m06; - out.m03 = a01; - out.m05 = a.m07; - out.m06 = a02; - out.m07 = a12; - } else { - out.m00 = a.m00; - out.m01 = a.m03; - out.m02 = a.m06; - out.m03 = a.m01; - out.m04 = a.m04; - out.m05 = a.m07; - out.m06 = a.m02; - out.m07 = a.m05; - out.m08 = a.m08; - } - - return out; - }; - - /** - * Inverts a mat3 - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the source matrix - * @returns {mat3} out - */ - mat3.invert = function (out, a) { - var a00 = a.m00, a01 = a.m01, a02 = a.m02, - a10 = a.m03, a11 = a.m04, a12 = a.m05, - a20 = a.m06, a21 = a.m07, a22 = a.m08; - - var b01 = a22 * a11 - a12 * a21; - var b11 = -a22 * a10 + a12 * a20; - var b21 = a21 * a10 - a11 * a20; - - // Calculate the determinant - var det = a00 * b01 + a01 * b11 + a02 * b21; - - if (!det) { - return null; - } - det = 1.0 / det; - - out.m00 = b01 * det; - out.m01 = (-a22 * a01 + a02 * a21) * det; - out.m02 = (a12 * a01 - a02 * a11) * det; - out.m03 = b11 * det; - out.m04 = (a22 * a00 - a02 * a20) * det; - out.m05 = (-a12 * a00 + a02 * a10) * det; - out.m06 = b21 * det; - out.m07 = (-a21 * a00 + a01 * a20) * det; - out.m08 = (a11 * a00 - a01 * a10) * det; - return out; - }; - - /** - * Calculates the adjugate of a mat3 - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the source matrix - * @returns {mat3} out - */ - mat3.adjoint = function (out, a) { - var a00 = a.m00, a01 = a.m01, a02 = a.m02, - a10 = a.m03, a11 = a.m04, a12 = a.m05, - a20 = a.m06, a21 = a.m07, a22 = a.m08; - - out.m00 = (a11 * a22 - a12 * a21); - out.m01 = (a02 * a21 - a01 * a22); - out.m02 = (a01 * a12 - a02 * a11); - out.m03 = (a12 * a20 - a10 * a22); - out.m04 = (a00 * a22 - a02 * a20); - out.m05 = (a02 * a10 - a00 * a12); - out.m06 = (a10 * a21 - a11 * a20); - out.m07 = (a01 * a20 - a00 * a21); - out.m08 = (a00 * a11 - a01 * a10); - return out; - }; - - /** - * Calculates the determinant of a mat3 - * - * @param {mat3} a the source matrix - * @returns {Number} determinant of a - */ - mat3.determinant = function (a) { - var a00 = a.m00, a01 = a.m01, a02 = a.m02, - a10 = a.m03, a11 = a.m04, a12 = a.m05, - a20 = a.m06, a21 = a.m07, a22 = a.m08; - - return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); - }; - - /** - * Multiplies two mat3's - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - mat3.multiply = function (out, a, b) { - var a00 = a.m00, a01 = a.m01, a02 = a.m02, - a10 = a.m03, a11 = a.m04, a12 = a.m05, - a20 = a.m06, a21 = a.m07, a22 = a.m08; - - var b00 = b.m00, b01 = b.m01, b02 = b.m02; - var b10 = b.m03, b11 = b.m04, b12 = b.m05; - var b20 = b.m06, b21 = b.m07, b22 = b.m08; - - out.m00 = b00 * a00 + b01 * a10 + b02 * a20; - out.m01 = b00 * a01 + b01 * a11 + b02 * a21; - out.m02 = b00 * a02 + b01 * a12 + b02 * a22; - - out.m03 = b10 * a00 + b11 * a10 + b12 * a20; - out.m04 = b10 * a01 + b11 * a11 + b12 * a21; - out.m05 = b10 * a02 + b11 * a12 + b12 * a22; - - out.m06 = b20 * a00 + b21 * a10 + b22 * a20; - out.m07 = b20 * a01 + b21 * a11 + b22 * a21; - out.m08 = b20 * a02 + b21 * a12 + b22 * a22; - return out; - }; - - /** - * Alias for {@link mat3.multiply} - * @function - */ - mat3.mul = mat3.multiply; - - /** - * Translate a mat3 by the given vector - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the matrix to translate - * @param {vec2} v vector to translate by - * @returns {mat3} out - */ - mat3.translate = function (out, a, v) { - var a00 = a.m00, a01 = a.m01, a02 = a.m02, - a10 = a.m03, a11 = a.m04, a12 = a.m05, - a20 = a.m06, a21 = a.m07, a22 = a.m08; - var x = v.x, y = v.y; - - out.m00 = a00; - out.m01 = a01; - out.m02 = a02; - - out.m03 = a10; - out.m04 = a11; - out.m05 = a12; - - out.m06 = x * a00 + y * a10 + a20; - out.m07 = x * a01 + y * a11 + a21; - out.m08 = x * a02 + y * a12 + a22; - return out; - }; - - /** - * Rotates a mat3 by the given angle - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat3} out - */ - mat3.rotate = function (out, a, rad) { - var a00 = a.m00, a01 = a.m01, a02 = a.m02, - a10 = a.m03, a11 = a.m04, a12 = a.m05, - a20 = a.m06, a21 = a.m07, a22 = a.m08; - - var s = Math.sin(rad); - var c = Math.cos(rad); - - out.m00 = c * a00 + s * a10; - out.m01 = c * a01 + s * a11; - out.m02 = c * a02 + s * a12; - - out.m03 = c * a10 - s * a00; - out.m04 = c * a11 - s * a01; - out.m05 = c * a12 - s * a02; - - out.m06 = a20; - out.m07 = a21; - out.m08 = a22; - return out; - }; - - /** - * Scales the mat3 by the dimensions in the given vec2 - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the matrix to rotate - * @param {vec2} v the vec2 to scale the matrix by - * @returns {mat3} out - **/ - mat3.scale = function (out, a, v) { - var x = v.x, y = v.y; - - out.m00 = x * a.m00; - out.m01 = x * a.m01; - out.m02 = x * a.m02; - - out.m03 = y * a.m03; - out.m04 = y * a.m04; - out.m05 = y * a.m05; - - out.m06 = a.m06; - out.m07 = a.m07; - out.m08 = a.m08; - return out; - }; - - /** - * Copies the upper-left 3x3 values into the given mat3. - * - * @param {mat3} out the receiving 3x3 matrix - * @param {mat4} a the source 4x4 matrix - * @returns {mat3} out - */ - mat3.fromMat4 = function (out, a) { - out.m00 = a.m00; - out.m01 = a.m01; - out.m02 = a.m02; - out.m03 = a.m04; - out.m04 = a.m05; - out.m05 = a.m06; - out.m06 = a.m08; - out.m07 = a.m09; - out.m08 = a.m10; - return out; - }; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.translate(dest, dest, vec); - * - * @param {mat3} out mat3 receiving operation result - * @param {vec2} v Translation vector - * @returns {mat3} out - */ - mat3.fromTranslation = function (out, v) { - out.m00 = 1; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 1; - out.m05 = 0; - out.m06 = v.x; - out.m07 = v.y; - out.m08 = 1; - return out; - }; - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.rotate(dest, dest, rad); - * - * @param {mat3} out mat3 receiving operation result - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat3} out - */ - mat3.fromRotation = function (out, rad) { - var s = Math.sin(rad), c = Math.cos(rad); - - out.m00 = c; - out.m01 = s; - out.m02 = 0; - - out.m03 = -s; - out.m04 = c; - out.m05 = 0; - - out.m06 = 0; - out.m07 = 0; - out.m08 = 1; - return out; - }; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.scale(dest, dest, vec); - * - * @param {mat3} out mat3 receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat3} out - */ - mat3.fromScaling = function (out, v) { - out.m00 = v.x; - out.m01 = 0; - out.m02 = 0; - - out.m03 = 0; - out.m04 = v.y; - out.m05 = 0; - - out.m06 = 0; - out.m07 = 0; - out.m08 = 1; - return out; - }; - - /** - * Copies the values from a mat2d into a mat3 - * - * @param {mat3} out the receiving matrix - * @param {mat2d} a the matrix to copy - * @returns {mat3} out - **/ - mat3.fromMat2d = function (out, a) { - out.m00 = a.m00; - out.m01 = a.m01; - out.m02 = 0; - - out.m03 = a.m02; - out.m04 = a.m03; - out.m05 = 0; - - out.m06 = a.m04; - out.m07 = a.m05; - out.m08 = 1; - return out; - }; - - /** - * Calculates a 3x3 matrix from the given quaternion - * - * @param {mat3} out mat3 receiving operation result - * @param {quat} q Quaternion to create matrix from - * - * @returns {mat3} out - */ - mat3.fromQuat = function (out, q) { - var x = q.x, y = q.y, z = q.z, w = q.w; - var x2 = x + x; - var y2 = y + y; - var z2 = z + z; - - var xx = x * x2; - var yx = y * x2; - var yy = y * y2; - var zx = z * x2; - var zy = z * y2; - var zz = z * z2; - var wx = w * x2; - var wy = w * y2; - var wz = w * z2; - - out.m00 = 1 - yy - zz; - out.m03 = yx - wz; - out.m06 = zx + wy; - - out.m01 = yx + wz; - out.m04 = 1 - xx - zz; - out.m07 = zy - wx; - - out.m02 = zx - wy; - out.m05 = zy + wx; - out.m08 = 1 - xx - yy; - - return out; - }; - - /** - * Calculates a 3x3 matrix from view direction and up direction - * - * @param {mat3} out mat3 receiving operation result - * @param {vec3} view view direction (must be normalized) - * @param {vec3} [up] up direction, default is (0,1,0) (must be normalized) - * - * @returns {mat3} out - */ - mat3.fromViewUp = (function () { - var default_up = vec3.new(0, 1, 0); - var x = vec3.create(); - var y = vec3.create(); - - return function (out, view, up) { - if (vec3.sqrLen(view) < EPSILON * EPSILON) { - mat3.identity(out); - return out; - } - - up = up || default_up; - vec3.cross(x, up, view); - - if (vec3.sqrLen(x) < EPSILON * EPSILON) { - mat3.identity(out); - return out; - } - - vec3.cross(y, view, x); - mat3.set(out, - x.x, x.y, x.z, - y.x, y.y, y.z, - view.x, view.y, view.z - ); - - return out; - }; - })(); - - /** - * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix - * - * @param {mat3} out mat3 receiving operation result - * @param {mat4} a Mat4 to derive the normal matrix from - * - * @returns {mat3} out - */ - mat3.normalFromMat4 = function (out, a) { - var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, - a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, - a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, - a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; - - var b00 = a00 * a11 - a01 * a10; - var b01 = a00 * a12 - a02 * a10; - var b02 = a00 * a13 - a03 * a10; - var b03 = a01 * a12 - a02 * a11; - var b04 = a01 * a13 - a03 * a11; - var b05 = a02 * a13 - a03 * a12; - var b06 = a20 * a31 - a21 * a30; - var b07 = a20 * a32 - a22 * a30; - var b08 = a20 * a33 - a23 * a30; - var b09 = a21 * a32 - a22 * a31; - var b10 = a21 * a33 - a23 * a31; - var b11 = a22 * a33 - a23 * a32; - - // Calculate the determinant - var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - - if (!det) { - return null; - } - det = 1.0 / det; - - out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; - out.m01 = (a12 * b08 - a10 * b11 - a13 * b07) * det; - out.m02 = (a10 * b10 - a11 * b08 + a13 * b06) * det; - - out.m03 = (a02 * b10 - a01 * b11 - a03 * b09) * det; - out.m04 = (a00 * b11 - a02 * b08 + a03 * b07) * det; - out.m05 = (a01 * b08 - a00 * b10 - a03 * b06) * det; - - out.m06 = (a31 * b05 - a32 * b04 + a33 * b03) * det; - out.m07 = (a32 * b02 - a30 * b05 - a33 * b01) * det; - out.m08 = (a30 * b04 - a31 * b02 + a33 * b00) * det; - - return out; - }; - - /** - * Returns a string representation of a mat3 - * - * @param {mat3} a matrix to represent as a string - * @returns {String} string representation of the matrix - */ - mat3.str = function (a) { - return ("mat3(" + (a.m00) + ", " + (a.m01) + ", " + (a.m02) + ", " + (a.m03) + ", " + (a.m04) + ", " + (a.m05) + ", " + (a.m06) + ", " + (a.m07) + ", " + (a.m08) + ")"); - }; - - /** - * Returns typed array - * - * @param {array} out - * @param {mat3} m - * @returns {array} - */ - mat3.array = function (out, m) { - out[0] = m.m00; - out[1] = m.m01; - out[2] = m.m02; - out[3] = m.m03; - out[4] = m.m04; - out[5] = m.m05; - out[6] = m.m06; - out[7] = m.m07; - out[8] = m.m08; - - return out; - }; - - /** - * Returns Frobenius norm of a mat3 - * - * @param {mat3} a the matrix to calculate Frobenius norm of - * @returns {Number} Frobenius norm - */ - mat3.frob = function (a) { - return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + Math.pow(a.m06, 2) + Math.pow(a.m07, 2) + Math.pow(a.m08, 2))); - }; - - /** - * Adds two mat3's - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - mat3.add = function (out, a, b) { - out.m00 = a.m00 + b.m00; - out.m01 = a.m01 + b.m01; - out.m02 = a.m02 + b.m02; - out.m03 = a.m03 + b.m03; - out.m04 = a.m04 + b.m04; - out.m05 = a.m05 + b.m05; - out.m06 = a.m06 + b.m06; - out.m07 = a.m07 + b.m07; - out.m08 = a.m08 + b.m08; - return out; - }; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - mat3.subtract = function (out, a, b) { - out.m00 = a.m00 - b.m00; - out.m01 = a.m01 - b.m01; - out.m02 = a.m02 - b.m02; - out.m03 = a.m03 - b.m03; - out.m04 = a.m04 - b.m04; - out.m05 = a.m05 - b.m05; - out.m06 = a.m06 - b.m06; - out.m07 = a.m07 - b.m07; - out.m08 = a.m08 - b.m08; - return out; - }; - - /** - * Alias for {@link mat3.subtract} - * @function - */ - mat3.sub = mat3.subtract; - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the matrix to scale - * @param {Number} b amount to scale the matrix's elements by - * @returns {mat3} out - */ - mat3.multiplyScalar = function (out, a, b) { - out.m00 = a.m00 * b; - out.m01 = a.m01 * b; - out.m02 = a.m02 * b; - out.m03 = a.m03 * b; - out.m04 = a.m04 * b; - out.m05 = a.m05 * b; - out.m06 = a.m06 * b; - out.m07 = a.m07 * b; - out.m08 = a.m08 * b; - return out; - }; - - /** - * Adds two mat3's after multiplying each element of the second operand by a scalar value. - * - * @param {mat3} out the receiving vector - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @param {Number} scale the amount to scale b's elements by before adding - * @returns {mat3} out - */ - mat3.multiplyScalarAndAdd = function (out, a, b, scale) { - out.m00 = a.m00 + (b.m00 * scale); - out.m01 = a.m01 + (b.m01 * scale); - out.m02 = a.m02 + (b.m02 * scale); - out.m03 = a.m03 + (b.m03 * scale); - out.m04 = a.m04 + (b.m04 * scale); - out.m05 = a.m05 + (b.m05 * scale); - out.m06 = a.m06 + (b.m06 * scale); - out.m07 = a.m07 + (b.m07 * scale); - out.m08 = a.m08 + (b.m08 * scale); - return out; - }; - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat3} a The first matrix. - * @param {mat3} b The second matrix. - * @returns {Boolean} True if the matrices are equal, false otherwise. - */ - mat3.exactEquals = function (a, b) { - return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && - a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && - a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08; - }; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat3} a The first matrix. - * @param {mat3} b The second matrix. - * @returns {Boolean} True if the matrices are equal, false otherwise. - */ - mat3.equals = function (a, b) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, a6 = a.m06, a7 = a.m07, a8 = a.m08; - var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05, b6 = b.m06, b7 = b.m07, b8 = b.m08; - return ( - Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && - Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && - Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && - Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && - Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && - Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && - Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && - Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && - Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) - ); - }; - - var _tmp$4 = new Array(4); - - var _quat = function _quat(x, y, z, w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - }; - - _quat.prototype.toJSON = function toJSON () { - _tmp$4[0] = this.x; - _tmp$4[1] = this.y; - _tmp$4[2] = this.z; - _tmp$4[3] = this.w; - - return _tmp$4; - }; - - /** - * @class Quaternion - * @name quat - */ - var quat = {}; - - /** - * Creates a new identity quat - * - * @returns {quat} a new quaternion - */ - quat.create = function () { - return new _quat(0, 0, 0, 1); - }; - - /** - * Creates a new quat initialized with the given values - * - * @param {Number} x X component - * @param {Number} y Y component - * @param {Number} z Z component - * @param {Number} w W component - * @returns {quat} a new quaternion - * @function - */ - quat.new = function (x, y, z, w) { - return new _quat(x, y, z, w); - }; - - /** - * Creates a new quat initialized with values from an existing quaternion - * - * @param {quat} a quaternion to clone - * @returns {quat} a new quaternion - * @function - */ - quat.clone = function (a) { - return new _quat(a.x, a.y, a.z, a.w); - }; - - /** - * Copy the values from one quat to another - * - * @param {quat} out the receiving quaternion - * @param {quat} a the source quaternion - * @returns {quat} out - * @function - */ - quat.copy = vec4.copy; - - /** - * Set the components of a quat to the given values - * - * @param {quat} out the receiving quaternion - * @param {Number} x X component - * @param {Number} y Y component - * @param {Number} z Z component - * @param {Number} w W component - * @returns {quat} out - * @function - */ - quat.set = vec4.set; - - /** - * Set a quat to the identity quaternion - * - * @param {quat} out the receiving quaternion - * @returns {quat} out - */ - quat.identity = function (out) { + return x * x + y * y + z * z + w * w; +}; + +/** + * Alias for {@link vec4.squaredDistance} + * @function + */ +vec4.sqrDist = vec4.squaredDistance; + +/** + * Calculates the length of a vec4 + * + * @param {vec4} a vector to calculate length of + * @returns {Number} length of a + */ +vec4.length = function (a) { + var x = a.x, + y = a.y, + z = a.z, + w = a.w; + return Math.sqrt(x * x + y * y + z * z + w * w); +}; + +/** + * Alias for {@link vec4.length} + * @function + */ +vec4.len = vec4.length; + +/** + * Calculates the squared length of a vec4 + * + * @param {vec4} a vector to calculate squared length of + * @returns {Number} squared length of a + */ +vec4.squaredLength = function (a) { + var x = a.x, + y = a.y, + z = a.z, + w = a.w; + return x * x + y * y + z * z + w * w; +}; + +/** + * Alias for {@link vec4.squaredLength} + * @function + */ +vec4.sqrLen = vec4.squaredLength; + +/** + * Negates the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to negate + * @returns {vec4} out + */ +vec4.negate = function (out, a) { + out.x = -a.x; + out.y = -a.y; + out.z = -a.z; + out.w = -a.w; + return out; +}; + +/** + * Returns the inverse of the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to invert + * @returns {vec4} out + */ +vec4.inverse = function (out, a) { + out.x = 1.0 / a.x; + out.y = 1.0 / a.y; + out.z = 1.0 / a.z; + out.w = 1.0 / a.w; + return out; +}; + +/** + * Returns the inverse of the components of a vec4 safely + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to invert + * @returns {vec4} out + */ +vec4.inverseSafe = function (out, a) { + var x = a.x, + y = a.y, + z = a.z, + w = a.w; + + if (Math.abs(x) < EPSILON) { out.x = 0; + } else { + out.x = 1.0 / x; + } + + if (Math.abs(y) < EPSILON) { out.y = 0; + } else { + out.y = 1.0 / y; + } + + if (Math.abs(z) < EPSILON) { out.z = 0; - out.w = 1; - return out; - }; - - /** - * Sets a quaternion to represent the shortest rotation from one - * vector to another. - * - * Both vectors are assumed to be unit length. - * - * @param {quat} out the receiving quaternion. - * @param {vec3} a the initial vector - * @param {vec3} b the destination vector - * @returns {quat} out - */ - quat.rotationTo = (function () { - var tmpvec3 = vec3.create(); - var xUnitVec3 = vec3.new(1, 0, 0); - var yUnitVec3 = vec3.new(0, 1, 0); - - return function (out, a, b) { - var dot = vec3.dot(a, b); - if (dot < -0.999999) { - vec3.cross(tmpvec3, xUnitVec3, a); - if (vec3.length(tmpvec3) < 0.000001) { - vec3.cross(tmpvec3, yUnitVec3, a); - } - vec3.normalize(tmpvec3, tmpvec3); - quat.fromAxisAngle(out, tmpvec3, Math.PI); - return out; - } else if (dot > 0.999999) { - out.x = 0; - out.y = 0; - out.z = 0; - out.w = 1; - return out; - } else { - vec3.cross(tmpvec3, a, b); - out.x = tmpvec3.x; - out.y = tmpvec3.y; - out.z = tmpvec3.z; - out.w = 1 + dot; - return quat.normalize(out, out); - } - }; - })(); - - /** - * Gets the rotation axis and angle for a given - * quaternion. If a quaternion is created with - * fromAxisAngle, this method will return the same - * values as providied in the original parameter list - * OR functionally equivalent values. - * Example: The quaternion formed by axis [0, 0, 1] and - * angle -90 is the same as the quaternion formed by - * [0, 0, 1] and 270. This method favors the latter. - * @param {vec3} out_axis Vector receiving the axis of rotation - * @param {quat} q Quaternion to be decomposed - * @return {Number} Angle, in radians, of the rotation - */ - quat.getAxisAngle = function (out_axis, q) { - var rad = Math.acos(q.w) * 2.0; - var s = Math.sin(rad / 2.0); - if (s != 0.0) { - out_axis.x = q.x / s; - out_axis.y = q.y / s; - out_axis.z = q.z / s; + } else { + out.z = 1.0 / z; + } + + if (Math.abs(w) < EPSILON) { + out.w = 0; + } else { + out.w = 1.0 / w; + } + + return out; +}; + +/** + * Normalize a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to normalize + * @returns {vec4} out + */ +vec4.normalize = function (out, a) { + var x = a.x, + y = a.y, + z = a.z, + w = a.w; + var len = x * x + y * y + z * z + w * w; + if (len > 0) { + len = 1 / Math.sqrt(len); + out.x = x * len; + out.y = y * len; + out.z = z * len; + out.w = w * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec4's + * + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {Number} dot product of a and b + */ +vec4.dot = function (a, b) { + return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; +}; + +/** + * Performs a linear interpolation between two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {vec4} out + */ +vec4.lerp = function (out, a, b, t) { + var ax = a.x, + ay = a.y, + az = a.z, + aw = a.w; + out.x = ax + t * (b.x - ax); + out.y = ay + t * (b.y - ay); + out.z = az + t * (b.z - az); + out.w = aw + t * (b.w - aw); + return out; +}; + +/** + * Generates a random vector with the given scale + * + * @param {vec4} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec4} out + */ +vec4.random = function (out, scale) { + scale = scale || 1.0; + + //TODO: This is a pretty awful way of doing this. Find something better. + out.x = random(); + out.y = random(); + out.z = random(); + out.w = random(); + vec4.normalize(out, out); + vec4.scale(out, out, scale); + return out; +}; + +/** + * Transforms the vec4 with a mat4. + * + * @param {vec4} out the receiving vector + * @param {vec4} a the vector to transform + * @param {mat4} m matrix to transform with + * @returns {vec4} out + */ +vec4.transformMat4 = function (out, a, m) { + var x = a.x, y = a.y, z = a.z, w = a.w; + out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12 * w; + out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13 * w; + out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14 * w; + out.w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15 * w; + return out; +}; + +/** + * Transforms the vec4 with a quat + * + * @param {vec4} out the receiving vector + * @param {vec4} a the vector to transform + * @param {quat} q quaternion to transform with + * @returns {vec4} out + */ +vec4.transformQuat = function (out, a, q) { + var x = a.x, y = a.y, z = a.z; + var qx = q.x, qy = q.y, qz = q.z, qw = q.w; + + // calculate quat * vec + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = -qx * x - qy * y - qz * z; + + // calculate result * inverse quat + out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; + out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; + out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; + out.w = a.w; + return out; +}; + +/** + * Perform some operation over an array of vec4s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ +vec4.forEach = (function () { + var vec = vec4.create(); + + return function (a, stride, offset, count, fn, arg) { + var i, l; + if (!stride) { + stride = 4; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min((count * stride) + offset, a.length); } else { - // If s is zero, return any axis (no rotation - axis does not matter) - out_axis.x = 1; - out_axis.y = 0; - out_axis.z = 0; + l = a.length; } - return rad; - }; - - /** - * Multiplies two quat's - * - * @param {quat} out the receiving quaternion - * @param {quat} a the first operand - * @param {quat} b the second operand - * @returns {quat} out - */ - quat.multiply = function (out, a, b) { - var ax = a.x, ay = a.y, az = a.z, aw = a.w, - bx = b.x, by = b.y, bz = b.z, bw = b.w; - - out.x = ax * bw + aw * bx + ay * bz - az * by; - out.y = ay * bw + aw * by + az * bx - ax * bz; - out.z = az * bw + aw * bz + ax * by - ay * bx; - out.w = aw * bw - ax * bx - ay * by - az * bz; - return out; - }; - - /** - * Alias for {@link quat.multiply} - * @function - */ - quat.mul = quat.multiply; - - /** - * Scales a quat by a scalar number - * - * @param {quat} out the receiving vector - * @param {quat} a the vector to scale - * @param {Number} b amount to scale the vector by - * @returns {quat} out - * @function - */ - quat.scale = vec4.scale; - - /** - * Rotates a quaternion by the given angle about the X axis - * - * @param {quat} out quat receiving operation result - * @param {quat} a quat to rotate - * @param {number} rad angle (in radians) to rotate - * @returns {quat} out - */ - quat.rotateX = function (out, a, rad) { - rad *= 0.5; - - var ax = a.x, ay = a.y, az = a.z, aw = a.w, - bx = Math.sin(rad), bw = Math.cos(rad); - - out.x = ax * bw + aw * bx; - out.y = ay * bw + az * bx; - out.z = az * bw - ay * bx; - out.w = aw * bw - ax * bx; - return out; - }; - - /** - * Rotates a quaternion by the given angle about the Y axis - * - * @param {quat} out quat receiving operation result - * @param {quat} a quat to rotate - * @param {number} rad angle (in radians) to rotate - * @returns {quat} out - */ - quat.rotateY = function (out, a, rad) { - rad *= 0.5; - - var ax = a.x, ay = a.y, az = a.z, aw = a.w, - by = Math.sin(rad), bw = Math.cos(rad); - - out.x = ax * bw - az * by; - out.y = ay * bw + aw * by; - out.z = az * bw + ax * by; - out.w = aw * bw - ay * by; - return out; - }; - - /** - * Rotates a quaternion by the given angle about the Z axis - * - * @param {quat} out quat receiving operation result - * @param {quat} a quat to rotate - * @param {number} rad angle (in radians) to rotate - * @returns {quat} out - */ - quat.rotateZ = function (out, a, rad) { - rad *= 0.5; - - var ax = a.x, ay = a.y, az = a.z, aw = a.w, - bz = Math.sin(rad), bw = Math.cos(rad); - - out.x = ax * bw + ay * bz; - out.y = ay * bw - ax * bz; - out.z = az * bw + aw * bz; - out.w = aw * bw - az * bz; - return out; - }; - - /** - * Rotates a quaternion by the given angle about the axis in world space - * - * @param {quat} out quat receiving operation result - * @param {quat} rot quat to rotate - * @param {vec3} axis the axis around which to rotate in world space - * @param {number} rad angle (in radians) to rotate - * @returns {quat} out - */ - quat.rotateAround = (function () { - var v3_tmp = vec3.create(); - var q_tmp = quat.create(); - - return function (out, rot, axis, rad) { - // get inv-axis (local to rot) - quat.invert(q_tmp, rot); - vec3.transformQuat(v3_tmp, axis, q_tmp); - // rotate by inv-axis - quat.fromAxisAngle(q_tmp, v3_tmp, rad); - quat.mul(out, rot, q_tmp); - - return out; - }; - })(); - - /** - * Rotates a quaternion by the given angle about the axis in local space - * - * @param {quat} out quat receiving operation result - * @param {quat} rot quat to rotate - * @param {vec3} axis the axis around which to rotate in local space - * @param {number} rad angle (in radians) to rotate - * @returns {quat} out - */ - quat.rotateAroundLocal = (function () { - var q_tmp = quat.create(); - - return function (out, rot, axis, rad) { - quat.fromAxisAngle(q_tmp, axis, rad); - quat.mul(out, rot, q_tmp); - - return out; - }; - })(); - - /** - * Calculates the W component of a quat from the X, Y, and Z components. - * Assumes that quaternion is 1 unit in length. - * Any existing W component will be ignored. - * - * @param {quat} out the receiving quaternion - * @param {quat} a quat to calculate W component of - * @returns {quat} out - */ - quat.calculateW = function (out, a) { - var x = a.x, y = a.y, z = a.z; - - out.x = x; - out.y = y; - out.z = z; - out.w = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z)); - return out; - }; - - /** - * Calculates the dot product of two quat's - * - * @param {quat} a the first operand - * @param {quat} b the second operand - * @returns {Number} dot product of a and b - * @function - */ - quat.dot = vec4.dot; - - /** - * Performs a linear interpolation between two quat's - * - * @param {quat} out the receiving quaternion - * @param {quat} a the first operand - * @param {quat} b the second operand - * @param {Number} t interpolation amount between the two inputs - * @returns {quat} out - * @function - */ - quat.lerp = vec4.lerp; - - /** - * Performs a spherical linear interpolation between two quat - * - * @param {quat} out the receiving quaternion - * @param {quat} a the first operand - * @param {quat} b the second operand - * @param {Number} t interpolation amount between the two inputs - * @returns {quat} out - */ - quat.slerp = function (out, a, b, t) { - // benchmarks: - // http://jsperf.com/quaternion-slerp-implementations - - var ax = a.x, ay = a.y, az = a.z, aw = a.w, - bx = b.x, by = b.y, bz = b.z, bw = b.w; - - var omega, cosom, sinom, scale0, scale1; - - // calc cosine - cosom = ax * bx + ay * by + az * bz + aw * bw; - // adjust signs (if necessary) - if (cosom < 0.0) { - cosom = -cosom; - bx = - bx; - by = - by; - bz = - bz; - bw = - bw; + + for (i = offset; i < l; i += stride) { + vec.x = a[i]; vec.y = a[i + 1]; vec.z = a[i + 2]; vec.w = a[i + 3]; + fn(vec, vec, arg); + a[i] = vec.x; a[i + 1] = vec.y; a[i + 2] = vec.z; a[i + 3] = vec.w; } - // calculate coefficients - if ((1.0 - cosom) > 0.000001) { - // standard case (slerp) - omega = Math.acos(cosom); - sinom = Math.sin(omega); - scale0 = Math.sin((1.0 - t) * omega) / sinom; - scale1 = Math.sin(t * omega) / sinom; - } else { - // "from" and "to" quaternions are very close - // ... so we can do a linear interpolation - scale0 = 1.0 - t; - scale1 = t; - } - // calculate final values - out.x = scale0 * ax + scale1 * bx; - out.y = scale0 * ay + scale1 * by; - out.z = scale0 * az + scale1 * bz; - out.w = scale0 * aw + scale1 * bw; - - return out; + + return a; }; - - /** - * Performs a spherical linear interpolation with two control points - * - * @param {quat} out the receiving quaternion - * @param {quat} a the first operand - * @param {quat} b the second operand - * @param {quat} c the third operand - * @param {quat} d the fourth operand - * @param {Number} t interpolation amount - * @returns {quat} out - */ - quat.sqlerp = (function () { - var temp1 = quat.create(); - var temp2 = quat.create(); - - return function (out, a, b, c, d, t) { - quat.slerp(temp1, a, d, t); - quat.slerp(temp2, b, c, t); - quat.slerp(out, temp1, temp2, 2 * t * (1 - t)); - - return out; - }; - }()); - - /** - * Calculates the inverse of a quat - * - * @param {quat} out the receiving quaternion - * @param {quat} a quat to calculate inverse of - * @returns {quat} out - */ - quat.invert = function (out, a) { - var a0 = a.x, a1 = a.y, a2 = a.z, a3 = a.w; - var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; - var invDot = dot ? 1.0 / dot : 0; - - // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 - - out.x = -a0 * invDot; - out.y = -a1 * invDot; - out.z = -a2 * invDot; - out.w = a3 * invDot; - return out; - }; - - /** - * Calculates the conjugate of a quat - * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. - * - * @param {quat} out the receiving quaternion - * @param {quat} a quat to calculate conjugate of - * @returns {quat} out - */ - quat.conjugate = function (out, a) { - out.x = -a.x; - out.y = -a.y; - out.z = -a.z; - out.w = a.w; - return out; - }; - - /** - * Calculates the length of a quat - * - * @param {quat} a vector to calculate length of - * @returns {Number} length of a - * @function - */ - quat.length = vec4.length; - - /** - * Alias for {@link quat.length} - * @function - */ - quat.len = quat.length; - - /** - * Calculates the squared length of a quat - * - * @param {quat} a vector to calculate squared length of - * @returns {Number} squared length of a - * @function - */ - quat.squaredLength = vec4.squaredLength; - - /** - * Alias for {@link quat.squaredLength} - * @function - */ - quat.sqrLen = quat.squaredLength; - - /** - * Normalize a quat - * - * @param {quat} out the receiving quaternion - * @param {quat} a quaternion to normalize - * @returns {quat} out - * @function - */ - quat.normalize = vec4.normalize; - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param {vec3} xAxis the vector representing the local "right" direction - * @param {vec3} yAxis the vector representing the local "up" direction - * @param {vec3} zAxis the vector representing the viewing direction - * @returns {quat} out - */ - quat.fromAxes = (function () { - var matr = mat3.create(); - - return function (out, xAxis, yAxis, zAxis) { - mat3.set( - matr, - xAxis.x, xAxis.y, xAxis.z, - yAxis.x, yAxis.y, yAxis.z, - zAxis.x, zAxis.y, zAxis.z - ); - return quat.normalize(out, quat.fromMat3(out, matr)); - }; - })(); - - /** - * Calculates a quaternion from view direction and up direction - * - * @param {quat} out mat3 receiving operation result - * @param {vec3} view view direction (must be normalized) - * @param {vec3} [up] up direction, default is (0,1,0) (must be normalized) - * - * @returns {quat} out - */ - quat.fromViewUp = (function () { - var matr = mat3.create(); - - return function (out, view, up) { - mat3.fromViewUp(matr, view, up); - if (!matr) { - return null; - } - - return quat.normalize(out, quat.fromMat3(out, matr)); - }; - })(); - - /** - * Sets a quat from the given angle and rotation axis, - * then returns it. - * - * @param {quat} out the receiving quaternion - * @param {vec3} axis the axis around which to rotate - * @param {Number} rad the angle in radians - * @returns {quat} out - **/ - quat.fromAxisAngle = function (out, axis, rad) { - rad = rad * 0.5; - var s = Math.sin(rad); - out.x = s * axis.x; - out.y = s * axis.y; - out.z = s * axis.z; - out.w = Math.cos(rad); - return out; - }; - - /** - * Creates a quaternion from the given 3x3 rotation matrix. - * - * NOTE: The resultant quaternion is not normalized, so you should be sure - * to renormalize the quaternion yourself where necessary. - * - * @param {quat} out the receiving quaternion - * @param {mat3} m rotation matrix - * @returns {quat} out - * @function - */ - quat.fromMat3 = function (out, m) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - - var m00 = m.m00, m01 = m.m03, m02 = m.m06, - m10 = m.m01, m11 = m.m04, m12 = m.m07, - m20 = m.m02, m21 = m.m05, m22 = m.m08; - - var trace = m00 + m11 + m22; - - if (trace > 0) { - var s = 0.5 / Math.sqrt(trace + 1.0); - - out.w = 0.25 / s; - out.x = (m21 - m12) * s; - out.y = (m02 - m20) * s; - out.z = (m10 - m01) * s; - - } else if ((m00 > m11) && (m00 > m22)) { - var s$1 = 2.0 * Math.sqrt(1.0 + m00 - m11 - m22); - - out.w = (m21 - m12) / s$1; - out.x = 0.25 * s$1; - out.y = (m01 + m10) / s$1; - out.z = (m02 + m20) / s$1; - - } else if (m11 > m22) { - var s$2 = 2.0 * Math.sqrt(1.0 + m11 - m00 - m22); - - out.w = (m02 - m20) / s$2; - out.x = (m01 + m10) / s$2; - out.y = 0.25 * s$2; - out.z = (m12 + m21) / s$2; - - } else { - var s$3 = 2.0 * Math.sqrt(1.0 + m22 - m00 - m11); - - out.w = (m10 - m01) / s$3; - out.x = (m02 + m20) / s$3; - out.y = (m12 + m21) / s$3; - out.z = 0.25 * s$3; - } - - return out; - }; - - /** - * Creates a quaternion from the given euler angle x, y, z. - * - * @param {quat} out the receiving quaternion - * @param {x} Angle to rotate around X axis in degrees. - * @param {y} Angle to rotate around Y axis in degrees. - * @param {z} Angle to rotate around Z axis in degrees. - * @returns {quat} out - * @function - */ - quat.fromEuler = function (out, x, y, z) { - var halfToRad = 0.5 * Math.PI / 180.0; - x *= halfToRad; - y *= halfToRad; - z *= halfToRad; - - var sx = Math.sin(x); - var cx = Math.cos(x); - var sy = Math.sin(y); - var cy = Math.cos(y); - var sz = Math.sin(z); - var cz = Math.cos(z); - - out.x = sx * cy * cz - cx * sy * sz; - out.y = cx * sy * cz + sx * cy * sz; - out.z = cx * cy * sz - sx * sy * cz; - out.w = cx * cy * cz + sx * sy * sz; - - return out; - }; - - /** - * Returns a string representation of a quatenion - * - * @param {quat} a vector to represent as a string - * @returns {String} string representation of the vector - */ - quat.str = function (a) { - return ("quat(" + (a.x) + ", " + (a.y) + ", " + (a.z) + ", " + (a.w) + ")"); - }; - - /** - * Returns typed array - * - * @param {array} out - * @param {quat} q - * @returns {array} - */ - quat.array = function (out, q) { - out[0] = q.x; - out[1] = q.y; - out[2] = q.z; - out[3] = q.w; - - return out; - }; - - /** - * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) - * - * @param {quat} a The first quaternion. - * @param {quat} b The second quaternion. - * @returns {Boolean} True if the vectors are equal, false otherwise. - */ - quat.exactEquals = vec4.exactEquals; - - /** - * Returns whether or not the quaternions have approximately the same elements in the same position. - * - * @param {quat} a The first vector. - * @param {quat} b The second vector. - * @returns {Boolean} True if the vectors are equal, false otherwise. - */ - quat.equals = vec4.equals; - - var _tmp$5 = new Array(4); - - var _mat2 = function _mat2(m00, m01, m02, m03) { - this.m00 = m00; - this.m01 = m01; - this.m02 = m02; - this.m03 = m03; - }; - - _mat2.prototype.toJSON = function toJSON () { - _tmp$5[0] = this.m00; - _tmp$5[1] = this.m01; - _tmp$5[2] = this.m02; - _tmp$5[3] = this.m03; - - return _tmp$5; - }; - - /** - * @class 2x2 Matrix - * @name mat2 - */ - var mat2 = {}; - - /** - * Creates a new identity mat2 - * - * @returns {mat2} a new 2x2 matrix - */ - mat2.create = function() { - return new _mat2(1, 0, 0, 1); - }; - - /** - * Create a new mat2 with the given values - * - * @param {Number} m00 Component in column 0, row 0 position (index 0) - * @param {Number} m01 Component in column 0, row 1 position (index 1) - * @param {Number} m10 Component in column 1, row 0 position (index 2) - * @param {Number} m11 Component in column 1, row 1 position (index 3) - * @returns {mat2} out A new 2x2 matrix - */ - mat2.new = function (m00, m01, m10, m11) { - return new _mat2(m00, m01, m10, m11); - }; - - /** - * Creates a new mat2 initialized with values from an existing matrix - * - * @param {mat2} a matrix to clone - * @returns {mat2} a new 2x2 matrix - */ - mat2.clone = function (a) { - return new _mat2(a.m00, a.m01, a.m02, a.m03); - }; - - /** - * Copy the values from one mat2 to another - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the source matrix - * @returns {mat2} out - */ - mat2.copy = function (out, a) { +})(); + +/** + * Returns a string representation of a vector + * + * @param {vec4} a vector to represent as a string + * @returns {String} string representation of the vector + */ +vec4.str = function (a) { + return ("vec4(" + (a.x) + ", " + (a.y) + ", " + (a.z) + ", " + (a.w) + ")"); +}; + +/** + * Returns typed array + * + * @param {array} out + * @param {vec4} v + * @returns {array} + */ +vec4.array = function (out, v) { + out[0] = v.x; + out[1] = v.y; + out[2] = v.z; + out[3] = v.w; + + return out; +}; + +/** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ +vec4.exactEquals = function (a, b) { + return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w; +}; + +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ +vec4.equals = function (a, b) { + var a0 = a.x, a1 = a.y, a2 = a.z, a3 = a.w; + var b0 = b.x, b1 = b.y, b2 = b.z, b3 = b.w; + return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && + Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && + Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && + Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3))); +}; + +var _tmp$3 = new Array(9); + +var _mat3 = function _mat3(m00, m01, m02, m03, m04, m05, m06, m07, m08) { + this.m00 = m00; + this.m01 = m01; + this.m02 = m02; + this.m03 = m03; + this.m04 = m04; + this.m05 = m05; + this.m06 = m06; + this.m07 = m07; + this.m08 = m08; +}; + +_mat3.prototype.toJSON = function toJSON () { + _tmp$3[0] = this.m00; + _tmp$3[1] = this.m01; + _tmp$3[2] = this.m02; + _tmp$3[3] = this.m03; + _tmp$3[4] = this.m04; + _tmp$3[5] = this.m05; + _tmp$3[6] = this.m06; + _tmp$3[7] = this.m07; + _tmp$3[8] = this.m08; + + return _tmp$3; +}; + +/** + * @class 3x3 Matrix + * @name mat3 + * + * NOTE: we use column-major matrix for all matrix calculation. + * + * This may lead to some confusion when referencing OpenGL documentation, + * however, which represents out all matricies in column-major format. + * This means that while in code a matrix may be typed out as: + * + * [1, 0, 0, 0, + * 0, 1, 0, 0, + * 0, 0, 1, 0, + * x, y, z, 0] + * + * The same matrix in the [OpenGL documentation](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml) + * is written as: + * + * 1 0 0 x + * 0 1 0 y + * 0 0 1 z + * 0 0 0 0 + * + * Please rest assured, however, that they are the same thing! + * This is not unique to glMatrix, either, as OpenGL developers have long been confused by the + * apparent lack of consistency between the memory layout and the documentation. + */ +var mat3 = {}; + +/** + * Creates a new identity mat3 + * + * @returns {mat3} a new 3x3 matrix + */ +mat3.create = function () { + return new _mat3( + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ); +}; + +/** + * Create a new mat3 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m10 Component in column 1, row 0 position (index 3) + * @param {Number} m11 Component in column 1, row 1 position (index 4) + * @param {Number} m12 Component in column 1, row 2 position (index 5) + * @param {Number} m20 Component in column 2, row 0 position (index 6) + * @param {Number} m21 Component in column 2, row 1 position (index 7) + * @param {Number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ +mat3.new = function (m00, m01, m02, m10, m11, m12, m20, m21, m22) { + return new _mat3( + m00, m01, m02, + m10, m11, m12, + m20, m21, m22 + ); +}; + +/** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param {mat3} a matrix to clone + * @returns {mat3} a new 3x3 matrix + */ +mat3.clone = function (a) { + return new _mat3( + a.m00, a.m01, a.m02, + a.m03, a.m04, a.m05, + a.m06, a.m07, a.m08 + ); +}; + +/** + * Copy the values from one mat3 to another + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.copy = function (out, a) { + out.m00 = a.m00; + out.m01 = a.m01; + out.m02 = a.m02; + out.m03 = a.m03; + out.m04 = a.m04; + out.m05 = a.m05; + out.m06 = a.m06; + out.m07 = a.m07; + out.m08 = a.m08; + return out; +}; + +/** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m10 Component in column 1, row 0 position (index 3) + * @param {Number} m11 Component in column 1, row 1 position (index 4) + * @param {Number} m12 Component in column 1, row 2 position (index 5) + * @param {Number} m20 Component in column 2, row 0 position (index 6) + * @param {Number} m21 Component in column 2, row 1 position (index 7) + * @param {Number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ +mat3.set = function (out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { + out.m00 = m00; + out.m01 = m01; + out.m02 = m02; + out.m03 = m10; + out.m04 = m11; + out.m05 = m12; + out.m06 = m20; + out.m07 = m21; + out.m08 = m22; + return out; +}; + +/** + * Set a mat3 to the identity matrix + * + * @param {mat3} out the receiving matrix + * @returns {mat3} out + */ +mat3.identity = function (out) { + out.m00 = 1; + out.m01 = 0; + out.m02 = 0; + out.m03 = 0; + out.m04 = 1; + out.m05 = 0; + out.m06 = 0; + out.m07 = 0; + out.m08 = 1; + return out; +}; + +/** + * Transpose the values of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.transpose = function (out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a.m01, a02 = a.m02, a12 = a.m05; + out.m01 = a.m03; + out.m02 = a.m06; + out.m03 = a01; + out.m05 = a.m07; + out.m06 = a02; + out.m07 = a12; + } else { out.m00 = a.m00; - out.m01 = a.m01; - out.m02 = a.m02; - out.m03 = a.m03; - return out; - }; - - /** - * Set a mat2 to the identity matrix - * - * @param {mat2} out the receiving matrix - * @returns {mat2} out - */ - mat2.identity = function (out) { - out.m00 = 1; - out.m01 = 0; - out.m02 = 0; - out.m03 = 1; - return out; - }; - - /** - * Set the components of a mat2 to the given values - * - * @param {mat2} out the receiving matrix - * @param {Number} m00 Component in column 0, row 0 position (index 0) - * @param {Number} m01 Component in column 0, row 1 position (index 1) - * @param {Number} m10 Component in column 1, row 0 position (index 2) - * @param {Number} m11 Component in column 1, row 1 position (index 3) - * @returns {mat2} out - */ - mat2.set = function (out, m00, m01, m10, m11) { - out.m00 = m00; - out.m01 = m01; - out.m02 = m10; - out.m03 = m11; - return out; - }; - - - /** - * Transpose the values of a mat2 - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the source matrix - * @returns {mat2} out - */ - mat2.transpose = function (out, a) { - // If we are transposing ourselves we can skip a few steps but have to cache some values - if (out === a) { - var a1 = a.m01; - out.m01 = a.m02; - out.m02 = a1; - } else { - out.m00 = a.m00; - out.m01 = a.m02; - out.m02 = a.m01; - out.m03 = a.m03; - } - - return out; - }; - - /** - * Inverts a mat2 - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the source matrix - * @returns {mat2} out - */ - mat2.invert = function (out, a) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03; - - // Calculate the determinant - var det = a0 * a3 - a2 * a1; - - if (!det) { - return null; - } - det = 1.0 / det; - - out.m00 = a3 * det; - out.m01 = -a1 * det; - out.m02 = -a2 * det; - out.m03 = a0 * det; - - return out; - }; - - /** - * Calculates the adjugate of a mat2 - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the source matrix - * @returns {mat2} out - */ - mat2.adjoint = function (out, a) { - // Caching this value is nessecary if out == a - var a0 = a.m00; - out.m00 = a.m03; - out.m01 = -a.m01; - out.m02 = -a.m02; - out.m03 = a0; - - return out; - }; - - /** - * Calculates the determinant of a mat2 - * - * @param {mat2} a the source matrix - * @returns {Number} determinant of a - */ - mat2.determinant = function (a) { - return a.m00 * a.m03 - a.m02 * a.m01; - }; - - /** - * Multiplies two mat2's - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - mat2.multiply = function (out, a, b) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03; - var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03; - out.m00 = a0 * b0 + a2 * b1; - out.m01 = a1 * b0 + a3 * b1; - out.m02 = a0 * b2 + a2 * b3; - out.m03 = a1 * b2 + a3 * b3; - return out; - }; - - /** - * Alias for {@link mat2.multiply} - * @function - */ - mat2.mul = mat2.multiply; - - /** - * Rotates a mat2 by the given angle - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat2} out - */ - mat2.rotate = function (out, a, rad) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, - s = Math.sin(rad), - c = Math.cos(rad); - out.m00 = a0 * c + a2 * s; - out.m01 = a1 * c + a3 * s; - out.m02 = a0 * -s + a2 * c; - out.m03 = a1 * -s + a3 * c; - return out; - }; - - /** - * Scales the mat2 by the dimensions in the given vec2 - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the matrix to rotate - * @param {vec2} v the vec2 to scale the matrix by - * @returns {mat2} out - **/ - mat2.scale = function (out, a, v) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, - v0 = v.x, v1 = v.y; - out.m00 = a0 * v0; - out.m01 = a1 * v0; - out.m02 = a2 * v1; - out.m03 = a3 * v1; - return out; - }; - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat2.identity(dest); - * mat2.rotate(dest, dest, rad); - * - * @param {mat2} out mat2 receiving operation result - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat2} out - */ - mat2.fromRotation = function (out, rad) { - var s = Math.sin(rad), - c = Math.cos(rad); - out.m00 = c; - out.m01 = s; - out.m02 = -s; - out.m03 = c; - return out; - }; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat2.identity(dest); - * mat2.scale(dest, dest, vec); - * - * @param {mat2} out mat2 receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat2} out - */ - mat2.fromScaling = function (out, v) { - out.m00 = v.x; - out.m01 = 0; - out.m02 = 0; - out.m03 = v.y; - return out; - }; - - /** - * Returns a string representation of a mat2 - * - * @param {mat2} a matrix to represent as a string - * @returns {String} string representation of the matrix - */ - mat2.str = function (a) { - return ("mat2(" + (a.m00) + ", " + (a.m01) + ", " + (a.m02) + ", " + (a.m03) + ")"); - }; - - /** - * Returns typed array - * - * @param {array} out - * @param {mat2} m - * @returns {array} - */ - mat2.array = function (out, m) { - out[0] = m.m00; - out[1] = m.m01; - out[2] = m.m02; - out[3] = m.m03; - - return out; - }; - - /** - * Returns Frobenius norm of a mat2 - * - * @param {mat2} a the matrix to calculate Frobenius norm of - * @returns {Number} Frobenius norm - */ - mat2.frob = function (a) { - return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2))); - }; - - /** - * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix - * @param {mat2} L the lower triangular matrix - * @param {mat2} D the diagonal matrix - * @param {mat2} U the upper triangular matrix - * @param {mat2} a the input matrix to factorize - */ - - mat2.LDU = function (L, D, U, a) { - L.m02 = a.m02 / a.m00; - U.m00 = a.m00; - U.m01 = a.m01; - U.m03 = a.m03 - L.m02 * U.m01; - }; - - /** - * Adds two mat2's - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - mat2.add = function (out, a, b) { - out.m00 = a.m00 + b.m00; - out.m01 = a.m01 + b.m01; - out.m02 = a.m02 + b.m02; - out.m03 = a.m03 + b.m03; - return out; - }; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - mat2.subtract = function (out, a, b) { - out.m00 = a.m00 - b.m00; - out.m01 = a.m01 - b.m01; - out.m02 = a.m02 - b.m02; - out.m03 = a.m03 - b.m03; - return out; - }; - - /** - * Alias for {@link mat2.subtract} - * @function - */ - mat2.sub = mat2.subtract; - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat2} a The first matrix. - * @param {mat2} b The second matrix. - * @returns {Boolean} True if the matrices are equal, false otherwise. - */ - mat2.exactEquals = function (a, b) { - return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03; - }; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat2} a The first matrix. - * @param {mat2} b The second matrix. - * @returns {Boolean} True if the matrices are equal, false otherwise. - */ - mat2.equals = function (a, b) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03; - var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03; - return ( - Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && - Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && - Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && - Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) - ); - }; - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the matrix to scale - * @param {Number} b amount to scale the matrix's elements by - * @returns {mat2} out - */ - mat2.multiplyScalar = function (out, a, b) { - out.m00 = a.m00 * b; - out.m01 = a.m01 * b; - out.m02 = a.m02 * b; - out.m03 = a.m03 * b; - return out; - }; - - /** - * Adds two mat2's after multiplying each element of the second operand by a scalar value. - * - * @param {mat2} out the receiving vector - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @param {Number} scale the amount to scale b's elements by before adding - * @returns {mat2} out - */ - mat2.multiplyScalarAndAdd = function (out, a, b, scale) { - out.m00 = a.m00 + (b.m00 * scale); - out.m01 = a.m01 + (b.m01 * scale); - out.m02 = a.m02 + (b.m02 * scale); - out.m03 = a.m03 + (b.m03 * scale); - return out; - }; - - var _tmp$6 = new Array(6); - - var _mat23 = function _mat23(m00, m01, m02, m03, m04, m05) { - this.m00 = m00; - this.m01 = m01; - this.m02 = m02; - this.m03 = m03; - this.m04 = m04; - this.m05 = m05; - }; - - _mat23.prototype.toJSON = function toJSON () { - _tmp$6[0] = this.m00; - _tmp$6[1] = this.m01; - _tmp$6[2] = this.m02; - _tmp$6[3] = this.m03; - _tmp$6[4] = this.m04; - _tmp$6[5] = this.m05; - - return _tmp$6; - }; - - /** - * @class 2x3 Matrix - * @name mat23 - * - * @description - * A mat23 contains six elements defined as: - *
-   * [a, c, tx,
-   *  b, d, ty]
-   * 
- * This is a short form for the 3x3 matrix: - *
-   * [a, c, tx,
-   *  b, d, ty,
-   *  0, 0, 1]
-   * 
- * The last row is ignored so the array is shorter and operations are faster. - */ - var mat23 = {}; - - /** - * Creates a new identity mat23 - * - * @returns {mat23} a new 2x3 matrix - */ - mat23.create = function () { - return new _mat23( - 1, 0, - 0, 1, - 0, 0 - ); - }; - - /** - * Create a new mat23 with the given values - * - * @param {Number} a Component A (index 0) - * @param {Number} b Component B (index 1) - * @param {Number} c Component C (index 2) - * @param {Number} d Component D (index 3) - * @param {Number} tx Component TX (index 4) - * @param {Number} ty Component TY (index 5) - * @returns {mat23} A new mat23 - */ - mat23.new = function (a, b, c, d, tx, ty) { - return new _mat23( - a, b, - c, d, - tx, ty - ); - }; - - /** - * Creates a new mat23 initialized with values from an existing matrix - * - * @param {mat23} a matrix to clone - * @returns {mat23} a new 2x3 matrix - */ - mat23.clone = function (a) { - return new _mat23( - a.m00, a.m01, - a.m02, a.m03, - a.m04, a.m05 - ); - }; - - /** - * Copy the values from one mat23 to another - * - * @param {mat23} out the receiving matrix - * @param {mat23} a the source matrix - * @returns {mat23} out - */ - mat23.copy = function (out, a) { - out.m00 = a.m00; - out.m01 = a.m01; - out.m02 = a.m02; - out.m03 = a.m03; + out.m01 = a.m03; + out.m02 = a.m06; + out.m03 = a.m01; out.m04 = a.m04; - out.m05 = a.m05; + out.m05 = a.m07; + out.m06 = a.m02; + out.m07 = a.m05; + out.m08 = a.m08; + } + + return out; +}; + +/** + * Inverts a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.invert = function (out, a) { + var a00 = a.m00, a01 = a.m01, a02 = a.m02, + a10 = a.m03, a11 = a.m04, a12 = a.m05, + a20 = a.m06, a21 = a.m07, a22 = a.m08; + + var b01 = a22 * a11 - a12 * a21; + var b11 = -a22 * a10 + a12 * a20; + var b21 = a21 * a10 - a11 * a20; + + // Calculate the determinant + var det = a00 * b01 + a01 * b11 + a02 * b21; + + if (!det) { + return null; + } + det = 1.0 / det; + + out.m00 = b01 * det; + out.m01 = (-a22 * a01 + a02 * a21) * det; + out.m02 = (a12 * a01 - a02 * a11) * det; + out.m03 = b11 * det; + out.m04 = (a22 * a00 - a02 * a20) * det; + out.m05 = (-a12 * a00 + a02 * a10) * det; + out.m06 = b21 * det; + out.m07 = (-a21 * a00 + a01 * a20) * det; + out.m08 = (a11 * a00 - a01 * a10) * det; + return out; +}; + +/** + * Calculates the adjugate of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.adjoint = function (out, a) { + var a00 = a.m00, a01 = a.m01, a02 = a.m02, + a10 = a.m03, a11 = a.m04, a12 = a.m05, + a20 = a.m06, a21 = a.m07, a22 = a.m08; + + out.m00 = (a11 * a22 - a12 * a21); + out.m01 = (a02 * a21 - a01 * a22); + out.m02 = (a01 * a12 - a02 * a11); + out.m03 = (a12 * a20 - a10 * a22); + out.m04 = (a00 * a22 - a02 * a20); + out.m05 = (a02 * a10 - a00 * a12); + out.m06 = (a10 * a21 - a11 * a20); + out.m07 = (a01 * a20 - a00 * a21); + out.m08 = (a00 * a11 - a01 * a10); + return out; +}; + +/** + * Calculates the determinant of a mat3 + * + * @param {mat3} a the source matrix + * @returns {Number} determinant of a + */ +mat3.determinant = function (a) { + var a00 = a.m00, a01 = a.m01, a02 = a.m02, + a10 = a.m03, a11 = a.m04, a12 = a.m05, + a20 = a.m06, a21 = a.m07, a22 = a.m08; + + return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); +}; + +/** + * Multiplies two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ +mat3.multiply = function (out, a, b) { + var a00 = a.m00, a01 = a.m01, a02 = a.m02, + a10 = a.m03, a11 = a.m04, a12 = a.m05, + a20 = a.m06, a21 = a.m07, a22 = a.m08; + + var b00 = b.m00, b01 = b.m01, b02 = b.m02; + var b10 = b.m03, b11 = b.m04, b12 = b.m05; + var b20 = b.m06, b21 = b.m07, b22 = b.m08; + + out.m00 = b00 * a00 + b01 * a10 + b02 * a20; + out.m01 = b00 * a01 + b01 * a11 + b02 * a21; + out.m02 = b00 * a02 + b01 * a12 + b02 * a22; + + out.m03 = b10 * a00 + b11 * a10 + b12 * a20; + out.m04 = b10 * a01 + b11 * a11 + b12 * a21; + out.m05 = b10 * a02 + b11 * a12 + b12 * a22; + + out.m06 = b20 * a00 + b21 * a10 + b22 * a20; + out.m07 = b20 * a01 + b21 * a11 + b22 * a21; + out.m08 = b20 * a02 + b21 * a12 + b22 * a22; + return out; +}; + +/** + * Alias for {@link mat3.multiply} + * @function + */ +mat3.mul = mat3.multiply; + +/** + * Translate a mat3 by the given vector + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to translate + * @param {vec2} v vector to translate by + * @returns {mat3} out + */ +mat3.translate = function (out, a, v) { + var a00 = a.m00, a01 = a.m01, a02 = a.m02, + a10 = a.m03, a11 = a.m04, a12 = a.m05, + a20 = a.m06, a21 = a.m07, a22 = a.m08; + var x = v.x, y = v.y; + + out.m00 = a00; + out.m01 = a01; + out.m02 = a02; + + out.m03 = a10; + out.m04 = a11; + out.m05 = a12; + + out.m06 = x * a00 + y * a10 + a20; + out.m07 = x * a01 + y * a11 + a21; + out.m08 = x * a02 + y * a12 + a22; + return out; +}; + +/** + * Rotates a mat3 by the given angle + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ +mat3.rotate = function (out, a, rad) { + var a00 = a.m00, a01 = a.m01, a02 = a.m02, + a10 = a.m03, a11 = a.m04, a12 = a.m05, + a20 = a.m06, a21 = a.m07, a22 = a.m08; + + var s = Math.sin(rad); + var c = Math.cos(rad); + + out.m00 = c * a00 + s * a10; + out.m01 = c * a01 + s * a11; + out.m02 = c * a02 + s * a12; + + out.m03 = c * a10 - s * a00; + out.m04 = c * a11 - s * a01; + out.m05 = c * a12 - s * a02; + + out.m06 = a20; + out.m07 = a21; + out.m08 = a22; + return out; +}; + +/** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to rotate + * @param {vec2} v the vec2 to scale the matrix by + * @returns {mat3} out + **/ +mat3.scale = function (out, a, v) { + var x = v.x, y = v.y; + + out.m00 = x * a.m00; + out.m01 = x * a.m01; + out.m02 = x * a.m02; + + out.m03 = y * a.m03; + out.m04 = y * a.m04; + out.m05 = y * a.m05; + + out.m06 = a.m06; + out.m07 = a.m07; + out.m08 = a.m08; + return out; +}; + +/** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {mat4} a the source 4x4 matrix + * @returns {mat3} out + */ +mat3.fromMat4 = function (out, a) { + out.m00 = a.m00; + out.m01 = a.m01; + out.m02 = a.m02; + out.m03 = a.m04; + out.m04 = a.m05; + out.m05 = a.m06; + out.m06 = a.m08; + out.m07 = a.m09; + out.m08 = a.m10; + return out; +}; + +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Translation vector + * @returns {mat3} out + */ +mat3.fromTranslation = function (out, v) { + out.m00 = 1; + out.m01 = 0; + out.m02 = 0; + out.m03 = 0; + out.m04 = 1; + out.m05 = 0; + out.m06 = v.x; + out.m07 = v.y; + out.m08 = 1; + return out; +}; + +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ +mat3.fromRotation = function (out, rad) { + var s = Math.sin(rad), c = Math.cos(rad); + + out.m00 = c; + out.m01 = s; + out.m02 = 0; + + out.m03 = -s; + out.m04 = c; + out.m05 = 0; + + out.m06 = 0; + out.m07 = 0; + out.m08 = 1; + return out; +}; + +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat3} out + */ +mat3.fromScaling = function (out, v) { + out.m00 = v.x; + out.m01 = 0; + out.m02 = 0; + + out.m03 = 0; + out.m04 = v.y; + out.m05 = 0; + + out.m06 = 0; + out.m07 = 0; + out.m08 = 1; + return out; +}; + +/** + * Copies the values from a mat2d into a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns {mat3} out + **/ +mat3.fromMat2d = function (out, a) { + out.m00 = a.m00; + out.m01 = a.m01; + out.m02 = 0; + + out.m03 = a.m02; + out.m04 = a.m03; + out.m05 = 0; + + out.m06 = a.m04; + out.m07 = a.m05; + out.m08 = 1; + return out; +}; + +/** +* Calculates a 3x3 matrix from the given quaternion +* +* @param {mat3} out mat3 receiving operation result +* @param {quat} q Quaternion to create matrix from +* +* @returns {mat3} out +*/ +mat3.fromQuat = function (out, q) { + var x = q.x, y = q.y, z = q.z, w = q.w; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + + var xx = x * x2; + var yx = y * x2; + var yy = y * y2; + var zx = z * x2; + var zy = z * y2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + + out.m00 = 1 - yy - zz; + out.m03 = yx - wz; + out.m06 = zx + wy; + + out.m01 = yx + wz; + out.m04 = 1 - xx - zz; + out.m07 = zy - wx; + + out.m02 = zx - wy; + out.m05 = zy + wx; + out.m08 = 1 - xx - yy; + + return out; +}; + +/** +* Calculates a 3x3 matrix from view direction and up direction +* +* @param {mat3} out mat3 receiving operation result +* @param {vec3} view view direction (must be normalized) +* @param {vec3} [up] up direction, default is (0,1,0) (must be normalized) +* +* @returns {mat3} out +*/ +mat3.fromViewUp = (function () { + var default_up = vec3.new(0, 1, 0); + var x = vec3.create(); + var y = vec3.create(); + + return function (out, view, up) { + if (vec3.sqrLen(view) < EPSILON * EPSILON) { + mat3.identity(out); + return out; + } + + up = up || default_up; + vec3.cross(x, up, view); + + if (vec3.sqrLen(x) < EPSILON * EPSILON) { + mat3.identity(out); + return out; + } + + vec3.cross(y, view, x); + mat3.set(out, + x.x, x.y, x.z, + y.x, y.y, y.z, + view.x, view.y, view.z + ); + return out; }; - - /** - * Set a mat23 to the identity matrix - * - * @param {mat23} out the receiving matrix - * @returns {mat23} out - */ - mat23.identity = function (out) { - out.m00 = 1; - out.m01 = 0; - out.m02 = 0; - out.m03 = 1; - out.m04 = 0; - out.m05 = 0; +})(); + +/** +* Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix +* +* @param {mat3} out mat3 receiving operation result +* @param {mat4} a Mat4 to derive the normal matrix from +* +* @returns {mat3} out +*/ +mat3.normalFromMat4 = function (out, a) { + var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, + a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, + a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, + a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; + + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + det = 1.0 / det; + + out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out.m01 = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out.m02 = (a10 * b10 - a11 * b08 + a13 * b06) * det; + + out.m03 = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out.m04 = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out.m05 = (a01 * b08 - a00 * b10 - a03 * b06) * det; + + out.m06 = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out.m07 = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out.m08 = (a30 * b04 - a31 * b02 + a33 * b00) * det; + + return out; +}; + +/** + * Returns a string representation of a mat3 + * + * @param {mat3} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat3.str = function (a) { + return ("mat3(" + (a.m00) + ", " + (a.m01) + ", " + (a.m02) + ", " + (a.m03) + ", " + (a.m04) + ", " + (a.m05) + ", " + (a.m06) + ", " + (a.m07) + ", " + (a.m08) + ")"); +}; + +/** + * Returns typed array + * + * @param {array} out + * @param {mat3} m + * @returns {array} + */ +mat3.array = function (out, m) { + out[0] = m.m00; + out[1] = m.m01; + out[2] = m.m02; + out[3] = m.m03; + out[4] = m.m04; + out[5] = m.m05; + out[6] = m.m06; + out[7] = m.m07; + out[8] = m.m08; + + return out; +}; + +/** + * Returns Frobenius norm of a mat3 + * + * @param {mat3} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat3.frob = function (a) { + return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + Math.pow(a.m06, 2) + Math.pow(a.m07, 2) + Math.pow(a.m08, 2))); +}; + +/** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ +mat3.add = function (out, a, b) { + out.m00 = a.m00 + b.m00; + out.m01 = a.m01 + b.m01; + out.m02 = a.m02 + b.m02; + out.m03 = a.m03 + b.m03; + out.m04 = a.m04 + b.m04; + out.m05 = a.m05 + b.m05; + out.m06 = a.m06 + b.m06; + out.m07 = a.m07 + b.m07; + out.m08 = a.m08 + b.m08; + return out; +}; + +/** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ +mat3.subtract = function (out, a, b) { + out.m00 = a.m00 - b.m00; + out.m01 = a.m01 - b.m01; + out.m02 = a.m02 - b.m02; + out.m03 = a.m03 - b.m03; + out.m04 = a.m04 - b.m04; + out.m05 = a.m05 - b.m05; + out.m06 = a.m06 - b.m06; + out.m07 = a.m07 - b.m07; + out.m08 = a.m08 - b.m08; + return out; +}; + +/** + * Alias for {@link mat3.subtract} + * @function + */ +mat3.sub = mat3.subtract; + +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ +mat3.multiplyScalar = function (out, a, b) { + out.m00 = a.m00 * b; + out.m01 = a.m01 * b; + out.m02 = a.m02 * b; + out.m03 = a.m03 * b; + out.m04 = a.m04 * b; + out.m05 = a.m05 * b; + out.m06 = a.m06 * b; + out.m07 = a.m07 * b; + out.m08 = a.m08 * b; + return out; +}; + +/** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ +mat3.multiplyScalarAndAdd = function (out, a, b, scale) { + out.m00 = a.m00 + (b.m00 * scale); + out.m01 = a.m01 + (b.m01 * scale); + out.m02 = a.m02 + (b.m02 * scale); + out.m03 = a.m03 + (b.m03 * scale); + out.m04 = a.m04 + (b.m04 * scale); + out.m05 = a.m05 + (b.m05 * scale); + out.m06 = a.m06 + (b.m06 * scale); + out.m07 = a.m07 + (b.m07 * scale); + out.m08 = a.m08 + (b.m08 * scale); + return out; +}; + +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ +mat3.exactEquals = function (a, b) { + return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && + a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && + a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08; +}; + +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ +mat3.equals = function (a, b) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, a6 = a.m06, a7 = a.m07, a8 = a.m08; + var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05, b6 = b.m06, b7 = b.m07, b8 = b.m08; + return ( + Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && + Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && + Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && + Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && + Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && + Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && + Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && + Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && + Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) + ); +}; + +var _tmp$4 = new Array(4); + +var _quat = function _quat(x, y, z, w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; +}; + +_quat.prototype.toJSON = function toJSON () { + _tmp$4[0] = this.x; + _tmp$4[1] = this.y; + _tmp$4[2] = this.z; + _tmp$4[3] = this.w; + + return _tmp$4; +}; + +/** + * @class Quaternion + * @name quat + */ +var quat = {}; + +/** + * Creates a new identity quat + * + * @returns {quat} a new quaternion + */ +quat.create = function () { + return new _quat(0, 0, 0, 1); +}; + +/** + * Creates a new quat initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} a new quaternion + * @function + */ +quat.new = function (x, y, z, w) { + return new _quat(x, y, z, w); +}; + +/** + * Creates a new quat initialized with values from an existing quaternion + * + * @param {quat} a quaternion to clone + * @returns {quat} a new quaternion + * @function + */ +quat.clone = function (a) { + return new _quat(a.x, a.y, a.z, a.w); +}; + +/** + * Copy the values from one quat to another + * + * @param {quat} out the receiving quaternion + * @param {quat} a the source quaternion + * @returns {quat} out + * @function + */ +quat.copy = vec4.copy; + +/** + * Set the components of a quat to the given values + * + * @param {quat} out the receiving quaternion + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} out + * @function + */ +quat.set = vec4.set; + +/** + * Set a quat to the identity quaternion + * + * @param {quat} out the receiving quaternion + * @returns {quat} out + */ +quat.identity = function (out) { + out.x = 0; + out.y = 0; + out.z = 0; + out.w = 1; + return out; +}; + +/** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {vec3} a the initial vector + * @param {vec3} b the destination vector + * @returns {quat} out + */ +quat.rotationTo = (function () { + var tmpvec3 = vec3.create(); + var xUnitVec3 = vec3.new(1, 0, 0); + var yUnitVec3 = vec3.new(0, 1, 0); + + return function (out, a, b) { + var dot = vec3.dot(a, b); + if (dot < -0.999999) { + vec3.cross(tmpvec3, xUnitVec3, a); + if (vec3.length(tmpvec3) < 0.000001) { + vec3.cross(tmpvec3, yUnitVec3, a); + } + vec3.normalize(tmpvec3, tmpvec3); + quat.fromAxisAngle(out, tmpvec3, Math.PI); + return out; + } else if (dot > 0.999999) { + out.x = 0; + out.y = 0; + out.z = 0; + out.w = 1; + return out; + } else { + vec3.cross(tmpvec3, a, b); + out.x = tmpvec3.x; + out.y = tmpvec3.y; + out.z = tmpvec3.z; + out.w = 1 + dot; + return quat.normalize(out, out); + } + }; +})(); + +/** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * fromAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {quat} q Quaternion to be decomposed + * @return {Number} Angle, in radians, of the rotation + */ +quat.getAxisAngle = function (out_axis, q) { + var rad = Math.acos(q.w) * 2.0; + var s = Math.sin(rad / 2.0); + if (s != 0.0) { + out_axis.x = q.x / s; + out_axis.y = q.y / s; + out_axis.z = q.z / s; + } else { + // If s is zero, return any axis (no rotation - axis does not matter) + out_axis.x = 1; + out_axis.y = 0; + out_axis.z = 0; + } + return rad; +}; + +/** + * Multiplies two quat's + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @returns {quat} out + */ +quat.multiply = function (out, a, b) { + var ax = a.x, ay = a.y, az = a.z, aw = a.w, + bx = b.x, by = b.y, bz = b.z, bw = b.w; + + out.x = ax * bw + aw * bx + ay * bz - az * by; + out.y = ay * bw + aw * by + az * bx - ax * bz; + out.z = az * bw + aw * bz + ax * by - ay * bx; + out.w = aw * bw - ax * bx - ay * by - az * bz; + return out; +}; + +/** + * Alias for {@link quat.multiply} + * @function + */ +quat.mul = quat.multiply; + +/** + * Scales a quat by a scalar number + * + * @param {quat} out the receiving vector + * @param {quat} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {quat} out + * @function + */ +quat.scale = vec4.scale; + +/** + * Rotates a quaternion by the given angle about the X axis + * + * @param {quat} out quat receiving operation result + * @param {quat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ +quat.rotateX = function (out, a, rad) { + rad *= 0.5; + + var ax = a.x, ay = a.y, az = a.z, aw = a.w, + bx = Math.sin(rad), bw = Math.cos(rad); + + out.x = ax * bw + aw * bx; + out.y = ay * bw + az * bx; + out.z = az * bw - ay * bx; + out.w = aw * bw - ax * bx; + return out; +}; + +/** + * Rotates a quaternion by the given angle about the Y axis + * + * @param {quat} out quat receiving operation result + * @param {quat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ +quat.rotateY = function (out, a, rad) { + rad *= 0.5; + + var ax = a.x, ay = a.y, az = a.z, aw = a.w, + by = Math.sin(rad), bw = Math.cos(rad); + + out.x = ax * bw - az * by; + out.y = ay * bw + aw * by; + out.z = az * bw + ax * by; + out.w = aw * bw - ay * by; + return out; +}; + +/** + * Rotates a quaternion by the given angle about the Z axis + * + * @param {quat} out quat receiving operation result + * @param {quat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ +quat.rotateZ = function (out, a, rad) { + rad *= 0.5; + + var ax = a.x, ay = a.y, az = a.z, aw = a.w, + bz = Math.sin(rad), bw = Math.cos(rad); + + out.x = ax * bw + ay * bz; + out.y = ay * bw - ax * bz; + out.z = az * bw + aw * bz; + out.w = aw * bw - az * bz; + return out; +}; + +/** + * Rotates a quaternion by the given angle about the axis in world space + * + * @param {quat} out quat receiving operation result + * @param {quat} rot quat to rotate + * @param {vec3} axis the axis around which to rotate in world space + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ +quat.rotateAround = (function () { + var v3_tmp = vec3.create(); + var q_tmp = quat.create(); + + return function (out, rot, axis, rad) { + // get inv-axis (local to rot) + quat.invert(q_tmp, rot); + vec3.transformQuat(v3_tmp, axis, q_tmp); + // rotate by inv-axis + quat.fromAxisAngle(q_tmp, v3_tmp, rad); + quat.mul(out, rot, q_tmp); + return out; }; - - /** - * Set the components of a mat23 to the given values - * - * @param {mat23} out the receiving matrix - * @param {Number} a Component A (index 0) - * @param {Number} b Component B (index 1) - * @param {Number} c Component C (index 2) - * @param {Number} d Component D (index 3) - * @param {Number} tx Component TX (index 4) - * @param {Number} ty Component TY (index 5) - * @returns {mat23} out - */ - mat23.set = function (out, a, b, c, d, tx, ty) { - out.m00 = a; - out.m01 = b; - out.m02 = c; - out.m03 = d; - out.m04 = tx; - out.m05 = ty; +})(); + +/** + * Rotates a quaternion by the given angle about the axis in local space + * + * @param {quat} out quat receiving operation result + * @param {quat} rot quat to rotate + * @param {vec3} axis the axis around which to rotate in local space + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ +quat.rotateAroundLocal = (function () { + var q_tmp = quat.create(); + + return function (out, rot, axis, rad) { + quat.fromAxisAngle(q_tmp, axis, rad); + quat.mul(out, rot, q_tmp); + return out; }; - - /** - * Inverts a mat23 - * - * @param {mat23} out the receiving matrix - * @param {mat23} a the source matrix - * @returns {mat23} out - */ - mat23.invert = function (out, a) { - var aa = a.m00, ab = a.m01, ac = a.m02, ad = a.m03, - atx = a.m04, aty = a.m05; - - var det = aa * ad - ab * ac; - if (!det) { +})(); + +/** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param {quat} out the receiving quaternion + * @param {quat} a quat to calculate W component of + * @returns {quat} out + */ +quat.calculateW = function (out, a) { + var x = a.x, y = a.y, z = a.z; + + out.x = x; + out.y = y; + out.z = z; + out.w = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z)); + return out; +}; + +/** + * Calculates the dot product of two quat's + * + * @param {quat} a the first operand + * @param {quat} b the second operand + * @returns {Number} dot product of a and b + * @function + */ +quat.dot = vec4.dot; + +/** + * Performs a linear interpolation between two quat's + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {quat} out + * @function + */ +quat.lerp = vec4.lerp; + +/** + * Performs a spherical linear interpolation between two quat + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {quat} out + */ +quat.slerp = function (out, a, b, t) { + // benchmarks: + // http://jsperf.com/quaternion-slerp-implementations + + var ax = a.x, ay = a.y, az = a.z, aw = a.w, + bx = b.x, by = b.y, bz = b.z, bw = b.w; + + var omega, cosom, sinom, scale0, scale1; + + // calc cosine + cosom = ax * bx + ay * by + az * bz + aw * bw; + // adjust signs (if necessary) + if (cosom < 0.0) { + cosom = -cosom; + bx = - bx; + by = - by; + bz = - bz; + bw = - bw; + } + // calculate coefficients + if ((1.0 - cosom) > 0.000001) { + // standard case (slerp) + omega = Math.acos(cosom); + sinom = Math.sin(omega); + scale0 = Math.sin((1.0 - t) * omega) / sinom; + scale1 = Math.sin(t * omega) / sinom; + } else { + // "from" and "to" quaternions are very close + // ... so we can do a linear interpolation + scale0 = 1.0 - t; + scale1 = t; + } + // calculate final values + out.x = scale0 * ax + scale1 * bx; + out.y = scale0 * ay + scale1 * by; + out.z = scale0 * az + scale1 * bz; + out.w = scale0 * aw + scale1 * bw; + + return out; +}; + +/** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {quat} c the third operand + * @param {quat} d the fourth operand + * @param {Number} t interpolation amount + * @returns {quat} out + */ +quat.sqlerp = (function () { + var temp1 = quat.create(); + var temp2 = quat.create(); + + return function (out, a, b, c, d, t) { + quat.slerp(temp1, a, d, t); + quat.slerp(temp2, b, c, t); + quat.slerp(out, temp1, temp2, 2 * t * (1 - t)); + + return out; + }; +}()); + +/** + * Calculates the inverse of a quat + * + * @param {quat} out the receiving quaternion + * @param {quat} a quat to calculate inverse of + * @returns {quat} out + */ +quat.invert = function (out, a) { + var a0 = a.x, a1 = a.y, a2 = a.z, a3 = a.w; + var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; + var invDot = dot ? 1.0 / dot : 0; + + // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 + + out.x = -a0 * invDot; + out.y = -a1 * invDot; + out.z = -a2 * invDot; + out.w = a3 * invDot; + return out; +}; + +/** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param {quat} out the receiving quaternion + * @param {quat} a quat to calculate conjugate of + * @returns {quat} out + */ +quat.conjugate = function (out, a) { + out.x = -a.x; + out.y = -a.y; + out.z = -a.z; + out.w = a.w; + return out; +}; + +/** + * Calculates the length of a quat + * + * @param {quat} a vector to calculate length of + * @returns {Number} length of a + * @function + */ +quat.length = vec4.length; + +/** + * Alias for {@link quat.length} + * @function + */ +quat.len = quat.length; + +/** + * Calculates the squared length of a quat + * + * @param {quat} a vector to calculate squared length of + * @returns {Number} squared length of a + * @function + */ +quat.squaredLength = vec4.squaredLength; + +/** + * Alias for {@link quat.squaredLength} + * @function + */ +quat.sqrLen = quat.squaredLength; + +/** + * Normalize a quat + * + * @param {quat} out the receiving quaternion + * @param {quat} a quaternion to normalize + * @returns {quat} out + * @function + */ +quat.normalize = vec4.normalize; + +/** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} xAxis the vector representing the local "right" direction + * @param {vec3} yAxis the vector representing the local "up" direction + * @param {vec3} zAxis the vector representing the viewing direction + * @returns {quat} out + */ +quat.fromAxes = (function () { + var matr = mat3.create(); + + return function (out, xAxis, yAxis, zAxis) { + mat3.set( + matr, + xAxis.x, xAxis.y, xAxis.z, + yAxis.x, yAxis.y, yAxis.z, + zAxis.x, zAxis.y, zAxis.z + ); + return quat.normalize(out, quat.fromMat3(out, matr)); + }; +})(); + +/** +* Calculates a quaternion from view direction and up direction +* +* @param {quat} out mat3 receiving operation result +* @param {vec3} view view direction (must be normalized) +* @param {vec3} [up] up direction, default is (0,1,0) (must be normalized) +* +* @returns {quat} out +*/ +quat.fromViewUp = (function () { + var matr = mat3.create(); + + return function (out, view, up) { + mat3.fromViewUp(matr, view, up); + if (!matr) { return null; } - det = 1.0 / det; - - out.m00 = ad * det; - out.m01 = -ab * det; - out.m02 = -ac * det; - out.m03 = aa * det; - out.m04 = (ac * aty - ad * atx) * det; - out.m05 = (ab * atx - aa * aty) * det; - return out; + + return quat.normalize(out, quat.fromMat3(out, matr)); }; - - /** - * Calculates the determinant of a mat23 - * - * @param {mat23} a the source matrix - * @returns {Number} determinant of a - */ - mat23.determinant = function (a) { - return a.m00 * a.m03 - a.m01 * a.m02; - }; - - /** - * Multiplies two mat23's - * - * @param {mat23} out the receiving matrix - * @param {mat23} a the first operand - * @param {mat23} b the second operand - * @returns {mat23} out - */ - mat23.multiply = function (out, a, b) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, - b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05; - out.m00 = a0 * b0 + a2 * b1; - out.m01 = a1 * b0 + a3 * b1; - out.m02 = a0 * b2 + a2 * b3; - out.m03 = a1 * b2 + a3 * b3; - out.m04 = a0 * b4 + a2 * b5 + a4; - out.m05 = a1 * b4 + a3 * b5 + a5; - return out; - }; - - /** - * Alias for {@link mat23.multiply} - * @function - */ - mat23.mul = mat23.multiply; - - /** - * Rotates a mat23 by the given angle - * - * @param {mat23} out the receiving matrix - * @param {mat23} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat23} out - */ - mat23.rotate = function (out, a, rad) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, +})(); + +/** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param {quat} out the receiving quaternion + * @param {vec3} axis the axis around which to rotate + * @param {Number} rad the angle in radians + * @returns {quat} out + **/ +quat.fromAxisAngle = function (out, axis, rad) { + rad = rad * 0.5; + var s = Math.sin(rad); + out.x = s * axis.x; + out.y = s * axis.y; + out.z = s * axis.z; + out.w = Math.cos(rad); + return out; +}; + +/** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param {quat} out the receiving quaternion + * @param {mat3} m rotation matrix + * @returns {quat} out + * @function + */ +quat.fromMat3 = function (out, m) { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + + var m00 = m.m00, m01 = m.m03, m02 = m.m06, + m10 = m.m01, m11 = m.m04, m12 = m.m07, + m20 = m.m02, m21 = m.m05, m22 = m.m08; + + var trace = m00 + m11 + m22; + + if (trace > 0) { + var s = 0.5 / Math.sqrt(trace + 1.0); + + out.w = 0.25 / s; + out.x = (m21 - m12) * s; + out.y = (m02 - m20) * s; + out.z = (m10 - m01) * s; + + } else if ((m00 > m11) && (m00 > m22)) { + var s$1 = 2.0 * Math.sqrt(1.0 + m00 - m11 - m22); + + out.w = (m21 - m12) / s$1; + out.x = 0.25 * s$1; + out.y = (m01 + m10) / s$1; + out.z = (m02 + m20) / s$1; + + } else if (m11 > m22) { + var s$2 = 2.0 * Math.sqrt(1.0 + m11 - m00 - m22); + + out.w = (m02 - m20) / s$2; + out.x = (m01 + m10) / s$2; + out.y = 0.25 * s$2; + out.z = (m12 + m21) / s$2; + + } else { + var s$3 = 2.0 * Math.sqrt(1.0 + m22 - m00 - m11); + + out.w = (m10 - m01) / s$3; + out.x = (m02 + m20) / s$3; + out.y = (m12 + m21) / s$3; + out.z = 0.25 * s$3; + } + + return out; +}; + +/** + * Creates a quaternion from the given euler angle x, y, z. + * + * @param {quat} out the receiving quaternion + * @param {x} Angle to rotate around X axis in degrees. + * @param {y} Angle to rotate around Y axis in degrees. + * @param {z} Angle to rotate around Z axis in degrees. + * @returns {quat} out + * @function + */ +quat.fromEuler = function (out, x, y, z) { + var halfToRad = 0.5 * Math.PI / 180.0; + x *= halfToRad; + y *= halfToRad; + z *= halfToRad; + + var sx = Math.sin(x); + var cx = Math.cos(x); + var sy = Math.sin(y); + var cy = Math.cos(y); + var sz = Math.sin(z); + var cz = Math.cos(z); + + out.x = sx * cy * cz - cx * sy * sz; + out.y = cx * sy * cz + sx * cy * sz; + out.z = cx * cy * sz - sx * sy * cz; + out.w = cx * cy * cz + sx * sy * sz; + + return out; +}; + +/** + * Returns a string representation of a quatenion + * + * @param {quat} a vector to represent as a string + * @returns {String} string representation of the vector + */ +quat.str = function (a) { + return ("quat(" + (a.x) + ", " + (a.y) + ", " + (a.z) + ", " + (a.w) + ")"); +}; + +/** + * Returns typed array + * + * @param {array} out + * @param {quat} q + * @returns {array} + */ +quat.array = function (out, q) { + out[0] = q.x; + out[1] = q.y; + out[2] = q.z; + out[3] = q.w; + + return out; +}; + +/** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {quat} a The first quaternion. + * @param {quat} b The second quaternion. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ +quat.exactEquals = vec4.exactEquals; + +/** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ +quat.equals = vec4.equals; + +var _tmp$5 = new Array(4); + +var _mat2 = function _mat2(m00, m01, m02, m03) { + this.m00 = m00; + this.m01 = m01; + this.m02 = m02; + this.m03 = m03; +}; + +_mat2.prototype.toJSON = function toJSON () { + _tmp$5[0] = this.m00; + _tmp$5[1] = this.m01; + _tmp$5[2] = this.m02; + _tmp$5[3] = this.m03; + + return _tmp$5; +}; + +/** + * @class 2x2 Matrix + * @name mat2 + */ +var mat2 = {}; + +/** + * Creates a new identity mat2 + * + * @returns {mat2} a new 2x2 matrix + */ +mat2.create = function() { + return new _mat2(1, 0, 0, 1); +}; + +/** + * Create a new mat2 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m10 Component in column 1, row 0 position (index 2) + * @param {Number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ +mat2.new = function (m00, m01, m10, m11) { + return new _mat2(m00, m01, m10, m11); +}; + +/** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param {mat2} a matrix to clone + * @returns {mat2} a new 2x2 matrix + */ +mat2.clone = function (a) { + return new _mat2(a.m00, a.m01, a.m02, a.m03); +}; + +/** + * Copy the values from one mat2 to another + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.copy = function (out, a) { + out.m00 = a.m00; + out.m01 = a.m01; + out.m02 = a.m02; + out.m03 = a.m03; + return out; +}; + +/** + * Set a mat2 to the identity matrix + * + * @param {mat2} out the receiving matrix + * @returns {mat2} out + */ +mat2.identity = function (out) { + out.m00 = 1; + out.m01 = 0; + out.m02 = 0; + out.m03 = 1; + return out; +}; + +/** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m10 Component in column 1, row 0 position (index 2) + * @param {Number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ +mat2.set = function (out, m00, m01, m10, m11) { + out.m00 = m00; + out.m01 = m01; + out.m02 = m10; + out.m03 = m11; + return out; +}; + + +/** + * Transpose the values of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.transpose = function (out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a1 = a.m01; + out.m01 = a.m02; + out.m02 = a1; + } else { + out.m00 = a.m00; + out.m01 = a.m02; + out.m02 = a.m01; + out.m03 = a.m03; + } + + return out; +}; + +/** + * Inverts a mat2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.invert = function (out, a) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03; + + // Calculate the determinant + var det = a0 * a3 - a2 * a1; + + if (!det) { + return null; + } + det = 1.0 / det; + + out.m00 = a3 * det; + out.m01 = -a1 * det; + out.m02 = -a2 * det; + out.m03 = a0 * det; + + return out; +}; + +/** + * Calculates the adjugate of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.adjoint = function (out, a) { + // Caching this value is nessecary if out == a + var a0 = a.m00; + out.m00 = a.m03; + out.m01 = -a.m01; + out.m02 = -a.m02; + out.m03 = a0; + + return out; +}; + +/** + * Calculates the determinant of a mat2 + * + * @param {mat2} a the source matrix + * @returns {Number} determinant of a + */ +mat2.determinant = function (a) { + return a.m00 * a.m03 - a.m02 * a.m01; +}; + +/** + * Multiplies two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ +mat2.multiply = function (out, a, b) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03; + var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03; + out.m00 = a0 * b0 + a2 * b1; + out.m01 = a1 * b0 + a3 * b1; + out.m02 = a0 * b2 + a2 * b3; + out.m03 = a1 * b2 + a3 * b3; + return out; +}; + +/** + * Alias for {@link mat2.multiply} + * @function + */ +mat2.mul = mat2.multiply; + +/** + * Rotates a mat2 by the given angle + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ +mat2.rotate = function (out, a, rad) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, s = Math.sin(rad), c = Math.cos(rad); - out.m00 = a0 * c + a2 * s; - out.m01 = a1 * c + a3 * s; - out.m02 = a0 * -s + a2 * c; - out.m03 = a1 * -s + a3 * c; - out.m04 = a4; - out.m05 = a5; - return out; - }; - - /** - * Scales the mat23 by the dimensions in the given vec2 - * - * @param {mat23} out the receiving matrix - * @param {mat23} a the matrix to translate - * @param {vec2} v the vec2 to scale the matrix by - * @returns {mat23} out - **/ - mat23.scale = function (out, a, v) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, + out.m00 = a0 * c + a2 * s; + out.m01 = a1 * c + a3 * s; + out.m02 = a0 * -s + a2 * c; + out.m03 = a1 * -s + a3 * c; + return out; +}; + +/** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to rotate + * @param {vec2} v the vec2 to scale the matrix by + * @returns {mat2} out + **/ +mat2.scale = function (out, a, v) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, v0 = v.x, v1 = v.y; - out.m00 = a0 * v0; - out.m01 = a1 * v0; - out.m02 = a2 * v1; - out.m03 = a3 * v1; - out.m04 = a4; - out.m05 = a5; - return out; - }; - - /** - * Translates the mat23 by the dimensions in the given vec2 - * - * @param {mat23} out the receiving matrix - * @param {mat23} a the matrix to translate - * @param {vec2} v the vec2 to translate the matrix by - * @returns {mat23} out - **/ - mat23.translate = function (out, a, v) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, - v0 = v.x, v1 = v.y; - out.m00 = a0; - out.m01 = a1; - out.m02 = a2; - out.m03 = a3; - out.m04 = a0 * v0 + a2 * v1 + a4; - out.m05 = a1 * v0 + a3 * v1 + a5; - return out; - }; - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat23.identity(dest); - * mat23.rotate(dest, dest, rad); - * - * @param {mat23} out mat23 receiving operation result - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat23} out - */ - mat23.fromRotation = function (out, rad) { - var s = Math.sin(rad), c = Math.cos(rad); - out.m00 = c; - out.m01 = s; - out.m02 = -s; - out.m03 = c; - out.m04 = 0; - out.m05 = 0; - return out; - }; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat23.identity(dest); - * mat23.scale(dest, dest, vec); - * - * @param {mat23} out mat23 receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat23} out - */ - mat23.fromScaling = function (out, v) { - out.m00 = v.m00; - out.m01 = 0; - out.m02 = 0; - out.m03 = v.m01; - out.m04 = 0; - out.m05 = 0; - return out; - }; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat23.identity(dest); - * mat23.translate(dest, dest, vec); - * - * @param {mat23} out mat23 receiving operation result - * @param {vec2} v Translation vector - * @returns {mat23} out - */ - mat23.fromTranslation = function (out, v) { - out.m00 = 1; - out.m01 = 0; - out.m02 = 0; - out.m03 = 1; - out.m04 = v.x; - out.m05 = v.y; - return out; - }; - - /** - * Returns a string representation of a mat23 - * - * @param {mat23} a matrix to represent as a string - * @returns {String} string representation of the matrix - */ - mat23.str = function (a) { - return ("mat23(" + (a.m00) + ", " + (a.m01) + ", " + (a.m02) + ", " + (a.m03) + ", " + (a.m04) + ", " + (a.m05) + ")"); - }; - - /** - * Returns typed array - * - * @param {array} out - * @param {mat23} m - * @returns {array} - */ - mat23.array = function (out, m) { - out[0] = m.m00; - out[1] = m.m01; - out[2] = m.m02; - out[3] = m.m03; - out[4] = m.m04; - out[5] = m.m05; - - return out; - }; - - /** - * Returns typed array to 16 float array - * - * @param {array} out - * @param {mat23} m - * @returns {array} - */ - mat23.array4x4 = function (out, m) { - out[0] = m.m00; - out[1] = m.m01; - out[2] = 0; - out[3] = 0; - out[4] = m.m02; - out[5] = m.m03; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = m.m04; - out[13] = m.m05; - out[14] = 0; - out[15] = 1; - - return out; - }; - - /** - * Returns Frobenius norm of a mat23 - * - * @param {mat23} a the matrix to calculate Frobenius norm of - * @returns {Number} Frobenius norm - */ - mat23.frob = function (a) { - return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + 1)); - }; - - /** - * Adds two mat23's - * - * @param {mat23} out the receiving matrix - * @param {mat23} a the first operand - * @param {mat23} b the second operand - * @returns {mat23} out - */ - mat23.add = function (out, a, b) { - out.m00 = a.m00 + b.m00; - out.m01 = a.m01 + b.m01; - out.m02 = a.m02 + b.m02; - out.m03 = a.m03 + b.m03; - out.m04 = a.m04 + b.m04; - out.m05 = a.m05 + b.m05; - return out; - }; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat23} out the receiving matrix - * @param {mat23} a the first operand - * @param {mat23} b the second operand - * @returns {mat23} out - */ - mat23.subtract = function (out, a, b) { - out.m00 = a.m00 - b.m00; - out.m01 = a.m01 - b.m01; - out.m02 = a.m02 - b.m02; - out.m03 = a.m03 - b.m03; - out.m04 = a.m04 - b.m04; - out.m05 = a.m05 - b.m05; - return out; - }; - - /** - * Alias for {@link mat23.subtract} - * @function - */ - mat23.sub = mat23.subtract; - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat23} out the receiving matrix - * @param {mat23} a the matrix to scale - * @param {Number} b amount to scale the matrix's elements by - * @returns {mat23} out - */ - mat23.multiplyScalar = function (out, a, b) { - out.m00 = a.m00 * b; - out.m01 = a.m01 * b; - out.m02 = a.m02 * b; - out.m03 = a.m03 * b; - out.m04 = a.m04 * b; - out.m05 = a.m05 * b; - return out; - }; - - /** - * Adds two mat23's after multiplying each element of the second operand by a scalar value. - * - * @param {mat23} out the receiving vector - * @param {mat23} a the first operand - * @param {mat23} b the second operand - * @param {Number} scale the amount to scale b's elements by before adding - * @returns {mat23} out - */ - mat23.multiplyScalarAndAdd = function (out, a, b, scale) { - out.m00 = a.m00 + (b.m00 * scale); - out.m01 = a.m01 + (b.m01 * scale); - out.m02 = a.m02 + (b.m02 * scale); - out.m03 = a.m03 + (b.m03 * scale); - out.m04 = a.m04 + (b.m04 * scale); - out.m05 = a.m05 + (b.m05 * scale); - return out; - }; - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat23} a The first matrix. - * @param {mat23} b The second matrix. - * @returns {Boolean} True if the matrices are equal, false otherwise. - */ - mat23.exactEquals = function (a, b) { - return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05; - }; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat23} a The first matrix. - * @param {mat23} b The second matrix. - * @returns {Boolean} True if the matrices are equal, false otherwise. - */ - mat23.equals = function (a, b) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05; - var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05; - return ( - Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && - Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && - Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && - Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && - Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && - Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) - ); - }; - - var _tmp$7 = new Array(16); - - var _mat4 = function _mat4( + out.m00 = a0 * v0; + out.m01 = a1 * v0; + out.m02 = a2 * v1; + out.m03 = a3 * v1; + return out; +}; + +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ +mat2.fromRotation = function (out, rad) { + var s = Math.sin(rad), + c = Math.cos(rad); + out.m00 = c; + out.m01 = s; + out.m02 = -s; + out.m03 = c; + return out; +}; + +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2} out + */ +mat2.fromScaling = function (out, v) { + out.m00 = v.x; + out.m01 = 0; + out.m02 = 0; + out.m03 = v.y; + return out; +}; + +/** + * Returns a string representation of a mat2 + * + * @param {mat2} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat2.str = function (a) { + return ("mat2(" + (a.m00) + ", " + (a.m01) + ", " + (a.m02) + ", " + (a.m03) + ")"); +}; + +/** + * Returns typed array + * + * @param {array} out + * @param {mat2} m + * @returns {array} + */ +mat2.array = function (out, m) { + out[0] = m.m00; + out[1] = m.m01; + out[2] = m.m02; + out[3] = m.m03; + + return out; +}; + +/** + * Returns Frobenius norm of a mat2 + * + * @param {mat2} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat2.frob = function (a) { + return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2))); +}; + +/** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param {mat2} L the lower triangular matrix + * @param {mat2} D the diagonal matrix + * @param {mat2} U the upper triangular matrix + * @param {mat2} a the input matrix to factorize + */ + +mat2.LDU = function (L, D, U, a) { + L.m02 = a.m02 / a.m00; + U.m00 = a.m00; + U.m01 = a.m01; + U.m03 = a.m03 - L.m02 * U.m01; +}; + +/** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ +mat2.add = function (out, a, b) { + out.m00 = a.m00 + b.m00; + out.m01 = a.m01 + b.m01; + out.m02 = a.m02 + b.m02; + out.m03 = a.m03 + b.m03; + return out; +}; + +/** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ +mat2.subtract = function (out, a, b) { + out.m00 = a.m00 - b.m00; + out.m01 = a.m01 - b.m01; + out.m02 = a.m02 - b.m02; + out.m03 = a.m03 - b.m03; + return out; +}; + +/** + * Alias for {@link mat2.subtract} + * @function + */ +mat2.sub = mat2.subtract; + +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ +mat2.exactEquals = function (a, b) { + return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03; +}; + +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ +mat2.equals = function (a, b) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03; + var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03; + return ( + Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && + Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && + Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && + Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) + ); +}; + +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ +mat2.multiplyScalar = function (out, a, b) { + out.m00 = a.m00 * b; + out.m01 = a.m01 * b; + out.m02 = a.m02 * b; + out.m03 = a.m03 * b; + return out; +}; + +/** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ +mat2.multiplyScalarAndAdd = function (out, a, b, scale) { + out.m00 = a.m00 + (b.m00 * scale); + out.m01 = a.m01 + (b.m01 * scale); + out.m02 = a.m02 + (b.m02 * scale); + out.m03 = a.m03 + (b.m03 * scale); + return out; +}; + +var _tmp$6 = new Array(6); + +var _mat23 = function _mat23(m00, m01, m02, m03, m04, m05) { + this.m00 = m00; + this.m01 = m01; + this.m02 = m02; + this.m03 = m03; + this.m04 = m04; + this.m05 = m05; +}; + +_mat23.prototype.toJSON = function toJSON () { + _tmp$6[0] = this.m00; + _tmp$6[1] = this.m01; + _tmp$6[2] = this.m02; + _tmp$6[3] = this.m03; + _tmp$6[4] = this.m04; + _tmp$6[5] = this.m05; + + return _tmp$6; +}; + +/** + * @class 2x3 Matrix + * @name mat23 + * + * @description + * A mat23 contains six elements defined as: + *
+ * [a, c, tx,
+ *  b, d, ty]
+ * 
+ * This is a short form for the 3x3 matrix: + *
+ * [a, c, tx,
+ *  b, d, ty,
+ *  0, 0, 1]
+ * 
+ * The last row is ignored so the array is shorter and operations are faster. + */ +var mat23 = {}; + +/** + * Creates a new identity mat23 + * + * @returns {mat23} a new 2x3 matrix + */ +mat23.create = function () { + return new _mat23( + 1, 0, + 0, 1, + 0, 0 + ); +}; + +/** + * Create a new mat23 with the given values + * + * @param {Number} a Component A (index 0) + * @param {Number} b Component B (index 1) + * @param {Number} c Component C (index 2) + * @param {Number} d Component D (index 3) + * @param {Number} tx Component TX (index 4) + * @param {Number} ty Component TY (index 5) + * @returns {mat23} A new mat23 + */ +mat23.new = function (a, b, c, d, tx, ty) { + return new _mat23( + a, b, + c, d, + tx, ty + ); +}; + +/** + * Creates a new mat23 initialized with values from an existing matrix + * + * @param {mat23} a matrix to clone + * @returns {mat23} a new 2x3 matrix + */ +mat23.clone = function (a) { + return new _mat23( + a.m00, a.m01, + a.m02, a.m03, + a.m04, a.m05 + ); +}; + +/** + * Copy the values from one mat23 to another + * + * @param {mat23} out the receiving matrix + * @param {mat23} a the source matrix + * @returns {mat23} out + */ +mat23.copy = function (out, a) { + out.m00 = a.m00; + out.m01 = a.m01; + out.m02 = a.m02; + out.m03 = a.m03; + out.m04 = a.m04; + out.m05 = a.m05; + return out; +}; + +/** + * Set a mat23 to the identity matrix + * + * @param {mat23} out the receiving matrix + * @returns {mat23} out + */ +mat23.identity = function (out) { + out.m00 = 1; + out.m01 = 0; + out.m02 = 0; + out.m03 = 1; + out.m04 = 0; + out.m05 = 0; + return out; +}; + +/** + * Set the components of a mat23 to the given values + * + * @param {mat23} out the receiving matrix + * @param {Number} a Component A (index 0) + * @param {Number} b Component B (index 1) + * @param {Number} c Component C (index 2) + * @param {Number} d Component D (index 3) + * @param {Number} tx Component TX (index 4) + * @param {Number} ty Component TY (index 5) + * @returns {mat23} out + */ +mat23.set = function (out, a, b, c, d, tx, ty) { + out.m00 = a; + out.m01 = b; + out.m02 = c; + out.m03 = d; + out.m04 = tx; + out.m05 = ty; + return out; +}; + +/** + * Inverts a mat23 + * + * @param {mat23} out the receiving matrix + * @param {mat23} a the source matrix + * @returns {mat23} out + */ +mat23.invert = function (out, a) { + var aa = a.m00, ab = a.m01, ac = a.m02, ad = a.m03, + atx = a.m04, aty = a.m05; + + var det = aa * ad - ab * ac; + if (!det) { + return null; + } + det = 1.0 / det; + + out.m00 = ad * det; + out.m01 = -ab * det; + out.m02 = -ac * det; + out.m03 = aa * det; + out.m04 = (ac * aty - ad * atx) * det; + out.m05 = (ab * atx - aa * aty) * det; + return out; +}; + +/** + * Calculates the determinant of a mat23 + * + * @param {mat23} a the source matrix + * @returns {Number} determinant of a + */ +mat23.determinant = function (a) { + return a.m00 * a.m03 - a.m01 * a.m02; +}; + +/** + * Multiplies two mat23's + * + * @param {mat23} out the receiving matrix + * @param {mat23} a the first operand + * @param {mat23} b the second operand + * @returns {mat23} out + */ +mat23.multiply = function (out, a, b) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, + b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05; + out.m00 = a0 * b0 + a2 * b1; + out.m01 = a1 * b0 + a3 * b1; + out.m02 = a0 * b2 + a2 * b3; + out.m03 = a1 * b2 + a3 * b3; + out.m04 = a0 * b4 + a2 * b5 + a4; + out.m05 = a1 * b4 + a3 * b5 + a5; + return out; +}; + +/** + * Alias for {@link mat23.multiply} + * @function + */ +mat23.mul = mat23.multiply; + +/** + * Rotates a mat23 by the given angle + * + * @param {mat23} out the receiving matrix + * @param {mat23} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat23} out + */ +mat23.rotate = function (out, a, rad) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, + s = Math.sin(rad), + c = Math.cos(rad); + out.m00 = a0 * c + a2 * s; + out.m01 = a1 * c + a3 * s; + out.m02 = a0 * -s + a2 * c; + out.m03 = a1 * -s + a3 * c; + out.m04 = a4; + out.m05 = a5; + return out; +}; + +/** + * Scales the mat23 by the dimensions in the given vec2 + * + * @param {mat23} out the receiving matrix + * @param {mat23} a the matrix to translate + * @param {vec2} v the vec2 to scale the matrix by + * @returns {mat23} out + **/ +mat23.scale = function (out, a, v) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, + v0 = v.x, v1 = v.y; + out.m00 = a0 * v0; + out.m01 = a1 * v0; + out.m02 = a2 * v1; + out.m03 = a3 * v1; + out.m04 = a4; + out.m05 = a5; + return out; +}; + +/** + * Translates the mat23 by the dimensions in the given vec2 + * + * @param {mat23} out the receiving matrix + * @param {mat23} a the matrix to translate + * @param {vec2} v the vec2 to translate the matrix by + * @returns {mat23} out + **/ +mat23.translate = function (out, a, v) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, + v0 = v.x, v1 = v.y; + out.m00 = a0; + out.m01 = a1; + out.m02 = a2; + out.m03 = a3; + out.m04 = a0 * v0 + a2 * v1 + a4; + out.m05 = a1 * v0 + a3 * v1 + a5; + return out; +}; + +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat23.identity(dest); + * mat23.rotate(dest, dest, rad); + * + * @param {mat23} out mat23 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat23} out + */ +mat23.fromRotation = function (out, rad) { + var s = Math.sin(rad), c = Math.cos(rad); + out.m00 = c; + out.m01 = s; + out.m02 = -s; + out.m03 = c; + out.m04 = 0; + out.m05 = 0; + return out; +}; + +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat23.identity(dest); + * mat23.scale(dest, dest, vec); + * + * @param {mat23} out mat23 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat23} out + */ +mat23.fromScaling = function (out, v) { + out.m00 = v.m00; + out.m01 = 0; + out.m02 = 0; + out.m03 = v.m01; + out.m04 = 0; + out.m05 = 0; + return out; +}; + +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat23.identity(dest); + * mat23.translate(dest, dest, vec); + * + * @param {mat23} out mat23 receiving operation result + * @param {vec2} v Translation vector + * @returns {mat23} out + */ +mat23.fromTranslation = function (out, v) { + out.m00 = 1; + out.m01 = 0; + out.m02 = 0; + out.m03 = 1; + out.m04 = v.x; + out.m05 = v.y; + return out; +}; + +/** + * Returns a string representation of a mat23 + * + * @param {mat23} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat23.str = function (a) { + return ("mat23(" + (a.m00) + ", " + (a.m01) + ", " + (a.m02) + ", " + (a.m03) + ", " + (a.m04) + ", " + (a.m05) + ")"); +}; + +/** + * Returns typed array + * + * @param {array} out + * @param {mat23} m + * @returns {array} + */ +mat23.array = function (out, m) { + out[0] = m.m00; + out[1] = m.m01; + out[2] = m.m02; + out[3] = m.m03; + out[4] = m.m04; + out[5] = m.m05; + + return out; +}; + +/** + * Returns typed array to 16 float array + * + * @param {array} out + * @param {mat23} m + * @returns {array} + */ +mat23.array4x4 = function (out, m) { + out[0] = m.m00; + out[1] = m.m01; + out[2] = 0; + out[3] = 0; + out[4] = m.m02; + out[5] = m.m03; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = m.m04; + out[13] = m.m05; + out[14] = 0; + out[15] = 1; + + return out; +}; + +/** + * Returns Frobenius norm of a mat23 + * + * @param {mat23} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat23.frob = function (a) { + return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + 1)); +}; + +/** + * Adds two mat23's + * + * @param {mat23} out the receiving matrix + * @param {mat23} a the first operand + * @param {mat23} b the second operand + * @returns {mat23} out + */ +mat23.add = function (out, a, b) { + out.m00 = a.m00 + b.m00; + out.m01 = a.m01 + b.m01; + out.m02 = a.m02 + b.m02; + out.m03 = a.m03 + b.m03; + out.m04 = a.m04 + b.m04; + out.m05 = a.m05 + b.m05; + return out; +}; + +/** + * Subtracts matrix b from matrix a + * + * @param {mat23} out the receiving matrix + * @param {mat23} a the first operand + * @param {mat23} b the second operand + * @returns {mat23} out + */ +mat23.subtract = function (out, a, b) { + out.m00 = a.m00 - b.m00; + out.m01 = a.m01 - b.m01; + out.m02 = a.m02 - b.m02; + out.m03 = a.m03 - b.m03; + out.m04 = a.m04 - b.m04; + out.m05 = a.m05 - b.m05; + return out; +}; + +/** + * Alias for {@link mat23.subtract} + * @function + */ +mat23.sub = mat23.subtract; + +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat23} out the receiving matrix + * @param {mat23} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat23} out + */ +mat23.multiplyScalar = function (out, a, b) { + out.m00 = a.m00 * b; + out.m01 = a.m01 * b; + out.m02 = a.m02 * b; + out.m03 = a.m03 * b; + out.m04 = a.m04 * b; + out.m05 = a.m05 * b; + return out; +}; + +/** + * Adds two mat23's after multiplying each element of the second operand by a scalar value. + * + * @param {mat23} out the receiving vector + * @param {mat23} a the first operand + * @param {mat23} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat23} out + */ +mat23.multiplyScalarAndAdd = function (out, a, b, scale) { + out.m00 = a.m00 + (b.m00 * scale); + out.m01 = a.m01 + (b.m01 * scale); + out.m02 = a.m02 + (b.m02 * scale); + out.m03 = a.m03 + (b.m03 * scale); + out.m04 = a.m04 + (b.m04 * scale); + out.m05 = a.m05 + (b.m05 * scale); + return out; +}; + +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat23} a The first matrix. + * @param {mat23} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ +mat23.exactEquals = function (a, b) { + return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05; +}; + +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat23} a The first matrix. + * @param {mat23} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ +mat23.equals = function (a, b) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05; + var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05; + return ( + Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && + Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && + Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && + Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && + Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && + Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) + ); +}; + +var _tmp$7 = new Array(16); + +var _mat4 = function _mat4( + m00, m01, m02, m03, + m04, m05, m06, m07, + m08, m09, m10, m11, + m12, m13, m14, m15 +) { + this.m00 = m00; + this.m01 = m01; + this.m02 = m02; + this.m03 = m03; + this.m04 = m04; + this.m05 = m05; + this.m06 = m06; + this.m07 = m07; + this.m08 = m08; + this.m09 = m09; + this.m10 = m10; + this.m11 = m11; + this.m12 = m12; + this.m13 = m13; + this.m14 = m14; + this.m15 = m15; +}; + +_mat4.prototype.toJSON = function toJSON () { + _tmp$7[0] = this.m00; + _tmp$7[1] = this.m01; + _tmp$7[2] = this.m02; + _tmp$7[3] = this.m03; + _tmp$7[4] = this.m04; + _tmp$7[5] = this.m05; + _tmp$7[6] = this.m06; + _tmp$7[7] = this.m07; + _tmp$7[8] = this.m08; + _tmp$7[9] = this.m09; + _tmp$7[10] = this.m10; + _tmp$7[11] = this.m11; + _tmp$7[12] = this.m12; + _tmp$7[13] = this.m13; + _tmp$7[14] = this.m14; + _tmp$7[15] = this.m15; + + return _tmp$7; +}; + +/** + * @class 4x4 Matrix + * @name mat4 + * + * NOTE: we use column-major matrix for all matrix calculation. + * + * This may lead to some confusion when referencing OpenGL documentation, + * however, which represents out all matricies in column-major format. + * This means that while in code a matrix may be typed out as: + * + * [1, 0, 0, 0, + * 0, 1, 0, 0, + * 0, 0, 1, 0, + * x, y, z, 0] + * + * The same matrix in the [OpenGL documentation](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml) + * is written as: + * + * 1 0 0 x + * 0 1 0 y + * 0 0 1 z + * 0 0 0 0 + * + * Please rest assured, however, that they are the same thing! + * This is not unique to glMatrix, either, as OpenGL developers have long been confused by the + * apparent lack of consistency between the memory layout and the documentation. + */ +var mat4 = {}; + +/** + * Creates a new identity mat4 + * + * @returns {mat4} a new 4x4 matrix + */ +mat4.create = function () { + return new _mat4( + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ); +}; + +/** + * Create a new mat4 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m03 Component in column 0, row 3 position (index 3) + * @param {Number} m10 Component in column 1, row 0 position (index 4) + * @param {Number} m11 Component in column 1, row 1 position (index 5) + * @param {Number} m12 Component in column 1, row 2 position (index 6) + * @param {Number} m13 Component in column 1, row 3 position (index 7) + * @param {Number} m20 Component in column 2, row 0 position (index 8) + * @param {Number} m21 Component in column 2, row 1 position (index 9) + * @param {Number} m22 Component in column 2, row 2 position (index 10) + * @param {Number} m23 Component in column 2, row 3 position (index 11) + * @param {Number} m30 Component in column 3, row 0 position (index 12) + * @param {Number} m31 Component in column 3, row 1 position (index 13) + * @param {Number} m32 Component in column 3, row 2 position (index 14) + * @param {Number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ +mat4.new = function (m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + return new _mat4( m00, m01, m02, m03, - m04, m05, m06, m07, - m08, m09, m10, m11, - m12, m13, m14, m15 - ) { - this.m00 = m00; - this.m01 = m01; - this.m02 = m02; - this.m03 = m03; - this.m04 = m04; - this.m05 = m05; - this.m06 = m06; - this.m07 = m07; - this.m08 = m08; - this.m09 = m09; - this.m10 = m10; - this.m11 = m11; - this.m12 = m12; - this.m13 = m13; - this.m14 = m14; - this.m15 = m15; - }; - - _mat4.prototype.toJSON = function toJSON () { - _tmp$7[0] = this.m00; - _tmp$7[1] = this.m01; - _tmp$7[2] = this.m02; - _tmp$7[3] = this.m03; - _tmp$7[4] = this.m04; - _tmp$7[5] = this.m05; - _tmp$7[6] = this.m06; - _tmp$7[7] = this.m07; - _tmp$7[8] = this.m08; - _tmp$7[9] = this.m09; - _tmp$7[10] = this.m10; - _tmp$7[11] = this.m11; - _tmp$7[12] = this.m12; - _tmp$7[13] = this.m13; - _tmp$7[14] = this.m14; - _tmp$7[15] = this.m15; - - return _tmp$7; - }; - - /** - * @class 4x4 Matrix - * @name mat4 - * - * NOTE: we use column-major matrix for all matrix calculation. - * - * This may lead to some confusion when referencing OpenGL documentation, - * however, which represents out all matricies in column-major format. - * This means that while in code a matrix may be typed out as: - * - * [1, 0, 0, 0, - * 0, 1, 0, 0, - * 0, 0, 1, 0, - * x, y, z, 0] - * - * The same matrix in the [OpenGL documentation](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml) - * is written as: - * - * 1 0 0 x - * 0 1 0 y - * 0 0 1 z - * 0 0 0 0 - * - * Please rest assured, however, that they are the same thing! - * This is not unique to glMatrix, either, as OpenGL developers have long been confused by the - * apparent lack of consistency between the memory layout and the documentation. - */ - var mat4 = {}; - - /** - * Creates a new identity mat4 - * - * @returns {mat4} a new 4x4 matrix - */ - mat4.create = function () { - return new _mat4( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ); - }; - - /** - * Create a new mat4 with the given values - * - * @param {Number} m00 Component in column 0, row 0 position (index 0) - * @param {Number} m01 Component in column 0, row 1 position (index 1) - * @param {Number} m02 Component in column 0, row 2 position (index 2) - * @param {Number} m03 Component in column 0, row 3 position (index 3) - * @param {Number} m10 Component in column 1, row 0 position (index 4) - * @param {Number} m11 Component in column 1, row 1 position (index 5) - * @param {Number} m12 Component in column 1, row 2 position (index 6) - * @param {Number} m13 Component in column 1, row 3 position (index 7) - * @param {Number} m20 Component in column 2, row 0 position (index 8) - * @param {Number} m21 Component in column 2, row 1 position (index 9) - * @param {Number} m22 Component in column 2, row 2 position (index 10) - * @param {Number} m23 Component in column 2, row 3 position (index 11) - * @param {Number} m30 Component in column 3, row 0 position (index 12) - * @param {Number} m31 Component in column 3, row 1 position (index 13) - * @param {Number} m32 Component in column 3, row 2 position (index 14) - * @param {Number} m33 Component in column 3, row 3 position (index 15) - * @returns {mat4} A new mat4 - */ - mat4.new = function (m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { - return new _mat4( - m00, m01, m02, m03, - m10, m11, m12, m13, - m20, m21, m22, m23, - m30, m31, m32, m33 - ); - }; - - /** - * Creates a new mat4 initialized with values from an existing matrix - * - * @param {mat4} a matrix to clone - * @returns {mat4} a new 4x4 matrix - */ - mat4.clone = function (a) { - return new _mat4( - a.m00, a.m01, a.m02, a.m03, - a.m04, a.m05, a.m06, a.m07, - a.m08, a.m09, a.m10, a.m11, - a.m12, a.m13, a.m14, a.m15 - ); - }; - - /** - * Copy the values from one mat4 to another - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the source matrix - * @returns {mat4} out - */ - mat4.copy = function (out, a) { + m10, m11, m12, m13, + m20, m21, m22, m23, + m30, m31, m32, m33 + ); +}; + +/** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param {mat4} a matrix to clone + * @returns {mat4} a new 4x4 matrix + */ +mat4.clone = function (a) { + return new _mat4( + a.m00, a.m01, a.m02, a.m03, + a.m04, a.m05, a.m06, a.m07, + a.m08, a.m09, a.m10, a.m11, + a.m12, a.m13, a.m14, a.m15 + ); +}; + +/** + * Copy the values from one mat4 to another + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.copy = function (out, a) { + out.m00 = a.m00; + out.m01 = a.m01; + out.m02 = a.m02; + out.m03 = a.m03; + out.m04 = a.m04; + out.m05 = a.m05; + out.m06 = a.m06; + out.m07 = a.m07; + out.m08 = a.m08; + out.m09 = a.m09; + out.m10 = a.m10; + out.m11 = a.m11; + out.m12 = a.m12; + out.m13 = a.m13; + out.m14 = a.m14; + out.m15 = a.m15; + return out; +}; + +/** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m03 Component in column 0, row 3 position (index 3) + * @param {Number} m10 Component in column 1, row 0 position (index 4) + * @param {Number} m11 Component in column 1, row 1 position (index 5) + * @param {Number} m12 Component in column 1, row 2 position (index 6) + * @param {Number} m13 Component in column 1, row 3 position (index 7) + * @param {Number} m20 Component in column 2, row 0 position (index 8) + * @param {Number} m21 Component in column 2, row 1 position (index 9) + * @param {Number} m22 Component in column 2, row 2 position (index 10) + * @param {Number} m23 Component in column 2, row 3 position (index 11) + * @param {Number} m30 Component in column 3, row 0 position (index 12) + * @param {Number} m31 Component in column 3, row 1 position (index 13) + * @param {Number} m32 Component in column 3, row 2 position (index 14) + * @param {Number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ +mat4.set = function (out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + out.m00 = m00; + out.m01 = m01; + out.m02 = m02; + out.m03 = m03; + out.m04 = m10; + out.m05 = m11; + out.m06 = m12; + out.m07 = m13; + out.m08 = m20; + out.m09 = m21; + out.m10 = m22; + out.m11 = m23; + out.m12 = m30; + out.m13 = m31; + out.m14 = m32; + out.m15 = m33; + return out; +}; + + +/** + * Set a mat4 to the identity matrix + * + * @param {mat4} out the receiving matrix + * @returns {mat4} out + */ +mat4.identity = function (out) { + out.m00 = 1; + out.m01 = 0; + out.m02 = 0; + out.m03 = 0; + out.m04 = 0; + out.m05 = 1; + out.m06 = 0; + out.m07 = 0; + out.m08 = 0; + out.m09 = 0; + out.m10 = 1; + out.m11 = 0; + out.m12 = 0; + out.m13 = 0; + out.m14 = 0; + out.m15 = 1; + return out; +}; + +/** + * Transpose the values of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.transpose = function (out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a.m01, a02 = a.m02, a03 = a.m03, + a12 = a.m06, a13 = a.m07, + a23 = a.m11; + + out.m01 = a.m04; + out.m02 = a.m08; + out.m03 = a.m12; + out.m04 = a01; + out.m06 = a.m09; + out.m07 = a.m13; + out.m08 = a02; + out.m09 = a12; + out.m11 = a.m14; + out.m12 = a03; + out.m13 = a13; + out.m14 = a23; + } else { + out.m00 = a.m00; + out.m01 = a.m04; + out.m02 = a.m08; + out.m03 = a.m12; + out.m04 = a.m01; + out.m05 = a.m05; + out.m06 = a.m09; + out.m07 = a.m13; + out.m08 = a.m02; + out.m09 = a.m06; + out.m10 = a.m10; + out.m11 = a.m14; + out.m12 = a.m03; + out.m13 = a.m07; + out.m14 = a.m11; + out.m15 = a.m15; + } + + return out; +}; + +/** + * Inverts a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.invert = function (out, a) { + var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, + a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, + a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, + a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; + + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + det = 1.0 / det; + + out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det; + + return out; +}; + +/** + * Calculates the adjugate of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.adjoint = function (out, a) { + var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, + a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, + a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, + a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; + + out.m00 = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22)); + out.m01 = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); + out.m02 = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12)); + out.m03 = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); + out.m04 = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); + out.m05 = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22)); + out.m06 = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); + out.m07 = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12)); + out.m08 = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21)); + out.m09 = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); + out.m10 = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11)); + out.m11 = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); + out.m12 = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); + out.m13 = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21)); + out.m14 = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); + out.m15 = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11)); + return out; +}; + +/** + * Calculates the determinant of a mat4 + * + * @param {mat4} a the source matrix + * @returns {Number} determinant of a + */ +mat4.determinant = function (a) { + var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, + a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, + a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, + a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; + + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; +}; + +/** + * Multiplies two mat4's explicitly + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ +mat4.multiply = function (out, a, b) { + var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, + a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, + a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, + a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; + + // Cache only the current line of the second matrix + var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03; + out.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b.m04; b1 = b.m05; b2 = b.m06; b3 = b.m07; + out.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b.m08; b1 = b.m09; b2 = b.m10; b3 = b.m11; + out.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b.m12; b1 = b.m13; b2 = b.m14; b3 = b.m15; + out.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + return out; +}; + +/** + * Alias for {@link mat4.multiply} + * @function + */ +mat4.mul = mat4.multiply; + +/** + * Translate a mat4 by the given vector + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to translate + * @param {vec3} v vector to translate by + * @returns {mat4} out + */ +mat4.translate = function (out, a, v) { + var x = v.x, y = v.y, z = v.z, + a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23; + + if (a === out) { + out.m12 = a.m00 * x + a.m04 * y + a.m08 * z + a.m12; + out.m13 = a.m01 * x + a.m05 * y + a.m09 * z + a.m13; + out.m14 = a.m02 * x + a.m06 * y + a.m10 * z + a.m14; + out.m15 = a.m03 * x + a.m07 * y + a.m11 * z + a.m15; + } else { + a00 = a.m00; a01 = a.m01; a02 = a.m02; a03 = a.m03; + a10 = a.m04; a11 = a.m05; a12 = a.m06; a13 = a.m07; + a20 = a.m08; a21 = a.m09; a22 = a.m10; a23 = a.m11; + + out.m00 = a00; out.m01 = a01; out.m02 = a02; out.m03 = a03; + out.m04 = a10; out.m05 = a11; out.m06 = a12; out.m07 = a13; + out.m08 = a20; out.m09 = a21; out.m10 = a22; out.m11 = a23; + + out.m12 = a00 * x + a10 * y + a20 * z + a.m12; + out.m13 = a01 * x + a11 * y + a21 * z + a.m13; + out.m14 = a02 * x + a12 * y + a22 * z + a.m14; + out.m15 = a03 * x + a13 * y + a23 * z + a.m15; + } + + return out; +}; + +/** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {vec3} v the vec3 to scale the matrix by + * @returns {mat4} out + **/ +mat4.scale = function (out, a, v) { + var x = v.x, y = v.y, z = v.z; + + out.m00 = a.m00 * x; + out.m01 = a.m01 * x; + out.m02 = a.m02 * x; + out.m03 = a.m03 * x; + out.m04 = a.m04 * y; + out.m05 = a.m05 * y; + out.m06 = a.m06 * y; + out.m07 = a.m07 * y; + out.m08 = a.m08 * z; + out.m09 = a.m09 * z; + out.m10 = a.m10 * z; + out.m11 = a.m11 * z; + out.m12 = a.m12; + out.m13 = a.m13; + out.m14 = a.m14; + out.m15 = a.m15; + return out; +}; + +/** + * Rotates a mat4 by the given angle around the given axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out + */ +mat4.rotate = function (out, a, rad, axis) { + var x = axis.x, y = axis.y, z = axis.z; + var s, c, t, + a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23, + b00, b01, b02, + b10, b11, b12, + b20, b21, b22; + + var len = Math.sqrt(x * x + y * y + z * z); + + if (Math.abs(len) < EPSILON) { + return null; + } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; + + a00 = a.m00; a01 = a.m01; a02 = a.m02; a03 = a.m03; + a10 = a.m04; a11 = a.m05; a12 = a.m06; a13 = a.m07; + a20 = a.m08; a21 = a.m09; a22 = a.m10; a23 = a.m11; + + // Construct the elements of the rotation matrix + b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s; + b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s; + b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c; + + // Perform rotation-specific matrix multiplication + out.m00 = a00 * b00 + a10 * b01 + a20 * b02; + out.m01 = a01 * b00 + a11 * b01 + a21 * b02; + out.m02 = a02 * b00 + a12 * b01 + a22 * b02; + out.m03 = a03 * b00 + a13 * b01 + a23 * b02; + out.m04 = a00 * b10 + a10 * b11 + a20 * b12; + out.m05 = a01 * b10 + a11 * b11 + a21 * b12; + out.m06 = a02 * b10 + a12 * b11 + a22 * b12; + out.m07 = a03 * b10 + a13 * b11 + a23 * b12; + out.m08 = a00 * b20 + a10 * b21 + a20 * b22; + out.m09 = a01 * b20 + a11 * b21 + a21 * b22; + out.m10 = a02 * b20 + a12 * b21 + a22 * b22; + out.m11 = a03 * b20 + a13 * b21 + a23 * b22; + + // If the source and destination differ, copy the unchanged last row + if (a !== out) { + out.m12 = a.m12; + out.m13 = a.m13; + out.m14 = a.m14; + out.m15 = a.m15; + } + + return out; +}; + +/** + * Rotates a matrix by the given angle around the X axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.rotateX = function (out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a10 = a.m04, + a11 = a.m05, + a12 = a.m06, + a13 = a.m07, + a20 = a.m08, + a21 = a.m09, + a22 = a.m10, + a23 = a.m11; + + if (a !== out) { // If the source and destination differ, copy the unchanged rows out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; out.m03 = a.m03; + out.m12 = a.m12; + out.m13 = a.m13; + out.m14 = a.m14; + out.m15 = a.m15; + } + + // Perform axis-specific matrix multiplication + out.m04 = a10 * c + a20 * s; + out.m05 = a11 * c + a21 * s; + out.m06 = a12 * c + a22 * s; + out.m07 = a13 * c + a23 * s; + out.m08 = a20 * c - a10 * s; + out.m09 = a21 * c - a11 * s; + out.m10 = a22 * c - a12 * s; + out.m11 = a23 * c - a13 * s; + + return out; +}; + +/** + * Rotates a matrix by the given angle around the Y axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.rotateY = function (out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a00 = a.m00, + a01 = a.m01, + a02 = a.m02, + a03 = a.m03, + a20 = a.m08, + a21 = a.m09, + a22 = a.m10, + a23 = a.m11; + + if (a !== out) { // If the source and destination differ, copy the unchanged rows out.m04 = a.m04; out.m05 = a.m05; out.m06 = a.m06; out.m07 = a.m07; + out.m12 = a.m12; + out.m13 = a.m13; + out.m14 = a.m14; + out.m15 = a.m15; + } + + // Perform axis-specific matrix multiplication + out.m00 = a00 * c - a20 * s; + out.m01 = a01 * c - a21 * s; + out.m02 = a02 * c - a22 * s; + out.m03 = a03 * c - a23 * s; + out.m08 = a00 * s + a20 * c; + out.m09 = a01 * s + a21 * c; + out.m10 = a02 * s + a22 * c; + out.m11 = a03 * s + a23 * c; + + return out; +}; + +/** + * Rotates a matrix by the given angle around the Z axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.rotateZ = function (out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a00 = a.m00, + a01 = a.m01, + a02 = a.m02, + a03 = a.m03, + a10 = a.m04, + a11 = a.m05, + a12 = a.m06, + a13 = a.m07; + + // If the source and destination differ, copy the unchanged last row + if (a !== out) { out.m08 = a.m08; out.m09 = a.m09; out.m10 = a.m10; @@ -5163,5011 +5698,4475 @@ var renderEngine = (function () { out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; - return out; - }; - - /** - * Set the components of a mat4 to the given values - * - * @param {mat4} out the receiving matrix - * @param {Number} m00 Component in column 0, row 0 position (index 0) - * @param {Number} m01 Component in column 0, row 1 position (index 1) - * @param {Number} m02 Component in column 0, row 2 position (index 2) - * @param {Number} m03 Component in column 0, row 3 position (index 3) - * @param {Number} m10 Component in column 1, row 0 position (index 4) - * @param {Number} m11 Component in column 1, row 1 position (index 5) - * @param {Number} m12 Component in column 1, row 2 position (index 6) - * @param {Number} m13 Component in column 1, row 3 position (index 7) - * @param {Number} m20 Component in column 2, row 0 position (index 8) - * @param {Number} m21 Component in column 2, row 1 position (index 9) - * @param {Number} m22 Component in column 2, row 2 position (index 10) - * @param {Number} m23 Component in column 2, row 3 position (index 11) - * @param {Number} m30 Component in column 3, row 0 position (index 12) - * @param {Number} m31 Component in column 3, row 1 position (index 13) - * @param {Number} m32 Component in column 3, row 2 position (index 14) - * @param {Number} m33 Component in column 3, row 3 position (index 15) - * @returns {mat4} out - */ - mat4.set = function (out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { - out.m00 = m00; - out.m01 = m01; - out.m02 = m02; - out.m03 = m03; - out.m04 = m10; - out.m05 = m11; - out.m06 = m12; - out.m07 = m13; - out.m08 = m20; - out.m09 = m21; - out.m10 = m22; - out.m11 = m23; - out.m12 = m30; - out.m13 = m31; - out.m14 = m32; - out.m15 = m33; - return out; - }; - - - /** - * Set a mat4 to the identity matrix - * - * @param {mat4} out the receiving matrix - * @returns {mat4} out - */ - mat4.identity = function (out) { - out.m00 = 1; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 0; - out.m05 = 1; - out.m06 = 0; - out.m07 = 0; - out.m08 = 0; - out.m09 = 0; - out.m10 = 1; - out.m11 = 0; - out.m12 = 0; - out.m13 = 0; - out.m14 = 0; - out.m15 = 1; - return out; - }; - - /** - * Transpose the values of a mat4 - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the source matrix - * @returns {mat4} out - */ - mat4.transpose = function (out, a) { - // If we are transposing ourselves we can skip a few steps but have to cache some values - if (out === a) { - var a01 = a.m01, a02 = a.m02, a03 = a.m03, - a12 = a.m06, a13 = a.m07, - a23 = a.m11; - - out.m01 = a.m04; - out.m02 = a.m08; - out.m03 = a.m12; - out.m04 = a01; - out.m06 = a.m09; - out.m07 = a.m13; - out.m08 = a02; - out.m09 = a12; - out.m11 = a.m14; - out.m12 = a03; - out.m13 = a13; - out.m14 = a23; - } else { - out.m00 = a.m00; - out.m01 = a.m04; - out.m02 = a.m08; - out.m03 = a.m12; - out.m04 = a.m01; - out.m05 = a.m05; - out.m06 = a.m09; - out.m07 = a.m13; - out.m08 = a.m02; - out.m09 = a.m06; - out.m10 = a.m10; - out.m11 = a.m14; - out.m12 = a.m03; - out.m13 = a.m07; - out.m14 = a.m11; - out.m15 = a.m15; - } - - return out; - }; - - /** - * Inverts a mat4 - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the source matrix - * @returns {mat4} out - */ - mat4.invert = function (out, a) { - var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, - a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, - a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, - a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; - - var b00 = a00 * a11 - a01 * a10; - var b01 = a00 * a12 - a02 * a10; - var b02 = a00 * a13 - a03 * a10; - var b03 = a01 * a12 - a02 * a11; - var b04 = a01 * a13 - a03 * a11; - var b05 = a02 * a13 - a03 * a12; - var b06 = a20 * a31 - a21 * a30; - var b07 = a20 * a32 - a22 * a30; - var b08 = a20 * a33 - a23 * a30; - var b09 = a21 * a32 - a22 * a31; - var b10 = a21 * a33 - a23 * a31; - var b11 = a22 * a33 - a23 * a32; - - // Calculate the determinant - var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - - if (!det) { - return null; - } - det = 1.0 / det; - - out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; - out.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det; - out.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det; - out.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det; - out.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det; - out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det; - out.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det; - out.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det; - out.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det; - out.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det; - out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det; - out.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det; - out.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det; - out.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det; - out.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det; - out.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det; - - return out; - }; - - /** - * Calculates the adjugate of a mat4 - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the source matrix - * @returns {mat4} out - */ - mat4.adjoint = function (out, a) { - var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, - a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, - a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, - a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; - - out.m00 = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22)); - out.m01 = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); - out.m02 = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12)); - out.m03 = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); - out.m04 = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); - out.m05 = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22)); - out.m06 = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); - out.m07 = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12)); - out.m08 = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21)); - out.m09 = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); - out.m10 = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11)); - out.m11 = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); - out.m12 = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); - out.m13 = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21)); - out.m14 = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); - out.m15 = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11)); - return out; - }; - - /** - * Calculates the determinant of a mat4 - * - * @param {mat4} a the source matrix - * @returns {Number} determinant of a - */ - mat4.determinant = function (a) { - var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, - a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, - a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, - a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; - - var b00 = a00 * a11 - a01 * a10; - var b01 = a00 * a12 - a02 * a10; - var b02 = a00 * a13 - a03 * a10; - var b03 = a01 * a12 - a02 * a11; - var b04 = a01 * a13 - a03 * a11; - var b05 = a02 * a13 - a03 * a12; - var b06 = a20 * a31 - a21 * a30; - var b07 = a20 * a32 - a22 * a30; - var b08 = a20 * a33 - a23 * a30; - var b09 = a21 * a32 - a22 * a31; - var b10 = a21 * a33 - a23 * a31; - var b11 = a22 * a33 - a23 * a32; - - // Calculate the determinant - return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - }; - - /** - * Multiplies two mat4's explicitly - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - mat4.multiply = function (out, a, b) { - var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, - a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, - a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, - a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; - - // Cache only the current line of the second matrix - var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03; - out.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - - b0 = b.m04; b1 = b.m05; b2 = b.m06; b3 = b.m07; - out.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - - b0 = b.m08; b1 = b.m09; b2 = b.m10; b3 = b.m11; - out.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - - b0 = b.m12; b1 = b.m13; b2 = b.m14; b3 = b.m15; - out.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - return out; - }; - - /** - * Alias for {@link mat4.multiply} - * @function - */ - mat4.mul = mat4.multiply; - - /** - * Translate a mat4 by the given vector - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to translate - * @param {vec3} v vector to translate by - * @returns {mat4} out - */ - mat4.translate = function (out, a, v) { - var x = v.x, y = v.y, z = v.z, - a00, a01, a02, a03, - a10, a11, a12, a13, - a20, a21, a22, a23; - - if (a === out) { - out.m12 = a.m00 * x + a.m04 * y + a.m08 * z + a.m12; - out.m13 = a.m01 * x + a.m05 * y + a.m09 * z + a.m13; - out.m14 = a.m02 * x + a.m06 * y + a.m10 * z + a.m14; - out.m15 = a.m03 * x + a.m07 * y + a.m11 * z + a.m15; - } else { - a00 = a.m00; a01 = a.m01; a02 = a.m02; a03 = a.m03; - a10 = a.m04; a11 = a.m05; a12 = a.m06; a13 = a.m07; - a20 = a.m08; a21 = a.m09; a22 = a.m10; a23 = a.m11; - - out.m00 = a00; out.m01 = a01; out.m02 = a02; out.m03 = a03; - out.m04 = a10; out.m05 = a11; out.m06 = a12; out.m07 = a13; - out.m08 = a20; out.m09 = a21; out.m10 = a22; out.m11 = a23; - - out.m12 = a00 * x + a10 * y + a20 * z + a.m12; - out.m13 = a01 * x + a11 * y + a21 * z + a.m13; - out.m14 = a02 * x + a12 * y + a22 * z + a.m14; - out.m15 = a03 * x + a13 * y + a23 * z + a.m15; - } - - return out; - }; - - /** - * Scales the mat4 by the dimensions in the given vec3 - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to scale - * @param {vec3} v the vec3 to scale the matrix by - * @returns {mat4} out - **/ - mat4.scale = function (out, a, v) { - var x = v.x, y = v.y, z = v.z; - - out.m00 = a.m00 * x; - out.m01 = a.m01 * x; - out.m02 = a.m02 * x; - out.m03 = a.m03 * x; - out.m04 = a.m04 * y; - out.m05 = a.m05 * y; - out.m06 = a.m06 * y; - out.m07 = a.m07 * y; - out.m08 = a.m08 * z; - out.m09 = a.m09 * z; - out.m10 = a.m10 * z; - out.m11 = a.m11 * z; - out.m12 = a.m12; - out.m13 = a.m13; - out.m14 = a.m14; - out.m15 = a.m15; - return out; - }; - - /** - * Rotates a mat4 by the given angle around the given axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @param {vec3} axis the axis to rotate around - * @returns {mat4} out - */ - mat4.rotate = function (out, a, rad, axis) { - var x = axis.x, y = axis.y, z = axis.z; - var s, c, t, - a00, a01, a02, a03, - a10, a11, a12, a13, - a20, a21, a22, a23, - b00, b01, b02, - b10, b11, b12, - b20, b21, b22; - - var len = Math.sqrt(x * x + y * y + z * z); - - if (Math.abs(len) < EPSILON) { - return null; - } - - len = 1 / len; - x *= len; - y *= len; - z *= len; - - s = Math.sin(rad); - c = Math.cos(rad); - t = 1 - c; - - a00 = a.m00; a01 = a.m01; a02 = a.m02; a03 = a.m03; - a10 = a.m04; a11 = a.m05; a12 = a.m06; a13 = a.m07; - a20 = a.m08; a21 = a.m09; a22 = a.m10; a23 = a.m11; - - // Construct the elements of the rotation matrix - b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s; - b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s; - b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c; - - // Perform rotation-specific matrix multiplication - out.m00 = a00 * b00 + a10 * b01 + a20 * b02; - out.m01 = a01 * b00 + a11 * b01 + a21 * b02; - out.m02 = a02 * b00 + a12 * b01 + a22 * b02; - out.m03 = a03 * b00 + a13 * b01 + a23 * b02; - out.m04 = a00 * b10 + a10 * b11 + a20 * b12; - out.m05 = a01 * b10 + a11 * b11 + a21 * b12; - out.m06 = a02 * b10 + a12 * b11 + a22 * b12; - out.m07 = a03 * b10 + a13 * b11 + a23 * b12; - out.m08 = a00 * b20 + a10 * b21 + a20 * b22; - out.m09 = a01 * b20 + a11 * b21 + a21 * b22; - out.m10 = a02 * b20 + a12 * b21 + a22 * b22; - out.m11 = a03 * b20 + a13 * b21 + a23 * b22; - - // If the source and destination differ, copy the unchanged last row - if (a !== out) { - out.m12 = a.m12; - out.m13 = a.m13; - out.m14 = a.m14; - out.m15 = a.m15; - } - - return out; - }; - - /** - * Rotates a matrix by the given angle around the X axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - mat4.rotateX = function (out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a10 = a.m04, - a11 = a.m05, - a12 = a.m06, - a13 = a.m07, - a20 = a.m08, - a21 = a.m09, - a22 = a.m10, - a23 = a.m11; - - if (a !== out) { // If the source and destination differ, copy the unchanged rows - out.m00 = a.m00; - out.m01 = a.m01; - out.m02 = a.m02; - out.m03 = a.m03; - out.m12 = a.m12; - out.m13 = a.m13; - out.m14 = a.m14; - out.m15 = a.m15; - } - - // Perform axis-specific matrix multiplication - out.m04 = a10 * c + a20 * s; - out.m05 = a11 * c + a21 * s; - out.m06 = a12 * c + a22 * s; - out.m07 = a13 * c + a23 * s; - out.m08 = a20 * c - a10 * s; - out.m09 = a21 * c - a11 * s; - out.m10 = a22 * c - a12 * s; - out.m11 = a23 * c - a13 * s; - - return out; - }; - - /** - * Rotates a matrix by the given angle around the Y axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - mat4.rotateY = function (out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a00 = a.m00, - a01 = a.m01, - a02 = a.m02, - a03 = a.m03, - a20 = a.m08, - a21 = a.m09, - a22 = a.m10, - a23 = a.m11; - - if (a !== out) { // If the source and destination differ, copy the unchanged rows - out.m04 = a.m04; - out.m05 = a.m05; - out.m06 = a.m06; - out.m07 = a.m07; - out.m12 = a.m12; - out.m13 = a.m13; - out.m14 = a.m14; - out.m15 = a.m15; - } - - // Perform axis-specific matrix multiplication - out.m00 = a00 * c - a20 * s; - out.m01 = a01 * c - a21 * s; - out.m02 = a02 * c - a22 * s; - out.m03 = a03 * c - a23 * s; - out.m08 = a00 * s + a20 * c; - out.m09 = a01 * s + a21 * c; - out.m10 = a02 * s + a22 * c; - out.m11 = a03 * s + a23 * c; - - return out; - }; - - /** - * Rotates a matrix by the given angle around the Z axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - mat4.rotateZ = function (out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a00 = a.m00, - a01 = a.m01, - a02 = a.m02, - a03 = a.m03, - a10 = a.m04, - a11 = a.m05, - a12 = a.m06, - a13 = a.m07; - - // If the source and destination differ, copy the unchanged last row - if (a !== out) { - out.m08 = a.m08; - out.m09 = a.m09; - out.m10 = a.m10; - out.m11 = a.m11; - out.m12 = a.m12; - out.m13 = a.m13; - out.m14 = a.m14; - out.m15 = a.m15; - } - - // Perform axis-specific matrix multiplication - out.m00 = a00 * c + a10 * s; - out.m01 = a01 * c + a11 * s; - out.m02 = a02 * c + a12 * s; - out.m03 = a03 * c + a13 * s; - out.m04 = a10 * c - a00 * s; - out.m05 = a11 * c - a01 * s; - out.m06 = a12 * c - a02 * s; - out.m07 = a13 * c - a03 * s; - - return out; - }; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, dest, vec); - * - * @param {mat4} out mat4 receiving operation result - * @param {vec3} v Translation vector - * @returns {mat4} out - */ - mat4.fromTranslation = function (out, v) { - out.m00 = 1; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 0; - out.m05 = 1; - out.m06 = 0; - out.m07 = 0; - out.m08 = 0; - out.m09 = 0; - out.m10 = 1; - out.m11 = 0; - out.m12 = v.x; - out.m13 = v.y; - out.m14 = v.z; - out.m15 = 1; - return out; - }; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.scale(dest, dest, vec); - * - * @param {mat4} out mat4 receiving operation result - * @param {vec3} v Scaling vector - * @returns {mat4} out - */ - mat4.fromScaling = function (out, v) { - out.m00 = v.x; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 0; - out.m05 = v.y; - out.m06 = 0; - out.m07 = 0; - out.m08 = 0; - out.m09 = 0; - out.m10 = v.z; - out.m11 = 0; - out.m12 = 0; - out.m13 = 0; - out.m14 = 0; - out.m15 = 1; - return out; - }; - - /** - * Creates a matrix from a given angle around a given axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotate(dest, dest, rad, axis); - * - * @param {mat4} out mat4 receiving operation result - * @param {Number} rad the angle to rotate the matrix by - * @param {vec3} axis the axis to rotate around - * @returns {mat4} out - */ - mat4.fromRotation = function (out, rad, axis) { - var x = axis.x, y = axis.y, z = axis.z; - var len = Math.sqrt(x * x + y * y + z * z); - var s, c, t; - - if (Math.abs(len) < EPSILON) { - return null; - } - - len = 1 / len; - x *= len; - y *= len; - z *= len; - - s = Math.sin(rad); - c = Math.cos(rad); - t = 1 - c; - - // Perform rotation-specific matrix multiplication - out.m00 = x * x * t + c; - out.m01 = y * x * t + z * s; - out.m02 = z * x * t - y * s; - out.m03 = 0; - out.m04 = x * y * t - z * s; - out.m05 = y * y * t + c; - out.m06 = z * y * t + x * s; - out.m07 = 0; - out.m08 = x * z * t + y * s; - out.m09 = y * z * t - x * s; - out.m10 = z * z * t + c; - out.m11 = 0; - out.m12 = 0; - out.m13 = 0; - out.m14 = 0; - out.m15 = 1; - return out; - }; - - /** - * Creates a matrix from the given angle around the X axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateX(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - mat4.fromXRotation = function (out, rad) { - var s = Math.sin(rad), - c = Math.cos(rad); - - // Perform axis-specific matrix multiplication - out.m00 = 1; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 0; - out.m05 = c; - out.m06 = s; - out.m07 = 0; - out.m08 = 0; - out.m09 = -s; - out.m10 = c; - out.m11 = 0; - out.m12 = 0; - out.m13 = 0; - out.m14 = 0; - out.m15 = 1; - return out; - }; - - /** - * Creates a matrix from the given angle around the Y axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateY(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - mat4.fromYRotation = function (out, rad) { - var s = Math.sin(rad), - c = Math.cos(rad); - - // Perform axis-specific matrix multiplication - out.m00 = c; - out.m01 = 0; - out.m02 = -s; - out.m03 = 0; - out.m04 = 0; - out.m05 = 1; - out.m06 = 0; - out.m07 = 0; - out.m08 = s; - out.m09 = 0; - out.m10 = c; - out.m11 = 0; - out.m12 = 0; - out.m13 = 0; - out.m14 = 0; - out.m15 = 1; - return out; - }; - - /** - * Creates a matrix from the given angle around the Z axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateZ(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - mat4.fromZRotation = function (out, rad) { - var s = Math.sin(rad), - c = Math.cos(rad); - - // Perform axis-specific matrix multiplication - out.m00 = c; - out.m01 = s; - out.m02 = 0; - out.m03 = 0; - out.m04 = -s; - out.m05 = c; - out.m06 = 0; - out.m07 = 0; - out.m08 = 0; - out.m09 = 0; - out.m10 = 1; - out.m11 = 0; - out.m12 = 0; - out.m13 = 0; - out.m14 = 0; - out.m15 = 1; - return out; - }; - - /** - * Creates a matrix from a quaternion rotation and vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * let quatMat = mat4.create(); - * quat.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Rotation quaternion - * @param {vec3} v Translation vector - * @returns {mat4} out - */ - mat4.fromRT = function (out, q, v) { - // Quaternion math - var x = q.x, y = q.y, z = q.z, w = q.w; - var x2 = x + x; - var y2 = y + y; - var z2 = z + z; - - var xx = x * x2; - var xy = x * y2; - var xz = x * z2; - var yy = y * y2; - var yz = y * z2; - var zz = z * z2; - var wx = w * x2; - var wy = w * y2; - var wz = w * z2; - - out.m00 = 1 - (yy + zz); - out.m01 = xy + wz; - out.m02 = xz - wy; - out.m03 = 0; - out.m04 = xy - wz; - out.m05 = 1 - (xx + zz); - out.m06 = yz + wx; - out.m07 = 0; - out.m08 = xz + wy; - out.m09 = yz - wx; - out.m10 = 1 - (xx + yy); - out.m11 = 0; - out.m12 = v.x; - out.m13 = v.y; - out.m14 = v.z; - out.m15 = 1; - - return out; - }; - - /** - * Returns the translation vector component of a transformation - * matrix. If a matrix is built with fromRT, - * the returned vector will be the same as the translation vector - * originally supplied. - * @param {vec3} out Vector to receive translation component - * @param {mat4} mat Matrix to be decomposed (input) - * @return {vec3} out - */ - mat4.getTranslation = function (out, mat) { - out.x = mat.m12; - out.y = mat.m13; - out.z = mat.m14; - - return out; - }; - - /** - * Returns the scaling factor component of a transformation - * matrix. If a matrix is built with fromRTS - * with a normalized Quaternion paramter, the returned vector will be - * the same as the scaling vector - * originally supplied. - * @param {vec3} out Vector to receive scaling factor component - * @param {mat4} mat Matrix to be decomposed (input) - * @return {vec3} out - */ - mat4.getScaling = function (out, mat) { - var m11 = mat.m00, - m12 = mat.m01, - m13 = mat.m02, - m21 = mat.m04, - m22 = mat.m05, - m23 = mat.m06, - m31 = mat.m08, - m32 = mat.m09, - m33 = mat.m10; - - out.x = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13); - out.y = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23); - out.z = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33); - - return out; - }; - - /** - * Returns a quaternion representing the rotational component - * of a transformation matrix. If a matrix is built with - * fromRT, the returned quaternion will be the - * same as the quaternion originally supplied. - * @param {quat} out Quaternion to receive the rotation component - * @param {mat4} mat Matrix to be decomposed (input) - * @return {quat} out - */ - mat4.getRotation = function (out, mat) { - // Algorithm taken from http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - var trace = mat.m00 + mat.m05 + mat.m10; - var S = 0; - - if (trace > 0) { - S = Math.sqrt(trace + 1.0) * 2; - out.w = 0.25 * S; - out.x = (mat.m06 - mat.m09) / S; - out.y = (mat.m08 - mat.m02) / S; - out.z = (mat.m01 - mat.m04) / S; - } else if ((mat.m00 > mat.m05) & (mat.m00 > mat.m10)) { - S = Math.sqrt(1.0 + mat.m00 - mat.m05 - mat.m10) * 2; - out.w = (mat.m06 - mat.m09) / S; - out.x = 0.25 * S; - out.y = (mat.m01 + mat.m04) / S; - out.z = (mat.m08 + mat.m02) / S; - } else if (mat.m05 > mat.m10) { - S = Math.sqrt(1.0 + mat.m05 - mat.m00 - mat.m10) * 2; - out.w = (mat.m08 - mat.m02) / S; - out.x = (mat.m01 + mat.m04) / S; - out.y = 0.25 * S; - out.z = (mat.m06 + mat.m09) / S; - } else { - S = Math.sqrt(1.0 + mat.m10 - mat.m00 - mat.m05) * 2; - out.w = (mat.m01 - mat.m04) / S; - out.x = (mat.m08 + mat.m02) / S; - out.y = (mat.m06 + mat.m09) / S; - out.z = 0.25 * S; - } - - return out; - }; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * let quatMat = mat4.create(); - * quat.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Rotation quaternion - * @param {vec3} v Translation vector - * @param {vec3} s Scaling vector - * @returns {mat4} out - */ - mat4.fromRTS = function (out, q, v, s) { - // Quaternion math - var x = q.x, y = q.y, z = q.z, w = q.w; - var x2 = x + x; - var y2 = y + y; - var z2 = z + z; - - var xx = x * x2; - var xy = x * y2; - var xz = x * z2; - var yy = y * y2; - var yz = y * z2; - var zz = z * z2; - var wx = w * x2; - var wy = w * y2; - var wz = w * z2; - var sx = s.x; - var sy = s.y; - var sz = s.z; - - out.m00 = (1 - (yy + zz)) * sx; - out.m01 = (xy + wz) * sx; - out.m02 = (xz - wy) * sx; - out.m03 = 0; - out.m04 = (xy - wz) * sy; - out.m05 = (1 - (xx + zz)) * sy; - out.m06 = (yz + wx) * sy; - out.m07 = 0; - out.m08 = (xz + wy) * sz; - out.m09 = (yz - wx) * sz; - out.m10 = (1 - (xx + yy)) * sz; - out.m11 = 0; - out.m12 = v.x; - out.m13 = v.y; - out.m14 = v.z; - out.m15 = 1; - - return out; - }; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * mat4.translate(dest, origin); - * let quatMat = mat4.create(); - * quat.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * mat4.translate(dest, negativeOrigin); - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Rotation quaternion - * @param {vec3} v Translation vector - * @param {vec3} s Scaling vector - * @param {vec3} o The origin vector around which to scale and rotate - * @returns {mat4} out - */ - mat4.fromRTSOrigin = function (out, q, v, s, o) { - // Quaternion math - var x = q.x, y = q.y, z = q.z, w = q.w; - var x2 = x + x; - var y2 = y + y; - var z2 = z + z; - - var xx = x * x2; - var xy = x * y2; - var xz = x * z2; - var yy = y * y2; - var yz = y * z2; - var zz = z * z2; - var wx = w * x2; - var wy = w * y2; - var wz = w * z2; - - var sx = s.x; - var sy = s.y; - var sz = s.z; - - var ox = o.x; - var oy = o.y; - var oz = o.z; - - out.m00 = (1 - (yy + zz)) * sx; - out.m01 = (xy + wz) * sx; - out.m02 = (xz - wy) * sx; - out.m03 = 0; - out.m04 = (xy - wz) * sy; - out.m05 = (1 - (xx + zz)) * sy; - out.m06 = (yz + wx) * sy; - out.m07 = 0; - out.m08 = (xz + wy) * sz; - out.m09 = (yz - wx) * sz; - out.m10 = (1 - (xx + yy)) * sz; - out.m11 = 0; - out.m12 = v.x + ox - (out.m00 * ox + out.m04 * oy + out.m08 * oz); - out.m13 = v.y + oy - (out.m01 * ox + out.m05 * oy + out.m09 * oz); - out.m14 = v.z + oz - (out.m02 * ox + out.m06 * oy + out.m10 * oz); - out.m15 = 1; - - return out; - }; - - /** - * Calculates a 4x4 matrix from the given quaternion - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Quaternion to create matrix from - * - * @returns {mat4} out - */ - mat4.fromQuat = function (out, q) { - var x = q.x, y = q.y, z = q.z, w = q.w; - var x2 = x + x; - var y2 = y + y; - var z2 = z + z; - - var xx = x * x2; - var yx = y * x2; - var yy = y * y2; - var zx = z * x2; - var zy = z * y2; - var zz = z * z2; - var wx = w * x2; - var wy = w * y2; - var wz = w * z2; - - out.m00 = 1 - yy - zz; - out.m01 = yx + wz; - out.m02 = zx - wy; - out.m03 = 0; - - out.m04 = yx - wz; - out.m05 = 1 - xx - zz; - out.m06 = zy + wx; - out.m07 = 0; - - out.m08 = zx + wy; - out.m09 = zy - wx; - out.m10 = 1 - xx - yy; - out.m11 = 0; - - out.m12 = 0; - out.m13 = 0; - out.m14 = 0; - out.m15 = 1; - - return out; - }; - - /** - * Generates a frustum matrix with the given bounds - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {Number} left Left bound of the frustum - * @param {Number} right Right bound of the frustum - * @param {Number} bottom Bottom bound of the frustum - * @param {Number} top Top bound of the frustum - * @param {Number} near Near bound of the frustum - * @param {Number} far Far bound of the frustum - * @returns {mat4} out - */ - mat4.frustum = function (out, left, right, bottom, top, near, far) { - var rl = 1 / (right - left); - var tb = 1 / (top - bottom); - var nf = 1 / (near - far); - - out.m00 = (near * 2) * rl; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 0; - out.m05 = (near * 2) * tb; - out.m06 = 0; - out.m07 = 0; - out.m08 = (right + left) * rl; - out.m09 = (top + bottom) * tb; - out.m10 = (far + near) * nf; - out.m11 = -1; - out.m12 = 0; - out.m13 = 0; - out.m14 = (far * near * 2) * nf; - out.m15 = 0; - return out; - }; - - /** - * Generates a perspective projection matrix with the given bounds - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {number} fovy Vertical field of view in radians - * @param {number} aspect Aspect ratio. typically viewport width/height - * @param {number} near Near bound of the frustum - * @param {number} far Far bound of the frustum - * @returns {mat4} out - */ - mat4.perspective = function (out, fovy, aspect, near, far) { - var f = 1.0 / Math.tan(fovy / 2); - var nf = 1 / (near - far); - - out.m00 = f / aspect; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 0; - out.m05 = f; - out.m06 = 0; - out.m07 = 0; - out.m08 = 0; - out.m09 = 0; - out.m10 = (far + near) * nf; - out.m11 = -1; - out.m12 = 0; - out.m13 = 0; - out.m14 = (2 * far * near) * nf; - out.m15 = 0; - return out; - }; - - /** - * Generates a perspective projection matrix with the given field of view. - * This is primarily useful for generating projection matrices to be used - * with the still experiemental WebVR API. - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees - * @param {number} near Near bound of the frustum - * @param {number} far Far bound of the frustum - * @returns {mat4} out - */ - mat4.perspectiveFromFieldOfView = function (out, fov, near, far) { - var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0); - var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0); - var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0); - var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0); - var xScale = 2.0 / (leftTan + rightTan); - var yScale = 2.0 / (upTan + downTan); - - out.m00 = xScale; - out.m01 = 0.0; - out.m02 = 0.0; - out.m03 = 0.0; - out.m04 = 0.0; - out.m05 = yScale; - out.m06 = 0.0; - out.m07 = 0.0; - out.m08 = -((leftTan - rightTan) * xScale * 0.5); - out.m09 = ((upTan - downTan) * yScale * 0.5); - out.m10 = far / (near - far); - out.m11 = -1.0; - out.m12 = 0.0; - out.m13 = 0.0; - out.m14 = (far * near) / (near - far); - out.m15 = 0.0; - return out; - }; - - /** - * Generates a orthogonal projection matrix with the given bounds - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {number} left Left bound of the frustum - * @param {number} right Right bound of the frustum - * @param {number} bottom Bottom bound of the frustum - * @param {number} top Top bound of the frustum - * @param {number} near Near bound of the frustum - * @param {number} far Far bound of the frustum - * @returns {mat4} out - */ - mat4.ortho = function (out, left, right, bottom, top, near, far) { - var lr = 1 / (left - right); - var bt = 1 / (bottom - top); - var nf = 1 / (near - far); - out.m00 = -2 * lr; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 0; - out.m05 = -2 * bt; - out.m06 = 0; - out.m07 = 0; - out.m08 = 0; - out.m09 = 0; - out.m10 = 2 * nf; - out.m11 = 0; - out.m12 = (left + right) * lr; - out.m13 = (top + bottom) * bt; - out.m14 = (far + near) * nf; - out.m15 = 1; - return out; - }; - - /** - * Generates a look-at matrix with the given eye position, focal point, and up axis - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {vec3} eye Position of the viewer - * @param {vec3} center Point the viewer is looking at - * @param {vec3} up vec3 pointing up - * @returns {mat4} out - */ - mat4.lookAt = function (out, eye, center, up) { - var x0, x1, x2, y0, y1, y2, z0, z1, z2, len; - var eyex = eye.x; - var eyey = eye.y; - var eyez = eye.z; - var upx = up.x; - var upy = up.y; - var upz = up.z; - var centerx = center.x; - var centery = center.y; - var centerz = center.z; - - if ( - Math.abs(eyex - centerx) < EPSILON && - Math.abs(eyey - centery) < EPSILON && - Math.abs(eyez - centerz) < EPSILON - ) { - return mat4.identity(out); - } - - z0 = eyex - centerx; - z1 = eyey - centery; - z2 = eyez - centerz; - - len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); - z0 *= len; - z1 *= len; - z2 *= len; - - x0 = upy * z2 - upz * z1; - x1 = upz * z0 - upx * z2; - x2 = upx * z1 - upy * z0; - len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); - if (!len) { - x0 = 0; - x1 = 0; - x2 = 0; - } else { - len = 1 / len; - x0 *= len; - x1 *= len; - x2 *= len; - } - - y0 = z1 * x2 - z2 * x1; - y1 = z2 * x0 - z0 * x2; - y2 = z0 * x1 - z1 * x0; - - len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); - if (!len) { - y0 = 0; - y1 = 0; - y2 = 0; - } else { - len = 1 / len; - y0 *= len; - y1 *= len; - y2 *= len; - } - - out.m00 = x0; - out.m01 = y0; - out.m02 = z0; - out.m03 = 0; - out.m04 = x1; - out.m05 = y1; - out.m06 = z1; - out.m07 = 0; - out.m08 = x2; - out.m09 = y2; - out.m10 = z2; - out.m11 = 0; - out.m12 = -(x0 * eyex + x1 * eyey + x2 * eyez); - out.m13 = -(y0 * eyex + y1 * eyey + y2 * eyez); - out.m14 = -(z0 * eyex + z1 * eyey + z2 * eyez); - out.m15 = 1; - - return out; - }; - - /** - * Returns a string representation of a mat4 - * - * @param {mat4} a matrix to represent as a string - * @returns {String} string representation of the matrix - */ - mat4.str = function (a) { - return ("mat4(" + (a.m00) + ", " + (a.m01) + ", " + (a.m02) + ", " + (a.m03) + ", " + (a.m04) + ", " + (a.m05) + ", " + (a.m06) + ", " + (a.m07) + ", " + (a.m08) + ", " + (a.m09) + ", " + (a.m10) + ", " + (a.m11) + ", " + (a.m12) + ", " + (a.m13) + ", " + (a.m14) + ", " + (a.m15) + ")"); - }; - - /** - * Returns typed array - * - * @param {array} out - * @param {mat4} m - * @returns {array} - */ - mat4.array = function (out, m) { - out[0] = m.m00; - out[1] = m.m01; - out[2] = m.m02; - out[3] = m.m03; - out[4] = m.m04; - out[5] = m.m05; - out[6] = m.m06; - out[7] = m.m07; - out[8] = m.m08; - out[9] = m.m09; - out[10] = m.m10; - out[11] = m.m11; - out[12] = m.m12; - out[13] = m.m13; - out[14] = m.m14; - out[15] = m.m15; - - return out; - }; - - /** - * Returns Frobenius norm of a mat4 - * - * @param {mat4} a the matrix to calculate Frobenius norm of - * @returns {Number} Frobenius norm - */ - mat4.frob = function (a) { - return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + Math.pow(a.m06, 2) + Math.pow(a.m07, 2) + Math.pow(a.m08, 2) + Math.pow(a.m09, 2) + Math.pow(a.m10, 2) + Math.pow(a.m11, 2) + Math.pow(a.m12, 2) + Math.pow(a.m13, 2) + Math.pow(a.m14, 2) + Math.pow(a.m15, 2))) - }; - - /** - * Adds two mat4's - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - mat4.add = function (out, a, b) { - out.m00 = a.m00 + b.m00; - out.m01 = a.m01 + b.m01; - out.m02 = a.m02 + b.m02; - out.m03 = a.m03 + b.m03; - out.m04 = a.m04 + b.m04; - out.m05 = a.m05 + b.m05; - out.m06 = a.m06 + b.m06; - out.m07 = a.m07 + b.m07; - out.m08 = a.m08 + b.m08; - out.m09 = a.m09 + b.m09; - out.m10 = a.m10 + b.m10; - out.m11 = a.m11 + b.m11; - out.m12 = a.m12 + b.m12; - out.m13 = a.m13 + b.m13; - out.m14 = a.m14 + b.m14; - out.m15 = a.m15 + b.m15; - return out; - }; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - mat4.subtract = function (out, a, b) { - out.m00 = a.m00 - b.m00; - out.m01 = a.m01 - b.m01; - out.m02 = a.m02 - b.m02; - out.m03 = a.m03 - b.m03; - out.m04 = a.m04 - b.m04; - out.m05 = a.m05 - b.m05; - out.m06 = a.m06 - b.m06; - out.m07 = a.m07 - b.m07; - out.m08 = a.m08 - b.m08; - out.m09 = a.m09 - b.m09; - out.m10 = a.m10 - b.m10; - out.m11 = a.m11 - b.m11; - out.m12 = a.m12 - b.m12; - out.m13 = a.m13 - b.m13; - out.m14 = a.m14 - b.m14; - out.m15 = a.m15 - b.m15; - return out; - }; - - /** - * Alias for {@link mat4.subtract} - * @function - */ - mat4.sub = mat4.subtract; - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to scale - * @param {Number} b amount to scale the matrix's elements by - * @returns {mat4} out - */ - mat4.multiplyScalar = function (out, a, b) { - out.m00 = a.m00 * b; - out.m01 = a.m01 * b; - out.m02 = a.m02 * b; - out.m03 = a.m03 * b; - out.m04 = a.m04 * b; - out.m05 = a.m05 * b; - out.m06 = a.m06 * b; - out.m07 = a.m07 * b; - out.m08 = a.m08 * b; - out.m09 = a.m09 * b; - out.m10 = a.m10 * b; - out.m11 = a.m11 * b; - out.m12 = a.m12 * b; - out.m13 = a.m13 * b; - out.m14 = a.m14 * b; - out.m15 = a.m15 * b; - return out; - }; - - /** - * Adds two mat4's after multiplying each element of the second operand by a scalar value. - * - * @param {mat4} out the receiving vector - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @param {Number} scale the amount to scale b's elements by before adding - * @returns {mat4} out - */ - mat4.multiplyScalarAndAdd = function (out, a, b, scale) { - out.m00 = a.m00 + (b.m00 * scale); - out.m01 = a.m01 + (b.m01 * scale); - out.m02 = a.m02 + (b.m02 * scale); - out.m03 = a.m03 + (b.m03 * scale); - out.m04 = a.m04 + (b.m04 * scale); - out.m05 = a.m05 + (b.m05 * scale); - out.m06 = a.m06 + (b.m06 * scale); - out.m07 = a.m07 + (b.m07 * scale); - out.m08 = a.m08 + (b.m08 * scale); - out.m09 = a.m09 + (b.m09 * scale); - out.m10 = a.m10 + (b.m10 * scale); - out.m11 = a.m11 + (b.m11 * scale); - out.m12 = a.m12 + (b.m12 * scale); - out.m13 = a.m13 + (b.m13 * scale); - out.m14 = a.m14 + (b.m14 * scale); - out.m15 = a.m15 + (b.m15 * scale); - return out; - }; - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat4} a The first matrix. - * @param {mat4} b The second matrix. - * @returns {Boolean} True if the matrices are equal, false otherwise. - */ - mat4.exactEquals = function (a, b) { - return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && - a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && - a.m08 === b.m08 && a.m09 === b.m09 && a.m10 === b.m10 && a.m11 === b.m11 && - a.m12 === b.m12 && a.m13 === b.m13 && a.m14 === b.m14 && a.m15 === b.m15; - }; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat4} a The first matrix. - * @param {mat4} b The second matrix. - * @returns {Boolean} True if the matrices are equal, false otherwise. - */ - mat4.equals = function (a, b) { - var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, - a4 = a.m04, a5 = a.m05, a6 = a.m06, a7 = a.m07, - a8 = a.m08, a9 = a.m09, a10 = a.m10, a11 = a.m11, - a12 = a.m12, a13 = a.m13, a14 = a.m14, a15 = a.m15; - - var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, - b4 = b.m04, b5 = b.m05, b6 = b.m06, b7 = b.m07, - b8 = b.m08, b9 = b.m09, b10 = b.m10, b11 = b.m11, - b12 = b.m12, b13 = b.m13, b14 = b.m14, b15 = b.m15; - - return ( - Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && - Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && - Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && - Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && - Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && - Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && - Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && - Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && - Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && - Math.abs(a9 - b9) <= EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && - Math.abs(a10 - b10) <= EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && - Math.abs(a11 - b11) <= EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && - Math.abs(a12 - b12) <= EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && - Math.abs(a13 - b13) <= EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && - Math.abs(a14 - b14) <= EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && - Math.abs(a15 - b15) <= EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15)) - ); - }; - - var _tmp$8 = new Array(3); - - var _color3 = function _color3(r, g, b) { - this.r = r; - this.g = g; - this.b = b; - }; - - _color3.prototype.toJSON = function toJSON () { - _tmp$8[0] = this.r; - _tmp$8[1] = this.g; - _tmp$8[2] = this.b; - - return _tmp$8; - }; - - /** - * @class Color - * @name color3 - */ - var color3 = {}; - - /** - * Creates a new color - * - * @returns {color3} a new color - */ - color3.create = function () { - return new _color3(1, 1, 1); - }; - - /** - * Creates a new color initialized with the given values - * - * @param {Number} r red component - * @param {Number} g green component - * @param {Number} b blue component - * @returns {color3} a new color - * @function - */ - color3.new = function (r, g, b) { - return new _color3(r, g, b); - }; - - /** - * Creates a new color initialized with values from an existing quaternion - * - * @param {color3} a color to clone - * @returns {color3} a new color - * @function - */ - color3.clone = function (a) { - return new _color3(a.r, a.g, a.b, a.a); - }; - - /** - * Copy the values from one color to another - * - * @param {color3} out the receiving color - * @param {color3} a the source color - * @returns {color3} out - * @function - */ - color3.copy = function (out, a) { - out.r = a.r; - out.g = a.g; - out.b = a.b; - return out; - }; - - /** - * Set the components of a color to the given values - * - * @param {color3} out the receiving color - * @param {Number} r red component - * @param {Number} g green component - * @param {Number} b blue component - * @returns {color3} out - * @function - */ - color3.set = function (out, r, g, b) { - out.r = r; - out.g = g; - out.b = b; - return out; - }; - - /** - * Set from hex - * - * @param {color3} out the receiving color - * @param {Number} hex - * @returns {color3} out - * @function - */ - color3.fromHex = function (out, hex) { - var r = ((hex >> 16)) / 255.0; - var g = ((hex >> 8) & 0xff) / 255.0; - var b = ((hex) & 0xff) / 255.0; - - out.r = r; - out.g = g; - out.b = b; - return out; - }; - - /** - * Adds two color's - * - * @param {color3} out the receiving color - * @param {color3} a the first operand - * @param {color3} b the second operand - * @returns {color3} out - * @function - */ - color3.add = function (out, a, b) { - out.r = a.r + b.r; - out.g = a.g + b.g; - out.b = a.b + b.b; - return out; - }; - - /** - * Subtracts color b from color a - * - * @param {color3} out the receiving color - * @param {color3} a the first operand - * @param {color3} b the second operand - * @returns {color3} out - */ - color3.subtract = function (out, a, b) { - out.r = a.r - b.r; - out.g = a.g - b.g; - out.b = a.b - b.b; - return out; - }; - - /** - * Alias for {@link color3.subtract} - * @function - */ - color3.sub = color3.subtract; - - /** - * Multiplies two color's - * - * @param {color3} out the receiving color - * @param {color3} a the first operand - * @param {color3} b the second operand - * @returns {color3} out - * @function - */ - color3.multiply = function (out, a, b) { - out.r = a.r * b.r; - out.g = a.g * b.g; - out.b = a.b * b.b; - return out; - }; - - /** - * Alias for {@link color3.multiply} - * @function - */ - color3.mul = color3.multiply; - - /** - * Divides two color's - * - * @param {color3} out the receiving vector - * @param {color3} a the first operand - * @param {color3} b the second operand - * @returns {color3} out - */ - color3.divide = function (out, a, b) { - out.r = a.r / b.r; - out.g = a.g / b.g; - out.b = a.b / b.b; - return out; - }; - - /** - * Alias for {@link color3.divide} - * @function - */ - color3.div = color3.divide; - - - /** - * Scales a color by a scalar number - * - * @param {color3} out the receiving vector - * @param {color3} a the vector to scale - * @param {Number} b amount to scale the vector by - * @returns {color3} out - * @function - */ - color3.scale = function (out, a, b) { - out.r = a.r * b; - out.g = a.g * b; - out.b = a.b * b; - return out; - }; - - /** - * Performs a linear interpolation between two color's - * - * @param {color3} out the receiving color - * @param {color3} a the first operand - * @param {color3} b the second operand - * @param {Number} t interpolation amount between the two inputs - * @returns {color3} out - * @function - */ - color3.lerp = function (out, a, b, t) { - var ar = a.r, - ag = a.g, - ab = a.b; - out.r = ar + t * (b.r - ar); - out.g = ag + t * (b.g - ag); - out.b = ab + t * (b.b - ab); - return out; - }; - - /** - * Returns a string representation of a color - * - * @param {color3} a vector to represent as a string - * @returns {String} string representation of the vector - */ - color3.str = function (a) { - return ("color3(" + (a.r) + ", " + (a.g) + ", " + (a.b) + ")"); - }; - - /** - * Returns typed array - * - * @param {array} out - * @param {color3} a - * @returns {array} - */ - color3.array = function (out, a) { - out[0] = a.r; - out[1] = a.g; - out[2] = a.b; - - return out; - }; - - /** - * Returns whether or not the color have exactly the same elements in the same position (when compared with ===) - * - * @param {color3} a The first color3. - * @param {color3} b The second color3. - * @returns {Boolean} True if the colors are equal, false otherwise. - */ - color3.exactEquals = function (a, b) { - return a.r === b.r && a.g === b.g && a.b === b.b; - }; - - /** - * Returns whether or not the colors have approximately the same elements in the same position. - * - * @param {color3} a The first color3. - * @param {color3} b The second color3. - * @returns {Boolean} True if the colors are equal, false otherwise. - */ - color3.equals = function (a, b) { - var a0 = a.r, a1 = a.g, a2 = a.b; - var b0 = b.r, b1 = b.g, b2 = b.b; - return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && - Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && - Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2))); - }; - - /** - * Returns the hex value - * - * @param {color3} a The color - * @returns {Number} - */ - color3.hex = function (a) { - return (a.r * 255) << 16 | (a.g * 255) << 8 | (a.b * 255); - }; - - var _tmp$9 = new Array(4); - - var _color4 = function _color4(r, g, b, a) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - }; - - _color4.prototype.toJSON = function toJSON () { - _tmp$9[0] = this.r; - _tmp$9[1] = this.g; - _tmp$9[2] = this.b; - _tmp$9[3] = this.a; - - return _tmp$9; - }; - - /** - * @class Color - * @name color4 - */ - var color4 = {}; - - /** - * Creates a new color - * - * @returns {color4} a new color - */ - color4.create = function () { - return new _color4(1, 1, 1, 1); - }; - - /** - * Creates a new color initialized with the given values - * - * @param {Number} r red component - * @param {Number} g green component - * @param {Number} b blue component - * @param {Number} a alpha component - * @returns {color4} a new color - * @function - */ - color4.new = function (r, g, b, a) { - return new _color4(r, g, b, a); - }; - - /** - * Creates a new color initialized with values from an existing quaternion - * - * @param {color4} a color to clone - * @returns {color4} a new color - * @function - */ - color4.clone = function (a) { - return new _color4(a.r, a.g, a.b, a.a); - }; - - /** - * Copy the values from one color to another - * - * @param {color4} out the receiving color - * @param {color4} a the source color - * @returns {color4} out - * @function - */ - color4.copy = function (out, a) { - out.r = a.r; - out.g = a.g; - out.b = a.b; - out.a = a.a; - return out; - }; - - /** - * Set the components of a color to the given values - * - * @param {color4} out the receiving color - * @param {Number} r red component - * @param {Number} g green component - * @param {Number} b blue component - * @param {Number} a alpha component - * @returns {color4} out - * @function - */ - color4.set = function (out, r, g, b, a) { - out.r = r; - out.g = g; - out.b = b; - out.a = a; - return out; - }; - - /** - * Set from hex - * - * @param {color4} out the receiving color - * @param {Number} hex - * @returns {color4} out - * @function - */ - color4.fromHex = function (out, hex) { - var r = ((hex >> 24)) / 255.0; - var g = ((hex >> 16) & 0xff) / 255.0; - var b = ((hex >> 8) & 0xff) / 255.0; - var a = ((hex) & 0xff) / 255.0; - - out.r = r; - out.g = g; - out.b = b; - out.a = a; - return out; - }; - - /** - * Adds two color's - * - * @param {color4} out the receiving color - * @param {color4} a the first operand - * @param {color4} b the second operand - * @returns {color4} out - * @function - */ - color4.add = function (out, a, b) { - out.r = a.r + b.r; - out.g = a.g + b.g; - out.b = a.b + b.b; - out.a = a.a + b.a; - return out; - }; - - /** - * Subtracts color b from color a - * - * @param {color4} out the receiving color - * @param {color4} a the first operand - * @param {color4} b the second operand - * @returns {color4} out - */ - color4.subtract = function (out, a, b) { - out.r = a.r - b.r; - out.g = a.g - b.g; - out.b = a.b - b.b; - out.a = a.a - b.a; - return out; - }; - - /** - * Alias for {@link color4.subtract} - * @function - */ - color4.sub = color4.subtract; - - /** - * Multiplies two color's - * - * @param {color4} out the receiving color - * @param {color4} a the first operand - * @param {color4} b the second operand - * @returns {color4} out - * @function - */ - color4.multiply = function (out, a, b) { - out.r = a.r * b.r; - out.g = a.g * b.g; - out.b = a.b * b.b; - out.a = a.a * b.a; - return out; - }; - - /** - * Alias for {@link color4.multiply} - * @function - */ - color4.mul = color4.multiply; - - /** - * Divides two color's - * - * @param {color4} out the receiving vector - * @param {color4} a the first operand - * @param {color4} b the second operand - * @returns {color4} out - */ - color4.divide = function (out, a, b) { - out.r = a.r / b.r; - out.g = a.g / b.g; - out.b = a.b / b.b; - out.a = a.a / b.a; - return out; - }; - - /** - * Alias for {@link color4.divide} - * @function - */ - color4.div = color4.divide; - - - /** - * Scales a color by a scalar number - * - * @param {color4} out the receiving vector - * @param {color4} a the vector to scale - * @param {Number} b amount to scale the vector by - * @returns {color4} out - * @function - */ - color4.scale = function (out, a, b) { - out.r = a.r * b; - out.g = a.g * b; - out.b = a.b * b; - out.a = a.a * b; - return out; - }; - - /** - * Performs a linear interpolation between two color's - * - * @param {color4} out the receiving color - * @param {color4} a the first operand - * @param {color4} b the second operand - * @param {Number} t interpolation amount between the two inputs - * @returns {color4} out - * @function - */ - color4.lerp = function (out, a, b, t) { - var ar = a.r, - ag = a.g, - ab = a.b, - aa = a.a; - out.r = ar + t * (b.r - ar); - out.g = ag + t * (b.g - ag); - out.b = ab + t * (b.b - ab); - out.a = aa + t * (b.a - aa); - return out; - }; - - /** - * Returns a string representation of a color - * - * @param {color4} a vector to represent as a string - * @returns {String} string representation of the vector - */ - color4.str = function (a) { - return ("color4(" + (a.r) + ", " + (a.g) + ", " + (a.b) + ", " + (a.a) + ")"); - }; - - /** - * Returns typed array - * - * @param {array} out - * @param {color4} a - * @returns {array} - */ - color4.array = function (out, a) { - out[0] = a.r; - out[1] = a.g; - out[2] = a.b; - out[3] = a.a; - - return out; - }; - - /** - * Returns whether or not the color have exactly the same elements in the same position (when compared with ===) - * - * @param {color4} a The first color4. - * @param {color4} b The second color4. - * @returns {Boolean} True if the colors are equal, false otherwise. - */ - color4.exactEquals = function (a, b) { - return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a; - }; - - /** - * Returns whether or not the colors have approximately the same elements in the same position. - * - * @param {color4} a The first color4. - * @param {color4} b The second color4. - * @returns {Boolean} True if the colors are equal, false otherwise. - */ - color4.equals = function (a, b) { - var a0 = a.r, a1 = a.g, a2 = a.b, a3 = a.a; - var b0 = b.r, b1 = b.g, b2 = b.b, b3 = b.a; - return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && - Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && - Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && - Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3))); - }; - - /** - * Returns the hex value - * - * @param {color4} a The color - * @returns {Number} - */ - color4.hex = function (a) { - return ((a.r * 255) << 24 | (a.g * 255) << 16 | (a.b * 255) << 8 | a.a * 255) >>> 0; - }; - - // NOTE: there is no syntax for: export {* as bits} from './lib/bits'; - var bits = bits_; - - - - var math = Object.freeze({ - bits: bits, - vec2: vec2, - vec3: vec3, - vec4: vec4, - quat: quat, - mat2: mat2, - mat23: mat23, - mat3: mat3, - mat4: mat4, - color3: color3, - color4: color4, - EPSILON: EPSILON, - equals: equals, - approx: approx, - clamp: clamp, - clamp01: clamp01, - lerp: lerp, - toRadian: toRadian, - toDegree: toDegree, - random: random, - randomRange: randomRange, - randomRangeInt: randomRangeInt, - nextPow2: nextPow2 - }); - - var renderer = window.renderer; - - var gfx = window.gfx; - - // reference: https://github.com/mziccard/node-timsort - - /** - * Default minimum size of a run. - */ - var DEFAULT_MIN_MERGE = 32; - - /** - * Minimum ordered subsequece required to do galloping. - */ - var DEFAULT_MIN_GALLOPING = 7; - - /** - * Default tmp storage length. Can increase depending on the size of the - * smallest run to merge. - */ - var DEFAULT_TMP_STORAGE_LENGTH = 256; - - /** - * Pre-computed powers of 10 for efficient lexicographic comparison of - * small integers. - */ - var POWERS_OF_TEN = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]; - - /** - * Estimate the logarithm base 10 of a small integer. - * - * @param {number} x - The integer to estimate the logarithm of. - * @return {number} - The estimated logarithm of the integer. - */ - function log10$1(x) { - if (x < 1e5) { - if (x < 1e2) { - return x < 1e1 ? 0 : 1; - } - - if (x < 1e4) { - return x < 1e3 ? 2 : 3; - } - - return 4; - } - - if (x < 1e7) { - return x < 1e6 ? 5 : 6; - } - - if (x < 1e9) { - return x < 1e8 ? 7 : 8; - } - - return 9; } - - /** - * Default alphabetical comparison of items. - * - * @param {string|object|number} a - First element to compare. - * @param {string|object|number} b - Second element to compare. - * @return {number} - A positive number if a.toString() > b.toString(), a - * negative number if .toString() < b.toString(), 0 otherwise. - */ - function alphabeticalCompare(a, b) { - if (a === b) { - return 0; + + // Perform axis-specific matrix multiplication + out.m00 = a00 * c + a10 * s; + out.m01 = a01 * c + a11 * s; + out.m02 = a02 * c + a12 * s; + out.m03 = a03 * c + a13 * s; + out.m04 = a10 * c - a00 * s; + out.m05 = a11 * c - a01 * s; + out.m06 = a12 * c - a02 * s; + out.m07 = a13 * c - a03 * s; + + return out; +}; + +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Translation vector + * @returns {mat4} out + */ +mat4.fromTranslation = function (out, v) { + out.m00 = 1; + out.m01 = 0; + out.m02 = 0; + out.m03 = 0; + out.m04 = 0; + out.m05 = 1; + out.m06 = 0; + out.m07 = 0; + out.m08 = 0; + out.m09 = 0; + out.m10 = 1; + out.m11 = 0; + out.m12 = v.x; + out.m13 = v.y; + out.m14 = v.z; + out.m15 = 1; + return out; +}; + +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Scaling vector + * @returns {mat4} out + */ +mat4.fromScaling = function (out, v) { + out.m00 = v.x; + out.m01 = 0; + out.m02 = 0; + out.m03 = 0; + out.m04 = 0; + out.m05 = v.y; + out.m06 = 0; + out.m07 = 0; + out.m08 = 0; + out.m09 = 0; + out.m10 = v.z; + out.m11 = 0; + out.m12 = 0; + out.m13 = 0; + out.m14 = 0; + out.m15 = 1; + return out; +}; + +/** + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out + */ +mat4.fromRotation = function (out, rad, axis) { + var x = axis.x, y = axis.y, z = axis.z; + var len = Math.sqrt(x * x + y * y + z * z); + var s, c, t; + + if (Math.abs(len) < EPSILON) { + return null; + } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; + + // Perform rotation-specific matrix multiplication + out.m00 = x * x * t + c; + out.m01 = y * x * t + z * s; + out.m02 = z * x * t - y * s; + out.m03 = 0; + out.m04 = x * y * t - z * s; + out.m05 = y * y * t + c; + out.m06 = z * y * t + x * s; + out.m07 = 0; + out.m08 = x * z * t + y * s; + out.m09 = y * z * t - x * s; + out.m10 = z * z * t + c; + out.m11 = 0; + out.m12 = 0; + out.m13 = 0; + out.m14 = 0; + out.m15 = 1; + return out; +}; + +/** + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.fromXRotation = function (out, rad) { + var s = Math.sin(rad), + c = Math.cos(rad); + + // Perform axis-specific matrix multiplication + out.m00 = 1; + out.m01 = 0; + out.m02 = 0; + out.m03 = 0; + out.m04 = 0; + out.m05 = c; + out.m06 = s; + out.m07 = 0; + out.m08 = 0; + out.m09 = -s; + out.m10 = c; + out.m11 = 0; + out.m12 = 0; + out.m13 = 0; + out.m14 = 0; + out.m15 = 1; + return out; +}; + +/** + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.fromYRotation = function (out, rad) { + var s = Math.sin(rad), + c = Math.cos(rad); + + // Perform axis-specific matrix multiplication + out.m00 = c; + out.m01 = 0; + out.m02 = -s; + out.m03 = 0; + out.m04 = 0; + out.m05 = 1; + out.m06 = 0; + out.m07 = 0; + out.m08 = s; + out.m09 = 0; + out.m10 = c; + out.m11 = 0; + out.m12 = 0; + out.m13 = 0; + out.m14 = 0; + out.m15 = 1; + return out; +}; + +/** + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.fromZRotation = function (out, rad) { + var s = Math.sin(rad), + c = Math.cos(rad); + + // Perform axis-specific matrix multiplication + out.m00 = c; + out.m01 = s; + out.m02 = 0; + out.m03 = 0; + out.m04 = -s; + out.m05 = c; + out.m06 = 0; + out.m07 = 0; + out.m08 = 0; + out.m09 = 0; + out.m10 = 1; + out.m11 = 0; + out.m12 = 0; + out.m13 = 0; + out.m14 = 0; + out.m15 = 1; + return out; +}; + +/** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * let quatMat = mat4.create(); + * quat.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Rotation quaternion + * @param {vec3} v Translation vector + * @returns {mat4} out + */ +mat4.fromRT = function (out, q, v) { + // Quaternion math + var x = q.x, y = q.y, z = q.z, w = q.w; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + + out.m00 = 1 - (yy + zz); + out.m01 = xy + wz; + out.m02 = xz - wy; + out.m03 = 0; + out.m04 = xy - wz; + out.m05 = 1 - (xx + zz); + out.m06 = yz + wx; + out.m07 = 0; + out.m08 = xz + wy; + out.m09 = yz - wx; + out.m10 = 1 - (xx + yy); + out.m11 = 0; + out.m12 = v.x; + out.m13 = v.y; + out.m14 = v.z; + out.m15 = 1; + + return out; +}; + +/** + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRT, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ +mat4.getTranslation = function (out, mat) { + out.x = mat.m12; + out.y = mat.m13; + out.z = mat.m14; + + return out; +}; + +/** + * Returns the scaling factor component of a transformation + * matrix. If a matrix is built with fromRTS + * with a normalized Quaternion paramter, the returned vector will be + * the same as the scaling vector + * originally supplied. + * @param {vec3} out Vector to receive scaling factor component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ +mat4.getScaling = function (out, mat) { + var m11 = mat.m00, + m12 = mat.m01, + m13 = mat.m02, + m21 = mat.m04, + m22 = mat.m05, + m23 = mat.m06, + m31 = mat.m08, + m32 = mat.m09, + m33 = mat.m10; + + out.x = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13); + out.y = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23); + out.z = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33); + + return out; +}; + +/** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRT, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ +mat4.getRotation = function (out, mat) { + // Algorithm taken from http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + var trace = mat.m00 + mat.m05 + mat.m10; + var S = 0; + + if (trace > 0) { + S = Math.sqrt(trace + 1.0) * 2; + out.w = 0.25 * S; + out.x = (mat.m06 - mat.m09) / S; + out.y = (mat.m08 - mat.m02) / S; + out.z = (mat.m01 - mat.m04) / S; + } else if ((mat.m00 > mat.m05) & (mat.m00 > mat.m10)) { + S = Math.sqrt(1.0 + mat.m00 - mat.m05 - mat.m10) * 2; + out.w = (mat.m06 - mat.m09) / S; + out.x = 0.25 * S; + out.y = (mat.m01 + mat.m04) / S; + out.z = (mat.m08 + mat.m02) / S; + } else if (mat.m05 > mat.m10) { + S = Math.sqrt(1.0 + mat.m05 - mat.m00 - mat.m10) * 2; + out.w = (mat.m08 - mat.m02) / S; + out.x = (mat.m01 + mat.m04) / S; + out.y = 0.25 * S; + out.z = (mat.m06 + mat.m09) / S; + } else { + S = Math.sqrt(1.0 + mat.m10 - mat.m00 - mat.m05) * 2; + out.w = (mat.m01 - mat.m04) / S; + out.x = (mat.m08 + mat.m02) / S; + out.y = (mat.m06 + mat.m09) / S; + out.z = 0.25 * S; + } + + return out; +}; + +/** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * let quatMat = mat4.create(); + * quat.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Rotation quaternion + * @param {vec3} v Translation vector + * @param {vec3} s Scaling vector + * @returns {mat4} out + */ +mat4.fromRTS = function (out, q, v, s) { + // Quaternion math + var x = q.x, y = q.y, z = q.z, w = q.w; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + var sx = s.x; + var sy = s.y; + var sz = s.z; + + out.m00 = (1 - (yy + zz)) * sx; + out.m01 = (xy + wz) * sx; + out.m02 = (xz - wy) * sx; + out.m03 = 0; + out.m04 = (xy - wz) * sy; + out.m05 = (1 - (xx + zz)) * sy; + out.m06 = (yz + wx) * sy; + out.m07 = 0; + out.m08 = (xz + wy) * sz; + out.m09 = (yz - wx) * sz; + out.m10 = (1 - (xx + yy)) * sz; + out.m11 = 0; + out.m12 = v.x; + out.m13 = v.y; + out.m14 = v.z; + out.m15 = 1; + + return out; +}; + +/** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * let quatMat = mat4.create(); + * quat.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Rotation quaternion + * @param {vec3} v Translation vector + * @param {vec3} s Scaling vector + * @param {vec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ +mat4.fromRTSOrigin = function (out, q, v, s, o) { + // Quaternion math + var x = q.x, y = q.y, z = q.z, w = q.w; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + + var sx = s.x; + var sy = s.y; + var sz = s.z; + + var ox = o.x; + var oy = o.y; + var oz = o.z; + + out.m00 = (1 - (yy + zz)) * sx; + out.m01 = (xy + wz) * sx; + out.m02 = (xz - wy) * sx; + out.m03 = 0; + out.m04 = (xy - wz) * sy; + out.m05 = (1 - (xx + zz)) * sy; + out.m06 = (yz + wx) * sy; + out.m07 = 0; + out.m08 = (xz + wy) * sz; + out.m09 = (yz - wx) * sz; + out.m10 = (1 - (xx + yy)) * sz; + out.m11 = 0; + out.m12 = v.x + ox - (out.m00 * ox + out.m04 * oy + out.m08 * oz); + out.m13 = v.y + oy - (out.m01 * ox + out.m05 * oy + out.m09 * oz); + out.m14 = v.z + oz - (out.m02 * ox + out.m06 * oy + out.m10 * oz); + out.m15 = 1; + + return out; +}; + +/** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ +mat4.fromQuat = function (out, q) { + var x = q.x, y = q.y, z = q.z, w = q.w; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + + var xx = x * x2; + var yx = y * x2; + var yy = y * y2; + var zx = z * x2; + var zy = z * y2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + + out.m00 = 1 - yy - zz; + out.m01 = yx + wz; + out.m02 = zx - wy; + out.m03 = 0; + + out.m04 = yx - wz; + out.m05 = 1 - xx - zz; + out.m06 = zy + wx; + out.m07 = 0; + + out.m08 = zx + wy; + out.m09 = zy - wx; + out.m10 = 1 - xx - yy; + out.m11 = 0; + + out.m12 = 0; + out.m13 = 0; + out.m14 = 0; + out.m15 = 1; + + return out; +}; + +/** + * Generates a frustum matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Number} left Left bound of the frustum + * @param {Number} right Right bound of the frustum + * @param {Number} bottom Bottom bound of the frustum + * @param {Number} top Top bound of the frustum + * @param {Number} near Near bound of the frustum + * @param {Number} far Far bound of the frustum + * @returns {mat4} out + */ +mat4.frustum = function (out, left, right, bottom, top, near, far) { + var rl = 1 / (right - left); + var tb = 1 / (top - bottom); + var nf = 1 / (near - far); + + out.m00 = (near * 2) * rl; + out.m01 = 0; + out.m02 = 0; + out.m03 = 0; + out.m04 = 0; + out.m05 = (near * 2) * tb; + out.m06 = 0; + out.m07 = 0; + out.m08 = (right + left) * rl; + out.m09 = (top + bottom) * tb; + out.m10 = (far + near) * nf; + out.m11 = -1; + out.m12 = 0; + out.m13 = 0; + out.m14 = (far * near * 2) * nf; + out.m15 = 0; + return out; +}; + +/** + * Generates a perspective projection matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ +mat4.perspective = function (out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2); + var nf = 1 / (near - far); + + out.m00 = f / aspect; + out.m01 = 0; + out.m02 = 0; + out.m03 = 0; + out.m04 = 0; + out.m05 = f; + out.m06 = 0; + out.m07 = 0; + out.m08 = 0; + out.m09 = 0; + out.m10 = (far + near) * nf; + out.m11 = -1; + out.m12 = 0; + out.m13 = 0; + out.m14 = (2 * far * near) * nf; + out.m15 = 0; + return out; +}; + +/** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experiemental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ +mat4.perspectiveFromFieldOfView = function (out, fov, near, far) { + var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0); + var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0); + var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0); + var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0); + var xScale = 2.0 / (leftTan + rightTan); + var yScale = 2.0 / (upTan + downTan); + + out.m00 = xScale; + out.m01 = 0.0; + out.m02 = 0.0; + out.m03 = 0.0; + out.m04 = 0.0; + out.m05 = yScale; + out.m06 = 0.0; + out.m07 = 0.0; + out.m08 = -((leftTan - rightTan) * xScale * 0.5); + out.m09 = ((upTan - downTan) * yScale * 0.5); + out.m10 = far / (near - far); + out.m11 = -1.0; + out.m12 = 0.0; + out.m13 = 0.0; + out.m14 = (far * near) / (near - far); + out.m15 = 0.0; + return out; +}; + +/** + * Generates a orthogonal projection matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} left Left bound of the frustum + * @param {number} right Right bound of the frustum + * @param {number} bottom Bottom bound of the frustum + * @param {number} top Top bound of the frustum + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ +mat4.ortho = function (out, left, right, bottom, top, near, far) { + var lr = 1 / (left - right); + var bt = 1 / (bottom - top); + var nf = 1 / (near - far); + out.m00 = -2 * lr; + out.m01 = 0; + out.m02 = 0; + out.m03 = 0; + out.m04 = 0; + out.m05 = -2 * bt; + out.m06 = 0; + out.m07 = 0; + out.m08 = 0; + out.m09 = 0; + out.m10 = 2 * nf; + out.m11 = 0; + out.m12 = (left + right) * lr; + out.m13 = (top + bottom) * bt; + out.m14 = (far + near) * nf; + out.m15 = 1; + return out; +}; + +/** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {vec3} eye Position of the viewer + * @param {vec3} center Point the viewer is looking at + * @param {vec3} up vec3 pointing up + * @returns {mat4} out + */ +mat4.lookAt = function (out, eye, center, up) { + var x0, x1, x2, y0, y1, y2, z0, z1, z2, len; + var eyex = eye.x; + var eyey = eye.y; + var eyez = eye.z; + var upx = up.x; + var upy = up.y; + var upz = up.z; + var centerx = center.x; + var centery = center.y; + var centerz = center.z; + + if ( + Math.abs(eyex - centerx) < EPSILON && + Math.abs(eyey - centery) < EPSILON && + Math.abs(eyez - centerz) < EPSILON + ) { + return mat4.identity(out); + } + + z0 = eyex - centerx; + z1 = eyey - centery; + z2 = eyez - centerz; + + len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + z0 *= len; + z1 *= len; + z2 *= len; + + x0 = upy * z2 - upz * z1; + x1 = upz * z0 - upx * z2; + x2 = upx * z1 - upy * z0; + len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + if (!len) { + x0 = 0; + x1 = 0; + x2 = 0; + } else { + len = 1 / len; + x0 *= len; + x1 *= len; + x2 *= len; + } + + y0 = z1 * x2 - z2 * x1; + y1 = z2 * x0 - z0 * x2; + y2 = z0 * x1 - z1 * x0; + + len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + if (!len) { + y0 = 0; + y1 = 0; + y2 = 0; + } else { + len = 1 / len; + y0 *= len; + y1 *= len; + y2 *= len; + } + + out.m00 = x0; + out.m01 = y0; + out.m02 = z0; + out.m03 = 0; + out.m04 = x1; + out.m05 = y1; + out.m06 = z1; + out.m07 = 0; + out.m08 = x2; + out.m09 = y2; + out.m10 = z2; + out.m11 = 0; + out.m12 = -(x0 * eyex + x1 * eyey + x2 * eyez); + out.m13 = -(y0 * eyex + y1 * eyey + y2 * eyez); + out.m14 = -(z0 * eyex + z1 * eyey + z2 * eyez); + out.m15 = 1; + + return out; +}; + +/** + * Returns a string representation of a mat4 + * + * @param {mat4} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat4.str = function (a) { + return ("mat4(" + (a.m00) + ", " + (a.m01) + ", " + (a.m02) + ", " + (a.m03) + ", " + (a.m04) + ", " + (a.m05) + ", " + (a.m06) + ", " + (a.m07) + ", " + (a.m08) + ", " + (a.m09) + ", " + (a.m10) + ", " + (a.m11) + ", " + (a.m12) + ", " + (a.m13) + ", " + (a.m14) + ", " + (a.m15) + ")"); +}; + +/** + * Returns typed array + * + * @param {array} out + * @param {mat4} m + * @returns {array} + */ +mat4.array = function (out, m) { + out[0] = m.m00; + out[1] = m.m01; + out[2] = m.m02; + out[3] = m.m03; + out[4] = m.m04; + out[5] = m.m05; + out[6] = m.m06; + out[7] = m.m07; + out[8] = m.m08; + out[9] = m.m09; + out[10] = m.m10; + out[11] = m.m11; + out[12] = m.m12; + out[13] = m.m13; + out[14] = m.m14; + out[15] = m.m15; + + return out; +}; + +/** + * Returns Frobenius norm of a mat4 + * + * @param {mat4} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat4.frob = function (a) { + return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + Math.pow(a.m06, 2) + Math.pow(a.m07, 2) + Math.pow(a.m08, 2) + Math.pow(a.m09, 2) + Math.pow(a.m10, 2) + Math.pow(a.m11, 2) + Math.pow(a.m12, 2) + Math.pow(a.m13, 2) + Math.pow(a.m14, 2) + Math.pow(a.m15, 2))) +}; + +/** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ +mat4.add = function (out, a, b) { + out.m00 = a.m00 + b.m00; + out.m01 = a.m01 + b.m01; + out.m02 = a.m02 + b.m02; + out.m03 = a.m03 + b.m03; + out.m04 = a.m04 + b.m04; + out.m05 = a.m05 + b.m05; + out.m06 = a.m06 + b.m06; + out.m07 = a.m07 + b.m07; + out.m08 = a.m08 + b.m08; + out.m09 = a.m09 + b.m09; + out.m10 = a.m10 + b.m10; + out.m11 = a.m11 + b.m11; + out.m12 = a.m12 + b.m12; + out.m13 = a.m13 + b.m13; + out.m14 = a.m14 + b.m14; + out.m15 = a.m15 + b.m15; + return out; +}; + +/** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ +mat4.subtract = function (out, a, b) { + out.m00 = a.m00 - b.m00; + out.m01 = a.m01 - b.m01; + out.m02 = a.m02 - b.m02; + out.m03 = a.m03 - b.m03; + out.m04 = a.m04 - b.m04; + out.m05 = a.m05 - b.m05; + out.m06 = a.m06 - b.m06; + out.m07 = a.m07 - b.m07; + out.m08 = a.m08 - b.m08; + out.m09 = a.m09 - b.m09; + out.m10 = a.m10 - b.m10; + out.m11 = a.m11 - b.m11; + out.m12 = a.m12 - b.m12; + out.m13 = a.m13 - b.m13; + out.m14 = a.m14 - b.m14; + out.m15 = a.m15 - b.m15; + return out; +}; + +/** + * Alias for {@link mat4.subtract} + * @function + */ +mat4.sub = mat4.subtract; + +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ +mat4.multiplyScalar = function (out, a, b) { + out.m00 = a.m00 * b; + out.m01 = a.m01 * b; + out.m02 = a.m02 * b; + out.m03 = a.m03 * b; + out.m04 = a.m04 * b; + out.m05 = a.m05 * b; + out.m06 = a.m06 * b; + out.m07 = a.m07 * b; + out.m08 = a.m08 * b; + out.m09 = a.m09 * b; + out.m10 = a.m10 * b; + out.m11 = a.m11 * b; + out.m12 = a.m12 * b; + out.m13 = a.m13 * b; + out.m14 = a.m14 * b; + out.m15 = a.m15 * b; + return out; +}; + +/** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ +mat4.multiplyScalarAndAdd = function (out, a, b, scale) { + out.m00 = a.m00 + (b.m00 * scale); + out.m01 = a.m01 + (b.m01 * scale); + out.m02 = a.m02 + (b.m02 * scale); + out.m03 = a.m03 + (b.m03 * scale); + out.m04 = a.m04 + (b.m04 * scale); + out.m05 = a.m05 + (b.m05 * scale); + out.m06 = a.m06 + (b.m06 * scale); + out.m07 = a.m07 + (b.m07 * scale); + out.m08 = a.m08 + (b.m08 * scale); + out.m09 = a.m09 + (b.m09 * scale); + out.m10 = a.m10 + (b.m10 * scale); + out.m11 = a.m11 + (b.m11 * scale); + out.m12 = a.m12 + (b.m12 * scale); + out.m13 = a.m13 + (b.m13 * scale); + out.m14 = a.m14 + (b.m14 * scale); + out.m15 = a.m15 + (b.m15 * scale); + return out; +}; + +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ +mat4.exactEquals = function (a, b) { + return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && + a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && + a.m08 === b.m08 && a.m09 === b.m09 && a.m10 === b.m10 && a.m11 === b.m11 && + a.m12 === b.m12 && a.m13 === b.m13 && a.m14 === b.m14 && a.m15 === b.m15; +}; + +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ +mat4.equals = function (a, b) { + var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, + a4 = a.m04, a5 = a.m05, a6 = a.m06, a7 = a.m07, + a8 = a.m08, a9 = a.m09, a10 = a.m10, a11 = a.m11, + a12 = a.m12, a13 = a.m13, a14 = a.m14, a15 = a.m15; + + var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, + b4 = b.m04, b5 = b.m05, b6 = b.m06, b7 = b.m07, + b8 = b.m08, b9 = b.m09, b10 = b.m10, b11 = b.m11, + b12 = b.m12, b13 = b.m13, b14 = b.m14, b15 = b.m15; + + return ( + Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && + Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && + Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && + Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && + Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && + Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && + Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && + Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && + Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && + Math.abs(a9 - b9) <= EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && + Math.abs(a10 - b10) <= EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && + Math.abs(a11 - b11) <= EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && + Math.abs(a12 - b12) <= EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && + Math.abs(a13 - b13) <= EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && + Math.abs(a14 - b14) <= EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && + Math.abs(a15 - b15) <= EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15)) + ); +}; + +var _tmp$8 = new Array(3); + +var _color3 = function _color3(r, g, b) { + this.r = r; + this.g = g; + this.b = b; +}; + +_color3.prototype.toJSON = function toJSON () { + _tmp$8[0] = this.r; + _tmp$8[1] = this.g; + _tmp$8[2] = this.b; + + return _tmp$8; +}; + +/** + * @class Color + * @name color3 + */ +var color3 = {}; + +/** + * Creates a new color + * + * @returns {color3} a new color + */ +color3.create = function () { + return new _color3(1, 1, 1); +}; + +/** + * Creates a new color initialized with the given values + * + * @param {Number} r red component + * @param {Number} g green component + * @param {Number} b blue component + * @returns {color3} a new color + * @function + */ +color3.new = function (r, g, b) { + return new _color3(r, g, b); +}; + +/** + * Creates a new color initialized with values from an existing quaternion + * + * @param {color3} a color to clone + * @returns {color3} a new color + * @function + */ +color3.clone = function (a) { + return new _color3(a.r, a.g, a.b, a.a); +}; + +/** + * Copy the values from one color to another + * + * @param {color3} out the receiving color + * @param {color3} a the source color + * @returns {color3} out + * @function + */ +color3.copy = function (out, a) { + out.r = a.r; + out.g = a.g; + out.b = a.b; + return out; +}; + +/** + * Set the components of a color to the given values + * + * @param {color3} out the receiving color + * @param {Number} r red component + * @param {Number} g green component + * @param {Number} b blue component + * @returns {color3} out + * @function + */ +color3.set = function (out, r, g, b) { + out.r = r; + out.g = g; + out.b = b; + return out; +}; + +/** + * Set from hex + * + * @param {color3} out the receiving color + * @param {Number} hex + * @returns {color3} out + * @function + */ +color3.fromHex = function (out, hex) { + var r = ((hex >> 16)) / 255.0; + var g = ((hex >> 8) & 0xff) / 255.0; + var b = ((hex) & 0xff) / 255.0; + + out.r = r; + out.g = g; + out.b = b; + return out; +}; + +/** + * Adds two color's + * + * @param {color3} out the receiving color + * @param {color3} a the first operand + * @param {color3} b the second operand + * @returns {color3} out + * @function + */ +color3.add = function (out, a, b) { + out.r = a.r + b.r; + out.g = a.g + b.g; + out.b = a.b + b.b; + return out; +}; + +/** + * Subtracts color b from color a + * + * @param {color3} out the receiving color + * @param {color3} a the first operand + * @param {color3} b the second operand + * @returns {color3} out + */ +color3.subtract = function (out, a, b) { + out.r = a.r - b.r; + out.g = a.g - b.g; + out.b = a.b - b.b; + return out; +}; + +/** + * Alias for {@link color3.subtract} + * @function + */ +color3.sub = color3.subtract; + +/** + * Multiplies two color's + * + * @param {color3} out the receiving color + * @param {color3} a the first operand + * @param {color3} b the second operand + * @returns {color3} out + * @function + */ +color3.multiply = function (out, a, b) { + out.r = a.r * b.r; + out.g = a.g * b.g; + out.b = a.b * b.b; + return out; +}; + +/** + * Alias for {@link color3.multiply} + * @function + */ +color3.mul = color3.multiply; + +/** + * Divides two color's + * + * @param {color3} out the receiving vector + * @param {color3} a the first operand + * @param {color3} b the second operand + * @returns {color3} out + */ +color3.divide = function (out, a, b) { + out.r = a.r / b.r; + out.g = a.g / b.g; + out.b = a.b / b.b; + return out; +}; + +/** + * Alias for {@link color3.divide} + * @function + */ +color3.div = color3.divide; + + +/** + * Scales a color by a scalar number + * + * @param {color3} out the receiving vector + * @param {color3} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {color3} out + * @function + */ +color3.scale = function (out, a, b) { + out.r = a.r * b; + out.g = a.g * b; + out.b = a.b * b; + return out; +}; + +/** + * Performs a linear interpolation between two color's + * + * @param {color3} out the receiving color + * @param {color3} a the first operand + * @param {color3} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {color3} out + * @function + */ +color3.lerp = function (out, a, b, t) { + var ar = a.r, + ag = a.g, + ab = a.b; + out.r = ar + t * (b.r - ar); + out.g = ag + t * (b.g - ag); + out.b = ab + t * (b.b - ab); + return out; +}; + +/** + * Returns a string representation of a color + * + * @param {color3} a vector to represent as a string + * @returns {String} string representation of the vector + */ +color3.str = function (a) { + return ("color3(" + (a.r) + ", " + (a.g) + ", " + (a.b) + ")"); +}; + +/** + * Returns typed array + * + * @param {array} out + * @param {color3} a + * @returns {array} + */ +color3.array = function (out, a) { + out[0] = a.r; + out[1] = a.g; + out[2] = a.b; + + return out; +}; + +/** + * Returns whether or not the color have exactly the same elements in the same position (when compared with ===) + * + * @param {color3} a The first color3. + * @param {color3} b The second color3. + * @returns {Boolean} True if the colors are equal, false otherwise. + */ +color3.exactEquals = function (a, b) { + return a.r === b.r && a.g === b.g && a.b === b.b; +}; + +/** + * Returns whether or not the colors have approximately the same elements in the same position. + * + * @param {color3} a The first color3. + * @param {color3} b The second color3. + * @returns {Boolean} True if the colors are equal, false otherwise. + */ +color3.equals = function (a, b) { + var a0 = a.r, a1 = a.g, a2 = a.b; + var b0 = b.r, b1 = b.g, b2 = b.b; + return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && + Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && + Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2))); +}; + +/** + * Returns the hex value + * + * @param {color3} a The color + * @returns {Number} + */ +color3.hex = function (a) { + return (a.r * 255) << 16 | (a.g * 255) << 8 | (a.b * 255); +}; + +var _tmp$9 = new Array(4); + +var _color4 = function _color4(r, g, b, a) { + this.r = r; + this.g = g; + this.b = b; + this.a = a; +}; + +_color4.prototype.toJSON = function toJSON () { + _tmp$9[0] = this.r; + _tmp$9[1] = this.g; + _tmp$9[2] = this.b; + _tmp$9[3] = this.a; + + return _tmp$9; +}; + +/** + * @class Color + * @name color4 + */ +var color4 = {}; + +/** + * Creates a new color + * + * @returns {color4} a new color + */ +color4.create = function () { + return new _color4(1, 1, 1, 1); +}; + +/** + * Creates a new color initialized with the given values + * + * @param {Number} r red component + * @param {Number} g green component + * @param {Number} b blue component + * @param {Number} a alpha component + * @returns {color4} a new color + * @function + */ +color4.new = function (r, g, b, a) { + return new _color4(r, g, b, a); +}; + +/** + * Creates a new color initialized with values from an existing quaternion + * + * @param {color4} a color to clone + * @returns {color4} a new color + * @function + */ +color4.clone = function (a) { + return new _color4(a.r, a.g, a.b, a.a); +}; + +/** + * Copy the values from one color to another + * + * @param {color4} out the receiving color + * @param {color4} a the source color + * @returns {color4} out + * @function + */ +color4.copy = function (out, a) { + out.r = a.r; + out.g = a.g; + out.b = a.b; + out.a = a.a; + return out; +}; + +/** + * Set the components of a color to the given values + * + * @param {color4} out the receiving color + * @param {Number} r red component + * @param {Number} g green component + * @param {Number} b blue component + * @param {Number} a alpha component + * @returns {color4} out + * @function + */ +color4.set = function (out, r, g, b, a) { + out.r = r; + out.g = g; + out.b = b; + out.a = a; + return out; +}; + +/** + * Set from hex + * + * @param {color4} out the receiving color + * @param {Number} hex + * @returns {color4} out + * @function + */ +color4.fromHex = function (out, hex) { + var r = ((hex >> 24)) / 255.0; + var g = ((hex >> 16) & 0xff) / 255.0; + var b = ((hex >> 8) & 0xff) / 255.0; + var a = ((hex) & 0xff) / 255.0; + + out.r = r; + out.g = g; + out.b = b; + out.a = a; + return out; +}; + +/** + * Adds two color's + * + * @param {color4} out the receiving color + * @param {color4} a the first operand + * @param {color4} b the second operand + * @returns {color4} out + * @function + */ +color4.add = function (out, a, b) { + out.r = a.r + b.r; + out.g = a.g + b.g; + out.b = a.b + b.b; + out.a = a.a + b.a; + return out; +}; + +/** + * Subtracts color b from color a + * + * @param {color4} out the receiving color + * @param {color4} a the first operand + * @param {color4} b the second operand + * @returns {color4} out + */ +color4.subtract = function (out, a, b) { + out.r = a.r - b.r; + out.g = a.g - b.g; + out.b = a.b - b.b; + out.a = a.a - b.a; + return out; +}; + +/** + * Alias for {@link color4.subtract} + * @function + */ +color4.sub = color4.subtract; + +/** + * Multiplies two color's + * + * @param {color4} out the receiving color + * @param {color4} a the first operand + * @param {color4} b the second operand + * @returns {color4} out + * @function + */ +color4.multiply = function (out, a, b) { + out.r = a.r * b.r; + out.g = a.g * b.g; + out.b = a.b * b.b; + out.a = a.a * b.a; + return out; +}; + +/** + * Alias for {@link color4.multiply} + * @function + */ +color4.mul = color4.multiply; + +/** + * Divides two color's + * + * @param {color4} out the receiving vector + * @param {color4} a the first operand + * @param {color4} b the second operand + * @returns {color4} out + */ +color4.divide = function (out, a, b) { + out.r = a.r / b.r; + out.g = a.g / b.g; + out.b = a.b / b.b; + out.a = a.a / b.a; + return out; +}; + +/** + * Alias for {@link color4.divide} + * @function + */ +color4.div = color4.divide; + + +/** + * Scales a color by a scalar number + * + * @param {color4} out the receiving vector + * @param {color4} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {color4} out + * @function + */ +color4.scale = function (out, a, b) { + out.r = a.r * b; + out.g = a.g * b; + out.b = a.b * b; + out.a = a.a * b; + return out; +}; + +/** + * Performs a linear interpolation between two color's + * + * @param {color4} out the receiving color + * @param {color4} a the first operand + * @param {color4} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {color4} out + * @function + */ +color4.lerp = function (out, a, b, t) { + var ar = a.r, + ag = a.g, + ab = a.b, + aa = a.a; + out.r = ar + t * (b.r - ar); + out.g = ag + t * (b.g - ag); + out.b = ab + t * (b.b - ab); + out.a = aa + t * (b.a - aa); + return out; +}; + +/** + * Returns a string representation of a color + * + * @param {color4} a vector to represent as a string + * @returns {String} string representation of the vector + */ +color4.str = function (a) { + return ("color4(" + (a.r) + ", " + (a.g) + ", " + (a.b) + ", " + (a.a) + ")"); +}; + +/** + * Returns typed array + * + * @param {array} out + * @param {color4} a + * @returns {array} + */ +color4.array = function (out, a) { + out[0] = a.r; + out[1] = a.g; + out[2] = a.b; + out[3] = a.a; + + return out; +}; + +/** + * Returns whether or not the color have exactly the same elements in the same position (when compared with ===) + * + * @param {color4} a The first color4. + * @param {color4} b The second color4. + * @returns {Boolean} True if the colors are equal, false otherwise. + */ +color4.exactEquals = function (a, b) { + return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a; +}; + +/** + * Returns whether or not the colors have approximately the same elements in the same position. + * + * @param {color4} a The first color4. + * @param {color4} b The second color4. + * @returns {Boolean} True if the colors are equal, false otherwise. + */ +color4.equals = function (a, b) { + var a0 = a.r, a1 = a.g, a2 = a.b, a3 = a.a; + var b0 = b.r, b1 = b.g, b2 = b.b, b3 = b.a; + return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && + Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && + Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && + Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3))); +}; + +/** + * Returns the hex value + * + * @param {color4} a The color + * @returns {Number} + */ +color4.hex = function (a) { + return ((a.r * 255) << 24 | (a.g * 255) << 16 | (a.b * 255) << 8 | a.a * 255) >>> 0; +}; + +// NOTE: there is no syntax for: export {* as bits} from './lib/bits'; +var bits = bits_; + + + +var math = Object.freeze({ + bits: bits, + vec2: vec2, + vec3: vec3, + vec4: vec4, + quat: quat, + mat2: mat2, + mat23: mat23, + mat3: mat3, + mat4: mat4, + color3: color3, + color4: color4, + EPSILON: EPSILON, + equals: equals, + approx: approx, + clamp: clamp, + clamp01: clamp01, + lerp: lerp, + toRadian: toRadian, + toDegree: toDegree, + random: random, + randomRange: randomRange, + randomRangeInt: randomRangeInt, + nextPow2: nextPow2 +}); + +var renderer = window.renderer; + +var gfx = window.gfx; + +// reference: https://github.com/mziccard/node-timsort + +/** + * Default minimum size of a run. + */ +var DEFAULT_MIN_MERGE = 32; + +/** + * Minimum ordered subsequece required to do galloping. + */ +var DEFAULT_MIN_GALLOPING = 7; + +/** + * Default tmp storage length. Can increase depending on the size of the + * smallest run to merge. + */ +var DEFAULT_TMP_STORAGE_LENGTH = 256; + +/** + * Pre-computed powers of 10 for efficient lexicographic comparison of + * small integers. + */ +var POWERS_OF_TEN = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]; + +/** + * Estimate the logarithm base 10 of a small integer. + * + * @param {number} x - The integer to estimate the logarithm of. + * @return {number} - The estimated logarithm of the integer. + */ +function log10$1(x) { + if (x < 1e5) { + if (x < 1e2) { + return x < 1e1 ? 0 : 1; } - - if (~~a === a && ~~b === b) { - if (a === 0 || b === 0) { - return a < b ? -1 : 1; - } - - if (a < 0 || b < 0) { - if (b >= 0) { - return -1; - } - - if (a >= 0) { - return 1; - } - - a = -a; - b = -b; - } - - var al = log10$1(a); - var bl = log10$1(b); - - var t = 0; - - if (al < bl) { - a *= POWERS_OF_TEN[bl - al - 1]; - b /= 10; - t = -1; - } else if (al > bl) { - b *= POWERS_OF_TEN[al - bl - 1]; - a /= 10; - t = 1; - } - - if (a === b) { - return t; - } - + + if (x < 1e4) { + return x < 1e3 ? 2 : 3; + } + + return 4; + } + + if (x < 1e7) { + return x < 1e6 ? 5 : 6; + } + + if (x < 1e9) { + return x < 1e8 ? 7 : 8; + } + + return 9; +} + +/** + * Default alphabetical comparison of items. + * + * @param {string|object|number} a - First element to compare. + * @param {string|object|number} b - Second element to compare. + * @return {number} - A positive number if a.toString() > b.toString(), a + * negative number if .toString() < b.toString(), 0 otherwise. + */ +function alphabeticalCompare(a, b) { + if (a === b) { + return 0; + } + + if (~~a === a && ~~b === b) { + if (a === 0 || b === 0) { return a < b ? -1 : 1; } - - var aStr = String(a); - var bStr = String(b); - - if (aStr === bStr) { - return 0; - } - - return aStr < bStr ? -1 : 1; - } - - /** - * Compute minimum run length for TimSort - * - * @param {number} n - The size of the array to sort. - */ - function minRunLength(n) { - var r = 0; - - while (n >= DEFAULT_MIN_MERGE) { - r |= (n & 1); - n >>= 1; - } - - return n + r; - } - - /** - * Counts the length of a monotonically ascending or strictly monotonically - * descending sequence (run) starting at array[lo] in the range [lo, hi). If - * the run is descending it is made ascending. - * - * @param {array} array - The array to reverse. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - * @param {function} compare - Item comparison function. - * @return {number} - The length of the run. - */ - function makeAscendingRun(array, lo, hi, compare) { - var runHi = lo + 1; - - if (runHi === hi) { - return 1; - } - - // Descending - if (compare(array[runHi++], array[lo]) < 0) { - while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) { - runHi++; + + if (a < 0 || b < 0) { + if (b >= 0) { + return -1; } - - reverseRun(array, lo, runHi); - // Ascending - } else { - while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) { - runHi++; + + if (a >= 0) { + return 1; } + + a = -a; + b = -b; } - - return runHi - lo; + + var al = log10$1(a); + var bl = log10$1(b); + + var t = 0; + + if (al < bl) { + a *= POWERS_OF_TEN[bl - al - 1]; + b /= 10; + t = -1; + } else if (al > bl) { + b *= POWERS_OF_TEN[al - bl - 1]; + a /= 10; + t = 1; + } + + if (a === b) { + return t; + } + + return a < b ? -1 : 1; } - - /** - * Reverse an array in the range [lo, hi). - * - * @param {array} array - The array to reverse. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - */ - function reverseRun(array, lo, hi) { - hi--; - - while (lo < hi) { - var t = array[lo]; - array[lo++] = array[hi]; - array[hi--] = t; + + var aStr = String(a); + var bStr = String(b); + + if (aStr === bStr) { + return 0; + } + + return aStr < bStr ? -1 : 1; +} + +/** + * Compute minimum run length for TimSort + * + * @param {number} n - The size of the array to sort. + */ +function minRunLength(n) { + var r = 0; + + while (n >= DEFAULT_MIN_MERGE) { + r |= (n & 1); + n >>= 1; + } + + return n + r; +} + +/** + * Counts the length of a monotonically ascending or strictly monotonically + * descending sequence (run) starting at array[lo] in the range [lo, hi). If + * the run is descending it is made ascending. + * + * @param {array} array - The array to reverse. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + * @param {function} compare - Item comparison function. + * @return {number} - The length of the run. + */ +function makeAscendingRun(array, lo, hi, compare) { + var runHi = lo + 1; + + if (runHi === hi) { + return 1; + } + + // Descending + if (compare(array[runHi++], array[lo]) < 0) { + while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) { + runHi++; + } + + reverseRun(array, lo, runHi); + // Ascending + } else { + while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) { + runHi++; } } - - /** - * Perform the binary sort of the array in the range [lo, hi) where start is - * the first element possibly out of order. - * - * @param {array} array - The array to sort. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - * @param {number} start - First element possibly out of order. - * @param {function} compare - Item comparison function. - */ - function binaryInsertionSort(array, lo, hi, start, compare) { - if (start === lo) { - start++; - } - - for (; start < hi; start++) { - var pivot = array[start]; - - // Ranges of the array where pivot belongs - var left = lo; - var right = start; - - /* - * pivot >= array[i] for i in [lo, left) - * pivot < array[i] for i in in [right, start) - */ - while (left < right) { - var mid = (left + right) >>> 1; - - if (compare(pivot, array[mid]) < 0) { - right = mid; - } else { - left = mid + 1; - } - } - - /* - * Move elements right to make room for the pivot. If there are elements - * equal to pivot, left points to the first slot after them: this is also - * a reason for which TimSort is stable - */ - var n = start - left; - // Switch is just an optimization for small arrays - switch (n) { - case 3: - array[left + 3] = array[left + 2]; - /* falls through */ - case 2: - array[left + 2] = array[left + 1]; - /* falls through */ - case 1: - array[left + 1] = array[left]; - break; - default: - while (n > 0) { - array[left + n] = array[left + n - 1]; - n--; - } - } - - array[left] = pivot; - } + + return runHi - lo; +} + +/** + * Reverse an array in the range [lo, hi). + * + * @param {array} array - The array to reverse. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + */ +function reverseRun(array, lo, hi) { + hi--; + + while (lo < hi) { + var t = array[lo]; + array[lo++] = array[hi]; + array[hi--] = t; } - - /** - * Find the position at which to insert a value in a sorted range. If the range - * contains elements equal to the value the leftmost element index is returned - * (for stability). - * - * @param {number} value - Value to insert. - * @param {array} array - The array in which to insert value. - * @param {number} start - First element in the range. - * @param {number} length - Length of the range. - * @param {number} hint - The index at which to begin the search. - * @param {function} compare - Item comparison function. - * @return {number} - The index where to insert value. - */ - function gallopLeft(value, array, start, length, hint, compare) { - var lastOffset = 0; - var maxOffset = 0; - var offset = 1; - - if (compare(value, array[start + hint]) > 0) { - maxOffset = length - hint; - - while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - lastOffset += hint; - offset += hint; - - // value <= array[start + hint] - } else { - maxOffset = hint + 1; - while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - var tmp = lastOffset; - lastOffset = hint - offset; - offset = hint - tmp; - } - +} + +/** + * Perform the binary sort of the array in the range [lo, hi) where start is + * the first element possibly out of order. + * + * @param {array} array - The array to sort. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + * @param {number} start - First element possibly out of order. + * @param {function} compare - Item comparison function. + */ +function binaryInsertionSort(array, lo, hi, start, compare) { + if (start === lo) { + start++; + } + + for (; start < hi; start++) { + var pivot = array[start]; + + // Ranges of the array where pivot belongs + var left = lo; + var right = start; + /* - * Now array[start+lastOffset] < value <= array[start+offset], so value - * belongs somewhere in the range (start + lastOffset, start + offset]. Do a - * binary search, with invariant array[start + lastOffset - 1] < value <= - * array[start + offset]. + * pivot >= array[i] for i in [lo, left) + * pivot < array[i] for i in in [right, start) */ - lastOffset++; - while (lastOffset < offset) { - var m = lastOffset + ((offset - lastOffset) >>> 1); - - if (compare(value, array[start + m]) > 0) { - lastOffset = m + 1; - + while (left < right) { + var mid = (left + right) >>> 1; + + if (compare(pivot, array[mid]) < 0) { + right = mid; } else { - offset = m; + left = mid + 1; } } - return offset; - } - - /** - * Find the position at which to insert a value in a sorted range. If the range - * contains elements equal to the value the rightmost element index is returned - * (for stability). - * - * @param {number} value - Value to insert. - * @param {array} array - The array in which to insert value. - * @param {number} start - First element in the range. - * @param {number} length - Length of the range. - * @param {number} hint - The index at which to begin the search. - * @param {function} compare - Item comparison function. - * @return {number} - The index where to insert value. - */ - function gallopRight(value, array, start, length, hint, compare) { - var lastOffset = 0; - var maxOffset = 0; - var offset = 1; - - if (compare(value, array[start + hint]) < 0) { - maxOffset = hint + 1; - - while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - var tmp = lastOffset; - lastOffset = hint - offset; - offset = hint - tmp; - - // value >= array[start + hint] - } else { - maxOffset = length - hint; - - while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - lastOffset += hint; - offset += hint; - } - + /* - * Now array[start+lastOffset] < value <= array[start+offset], so value - * belongs somewhere in the range (start + lastOffset, start + offset]. Do a - * binary search, with invariant array[start + lastOffset - 1] < value <= - * array[start + offset]. + * Move elements right to make room for the pivot. If there are elements + * equal to pivot, left points to the first slot after them: this is also + * a reason for which TimSort is stable */ - lastOffset++; - - while (lastOffset < offset) { - var m = lastOffset + ((offset - lastOffset) >>> 1); - - if (compare(value, array[start + m]) < 0) { - offset = m; - - } else { - lastOffset = m + 1; - } - } - - return offset; - } - - var TimSort = function TimSort(array, compare) { - this.array = array; - this.compare = compare; - this.minGallop = DEFAULT_MIN_GALLOPING; - this.length = array.length; - - this.tmpStorageLength = DEFAULT_TMP_STORAGE_LENGTH; - if (this.length < 2 * DEFAULT_TMP_STORAGE_LENGTH) { - this.tmpStorageLength = this.length >>> 1; - } - - this.tmp = new Array(this.tmpStorageLength); - - this.stackLength = - (this.length < 120 ? 5 : - this.length < 1542 ? 10 : - this.length < 119151 ? 19 : 40); - - this.runStart = new Array(this.stackLength); - this.runLength = new Array(this.stackLength); - this.stackSize = 0; - }; - - /** - * Push a new run on TimSort's stack. - * - * @param {number} runStart - Start index of the run in the original array. - * @param {number} runLength - Length of the run; - */ - TimSort.prototype.pushRun = function pushRun (runStart, runLength) { - this.runStart[this.stackSize] = runStart; - this.runLength[this.stackSize] = runLength; - this.stackSize += 1; - }; - - /** - * Merge runs on TimSort's stack so that the following holds for all i: - * 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1] - * 2) runLength[i - 2] > runLength[i - 1] - */ - TimSort.prototype.mergeRuns = function mergeRuns () { - var this$1 = this; - - while (this.stackSize > 1) { - var n = this$1.stackSize - 2; - - if ((n >= 1 && - this$1.runLength[n - 1] <= this$1.runLength[n] + this$1.runLength[n + 1]) || - (n >= 2 && - this$1.runLength[n - 2] <= this$1.runLength[n] + this$1.runLength[n - 1])) { - - if (this$1.runLength[n - 1] < this$1.runLength[n + 1]) { + var n = start - left; + // Switch is just an optimization for small arrays + switch (n) { + case 3: + array[left + 3] = array[left + 2]; + /* falls through */ + case 2: + array[left + 2] = array[left + 1]; + /* falls through */ + case 1: + array[left + 1] = array[left]; + break; + default: + while (n > 0) { + array[left + n] = array[left + n - 1]; n--; } - - } else if (this$1.runLength[n] > this$1.runLength[n + 1]) { - break; - } - this$1.mergeAt(n); } - }; - - /** - * Merge all runs on TimSort's stack until only one remains. + + array[left] = pivot; + } +} + +/** + * Find the position at which to insert a value in a sorted range. If the range + * contains elements equal to the value the leftmost element index is returned + * (for stability). + * + * @param {number} value - Value to insert. + * @param {array} array - The array in which to insert value. + * @param {number} start - First element in the range. + * @param {number} length - Length of the range. + * @param {number} hint - The index at which to begin the search. + * @param {function} compare - Item comparison function. + * @return {number} - The index where to insert value. + */ +function gallopLeft(value, array, start, length, hint, compare) { + var lastOffset = 0; + var maxOffset = 0; + var offset = 1; + + if (compare(value, array[start + hint]) > 0) { + maxOffset = length - hint; + + while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + lastOffset += hint; + offset += hint; + + // value <= array[start + hint] + } else { + maxOffset = hint + 1; + while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + var tmp = lastOffset; + lastOffset = hint - offset; + offset = hint - tmp; + } + + /* + * Now array[start+lastOffset] < value <= array[start+offset], so value + * belongs somewhere in the range (start + lastOffset, start + offset]. Do a + * binary search, with invariant array[start + lastOffset - 1] < value <= + * array[start + offset]. */ - TimSort.prototype.forceMergeRuns = function forceMergeRuns () { - var this$1 = this; - - while (this.stackSize > 1) { - var n = this$1.stackSize - 2; - - if (n > 0 && this$1.runLength[n - 1] < this$1.runLength[n + 1]) { + lastOffset++; + while (lastOffset < offset) { + var m = lastOffset + ((offset - lastOffset) >>> 1); + + if (compare(value, array[start + m]) > 0) { + lastOffset = m + 1; + + } else { + offset = m; + } + } + return offset; +} + +/** + * Find the position at which to insert a value in a sorted range. If the range + * contains elements equal to the value the rightmost element index is returned + * (for stability). + * + * @param {number} value - Value to insert. + * @param {array} array - The array in which to insert value. + * @param {number} start - First element in the range. + * @param {number} length - Length of the range. + * @param {number} hint - The index at which to begin the search. + * @param {function} compare - Item comparison function. + * @return {number} - The index where to insert value. + */ +function gallopRight(value, array, start, length, hint, compare) { + var lastOffset = 0; + var maxOffset = 0; + var offset = 1; + + if (compare(value, array[start + hint]) < 0) { + maxOffset = hint + 1; + + while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + var tmp = lastOffset; + lastOffset = hint - offset; + offset = hint - tmp; + + // value >= array[start + hint] + } else { + maxOffset = length - hint; + + while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + lastOffset += hint; + offset += hint; + } + + /* + * Now array[start+lastOffset] < value <= array[start+offset], so value + * belongs somewhere in the range (start + lastOffset, start + offset]. Do a + * binary search, with invariant array[start + lastOffset - 1] < value <= + * array[start + offset]. + */ + lastOffset++; + + while (lastOffset < offset) { + var m = lastOffset + ((offset - lastOffset) >>> 1); + + if (compare(value, array[start + m]) < 0) { + offset = m; + + } else { + lastOffset = m + 1; + } + } + + return offset; +} + +var TimSort = function TimSort(array, compare) { + this.array = array; + this.compare = compare; + this.minGallop = DEFAULT_MIN_GALLOPING; + this.length = array.length; + + this.tmpStorageLength = DEFAULT_TMP_STORAGE_LENGTH; + if (this.length < 2 * DEFAULT_TMP_STORAGE_LENGTH) { + this.tmpStorageLength = this.length >>> 1; + } + + this.tmp = new Array(this.tmpStorageLength); + + this.stackLength = + (this.length < 120 ? 5 : + this.length < 1542 ? 10 : + this.length < 119151 ? 19 : 40); + + this.runStart = new Array(this.stackLength); + this.runLength = new Array(this.stackLength); + this.stackSize = 0; +}; + +/** + * Push a new run on TimSort's stack. + * + * @param {number} runStart - Start index of the run in the original array. + * @param {number} runLength - Length of the run; + */ +TimSort.prototype.pushRun = function pushRun (runStart, runLength) { + this.runStart[this.stackSize] = runStart; + this.runLength[this.stackSize] = runLength; + this.stackSize += 1; +}; + +/** + * Merge runs on TimSort's stack so that the following holds for all i: + * 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1] + * 2) runLength[i - 2] > runLength[i - 1] + */ +TimSort.prototype.mergeRuns = function mergeRuns () { + var this$1 = this; + + while (this.stackSize > 1) { + var n = this$1.stackSize - 2; + + if ((n >= 1 && + this$1.runLength[n - 1] <= this$1.runLength[n] + this$1.runLength[n + 1]) || + (n >= 2 && + this$1.runLength[n - 2] <= this$1.runLength[n] + this$1.runLength[n - 1])) { + + if (this$1.runLength[n - 1] < this$1.runLength[n + 1]) { n--; } - - this$1.mergeAt(n); + + } else if (this$1.runLength[n] > this$1.runLength[n + 1]) { + break; } - }; - - /** - * Merge the runs on the stack at positions i and i+1. Must be always be called - * with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack). - * - * @param {number} i - Index of the run to merge in TimSort's stack. + this$1.mergeAt(n); + } +}; + +/** + * Merge all runs on TimSort's stack until only one remains. + */ +TimSort.prototype.forceMergeRuns = function forceMergeRuns () { + var this$1 = this; + + while (this.stackSize > 1) { + var n = this$1.stackSize - 2; + + if (n > 0 && this$1.runLength[n - 1] < this$1.runLength[n + 1]) { + n--; + } + + this$1.mergeAt(n); + } +}; + +/** + * Merge the runs on the stack at positions i and i+1. Must be always be called + * with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack). + * + * @param {number} i - Index of the run to merge in TimSort's stack. + */ +TimSort.prototype.mergeAt = function mergeAt (i) { + var compare = this.compare; + var array = this.array; + + var start1 = this.runStart[i]; + var length1 = this.runLength[i]; + var start2 = this.runStart[i + 1]; + var length2 = this.runLength[i + 1]; + + this.runLength[i] = length1 + length2; + + if (i === this.stackSize - 3) { + this.runStart[i + 1] = this.runStart[i + 2]; + this.runLength[i + 1] = this.runLength[i + 2]; + } + + this.stackSize--; + + /* + * Find where the first element in the second run goes in run1. Previous + * elements in run1 are already in place */ - TimSort.prototype.mergeAt = function mergeAt (i) { - var compare = this.compare; - var array = this.array; - - var start1 = this.runStart[i]; - var length1 = this.runLength[i]; - var start2 = this.runStart[i + 1]; - var length2 = this.runLength[i + 1]; - - this.runLength[i] = length1 + length2; - - if (i === this.stackSize - 3) { - this.runStart[i + 1] = this.runStart[i + 2]; - this.runLength[i + 1] = this.runLength[i + 2]; - } - - this.stackSize--; - - /* - * Find where the first element in the second run goes in run1. Previous - * elements in run1 are already in place - */ - var k = gallopRight(array[start2], array, start1, length1, 0, compare); - start1 += k; - length1 -= k; - - if (length1 === 0) { - return; - } - - /* - * Find where the last element in the first run goes in run2. Next elements - * in run2 are already in place - */ - length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare); - - if (length2 === 0) { - return; - } - - /* - * Merge remaining runs. A tmp array with length = min(length1, length2) is - * used - */ - if (length1 <= length2) { - this.mergeLow(start1, length1, start2, length2); - - } else { - this.mergeHigh(start1, length1, start2, length2); - } - }; - - /** - * Merge two adjacent runs in a stable way. The runs must be such that the - * first element of run1 is bigger than the first element in run2 and the - * last element of run1 is greater than all the elements in run2. - * The method should be called when run1.length <= run2.length as it uses - * TimSort temporary array to store run1. Use mergeHigh if run1.length > - * run2.length. - * - * @param {number} start1 - First element in run1. - * @param {number} length1 - Length of run1. - * @param {number} start2 - First element in run2. - * @param {number} length2 - Length of run2. + var k = gallopRight(array[start2], array, start1, length1, 0, compare); + start1 += k; + length1 -= k; + + if (length1 === 0) { + return; + } + + /* + * Find where the last element in the first run goes in run2. Next elements + * in run2 are already in place */ - TimSort.prototype.mergeLow = function mergeLow (start1, length1, start2, length2) { - - var compare = this.compare; - var array = this.array; - var tmp = this.tmp; - var i = 0; - + length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare); + + if (length2 === 0) { + return; + } + + /* + * Merge remaining runs. A tmp array with length = min(length1, length2) is + * used + */ + if (length1 <= length2) { + this.mergeLow(start1, length1, start2, length2); + + } else { + this.mergeHigh(start1, length1, start2, length2); + } +}; + +/** + * Merge two adjacent runs in a stable way. The runs must be such that the + * first element of run1 is bigger than the first element in run2 and the + * last element of run1 is greater than all the elements in run2. + * The method should be called when run1.length <= run2.length as it uses + * TimSort temporary array to store run1. Use mergeHigh if run1.length > + * run2.length. + * + * @param {number} start1 - First element in run1. + * @param {number} length1 - Length of run1. + * @param {number} start2 - First element in run2. + * @param {number} length2 - Length of run2. + */ +TimSort.prototype.mergeLow = function mergeLow (start1, length1, start2, length2) { + + var compare = this.compare; + var array = this.array; + var tmp = this.tmp; + var i = 0; + + for (i = 0; i < length1; i++) { + tmp[i] = array[start1 + i]; + } + + var cursor1 = 0; + var cursor2 = start2; + var dest = start1; + + array[dest++] = array[cursor2++]; + + if (--length2 === 0) { for (i = 0; i < length1; i++) { - tmp[i] = array[start1 + i]; + array[dest + i] = tmp[cursor1 + i]; } - - var cursor1 = 0; - var cursor2 = start2; - var dest = start1; - - array[dest++] = array[cursor2++]; - - if (--length2 === 0) { - for (i = 0; i < length1; i++) { - array[dest + i] = tmp[cursor1 + i]; - } - return; + return; + } + + if (length1 === 1) { + for (i = 0; i < length2; i++) { + array[dest + i] = array[cursor2 + i]; } - - if (length1 === 1) { - for (i = 0; i < length2; i++) { - array[dest + i] = array[cursor2 + i]; - } - array[dest + length2] = tmp[cursor1]; - return; - } - - var minGallop = this.minGallop; - - while (true) { - var count1 = 0; - var count2 = 0; - var exit = false; - - do { - if (compare(array[cursor2], tmp[cursor1]) < 0) { - array[dest++] = array[cursor2++]; - count2++; - count1 = 0; - - if (--length2 === 0) { - exit = true; - break; - } - - } else { - array[dest++] = tmp[cursor1++]; - count1++; - count2 = 0; - if (--length1 === 1) { - exit = true; - break; - } - } - } while ((count1 | count2) < minGallop); - - if (exit) { - break; - } - - do { - count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare); - - if (count1 !== 0) { - for (i = 0; i < count1; i++) { - array[dest + i] = tmp[cursor1 + i]; - } - - dest += count1; - cursor1 += count1; - length1 -= count1; - if (length1 <= 1) { - exit = true; - break; - } - } - + array[dest + length2] = tmp[cursor1]; + return; + } + + var minGallop = this.minGallop; + + while (true) { + var count1 = 0; + var count2 = 0; + var exit = false; + + do { + if (compare(array[cursor2], tmp[cursor1]) < 0) { array[dest++] = array[cursor2++]; - + count2++; + count1 = 0; + if (--length2 === 0) { exit = true; break; } - - count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare); - - if (count2 !== 0) { - for (i = 0; i < count2; i++) { - array[dest + i] = array[cursor2 + i]; - } - - dest += count2; - cursor2 += count2; - length2 -= count2; - - if (length2 === 0) { - exit = true; - break; - } - } + + } else { array[dest++] = tmp[cursor1++]; - + count1++; + count2 = 0; if (--length1 === 1) { exit = true; break; } - - minGallop--; - - } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); - - if (exit) { - break; } - - if (minGallop < 0) { - minGallop = 0; - } - - minGallop += 2; + } while ((count1 | count2) < minGallop); + + if (exit) { + break; } - - this.minGallop = minGallop; - - if (minGallop < 1) { - this.minGallop = 1; - } - - if (length1 === 1) { - for (i = 0; i < length2; i++) { - array[dest + i] = array[cursor2 + i]; - } - array[dest + length2] = tmp[cursor1]; - - } else if (length1 === 0) { - throw new Error('mergeLow preconditions were not respected'); - - } else { - for (i = 0; i < length1; i++) { - array[dest + i] = tmp[cursor1 + i]; - } - } - }; - - /** - * Merge two adjacent runs in a stable way. The runs must be such that the - * first element of run1 is bigger than the first element in run2 and the - * last element of run1 is greater than all the elements in run2. - * The method should be called when run1.length > run2.length as it uses - * TimSort temporary array to store run2. Use mergeLow if run1.length <= - * run2.length. - * - * @param {number} start1 - First element in run1. - * @param {number} length1 - Length of run1. - * @param {number} start2 - First element in run2. - * @param {number} length2 - Length of run2. - */ - TimSort.prototype.mergeHigh = function mergeHigh (start1, length1, start2, length2) { - var compare = this.compare; - var array = this.array; - var tmp = this.tmp; - var i = 0; - - for (i = 0; i < length2; i++) { - tmp[i] = array[start2 + i]; - } - - var cursor1 = start1 + length1 - 1; - var cursor2 = length2 - 1; - var dest = start2 + length2 - 1; - var customCursor = 0; - var customDest = 0; - - array[dest--] = array[cursor1--]; - - if (--length1 === 0) { - customCursor = dest - (length2 - 1); - - for (i = 0; i < length2; i++) { - array[customCursor + i] = tmp[i]; - } - - return; - } - - if (length2 === 1) { - dest -= length1; - cursor1 -= length1; - customDest = dest + 1; - customCursor = cursor1 + 1; - - for (i = length1 - 1; i >= 0; i--) { - array[customDest + i] = array[customCursor + i]; - } - - array[dest] = tmp[cursor2]; - return; - } - - var minGallop = this.minGallop; - - while (true) { - var count1 = 0; - var count2 = 0; - var exit = false; - - do { - if (compare(tmp[cursor2], array[cursor1]) < 0) { - array[dest--] = array[cursor1--]; - count1++; - count2 = 0; - if (--length1 === 0) { - exit = true; - break; - } - - } else { - array[dest--] = tmp[cursor2--]; - count2++; - count1 = 0; - if (--length2 === 1) { - exit = true; - break; - } + + do { + count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare); + + if (count1 !== 0) { + for (i = 0; i < count1; i++) { + array[dest + i] = tmp[cursor1 + i]; } - - } while ((count1 | count2) < minGallop); - - if (exit) { - break; - } - - do { - count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare); - - if (count1 !== 0) { - dest -= count1; - cursor1 -= count1; - length1 -= count1; - customDest = dest + 1; - customCursor = cursor1 + 1; - - for (i = count1 - 1; i >= 0; i--) { - array[customDest + i] = array[customCursor + i]; - } - - if (length1 === 0) { - exit = true; - break; - } - } - - array[dest--] = tmp[cursor2--]; - - if (--length2 === 1) { + + dest += count1; + cursor1 += count1; + length1 -= count1; + if (length1 <= 1) { exit = true; break; } - - count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare); - - if (count2 !== 0) { - dest -= count2; - cursor2 -= count2; - length2 -= count2; - customDest = dest + 1; - customCursor = cursor2 + 1; - - for (i = 0; i < count2; i++) { - array[customDest + i] = tmp[customCursor + i]; - } - - if (length2 <= 1) { - exit = true; - break; - } + } + + array[dest++] = array[cursor2++]; + + if (--length2 === 0) { + exit = true; + break; + } + + count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare); + + if (count2 !== 0) { + for (i = 0; i < count2; i++) { + array[dest + i] = array[cursor2 + i]; } - + + dest += count2; + cursor2 += count2; + length2 -= count2; + + if (length2 === 0) { + exit = true; + break; + } + } + array[dest++] = tmp[cursor1++]; + + if (--length1 === 1) { + exit = true; + break; + } + + minGallop--; + + } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); + + if (exit) { + break; + } + + if (minGallop < 0) { + minGallop = 0; + } + + minGallop += 2; + } + + this.minGallop = minGallop; + + if (minGallop < 1) { + this.minGallop = 1; + } + + if (length1 === 1) { + for (i = 0; i < length2; i++) { + array[dest + i] = array[cursor2 + i]; + } + array[dest + length2] = tmp[cursor1]; + + } else if (length1 === 0) { + throw new Error('mergeLow preconditions were not respected'); + + } else { + for (i = 0; i < length1; i++) { + array[dest + i] = tmp[cursor1 + i]; + } + } +}; + +/** + * Merge two adjacent runs in a stable way. The runs must be such that the + * first element of run1 is bigger than the first element in run2 and the + * last element of run1 is greater than all the elements in run2. + * The method should be called when run1.length > run2.length as it uses + * TimSort temporary array to store run2. Use mergeLow if run1.length <= + * run2.length. + * + * @param {number} start1 - First element in run1. + * @param {number} length1 - Length of run1. + * @param {number} start2 - First element in run2. + * @param {number} length2 - Length of run2. + */ +TimSort.prototype.mergeHigh = function mergeHigh (start1, length1, start2, length2) { + var compare = this.compare; + var array = this.array; + var tmp = this.tmp; + var i = 0; + + for (i = 0; i < length2; i++) { + tmp[i] = array[start2 + i]; + } + + var cursor1 = start1 + length1 - 1; + var cursor2 = length2 - 1; + var dest = start2 + length2 - 1; + var customCursor = 0; + var customDest = 0; + + array[dest--] = array[cursor1--]; + + if (--length1 === 0) { + customCursor = dest - (length2 - 1); + + for (i = 0; i < length2; i++) { + array[customCursor + i] = tmp[i]; + } + + return; + } + + if (length2 === 1) { + dest -= length1; + cursor1 -= length1; + customDest = dest + 1; + customCursor = cursor1 + 1; + + for (i = length1 - 1; i >= 0; i--) { + array[customDest + i] = array[customCursor + i]; + } + + array[dest] = tmp[cursor2]; + return; + } + + var minGallop = this.minGallop; + + while (true) { + var count1 = 0; + var count2 = 0; + var exit = false; + + do { + if (compare(tmp[cursor2], array[cursor1]) < 0) { array[dest--] = array[cursor1--]; - + count1++; + count2 = 0; if (--length1 === 0) { exit = true; break; } - - minGallop--; - - } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); - - if (exit) { + + } else { + array[dest--] = tmp[cursor2--]; + count2++; + count1 = 0; + if (--length2 === 1) { + exit = true; + break; + } + } + + } while ((count1 | count2) < minGallop); + + if (exit) { + break; + } + + do { + count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare); + + if (count1 !== 0) { + dest -= count1; + cursor1 -= count1; + length1 -= count1; + customDest = dest + 1; + customCursor = cursor1 + 1; + + for (i = count1 - 1; i >= 0; i--) { + array[customDest + i] = array[customCursor + i]; + } + + if (length1 === 0) { + exit = true; + break; + } + } + + array[dest--] = tmp[cursor2--]; + + if (--length2 === 1) { + exit = true; break; } - - if (minGallop < 0) { - minGallop = 0; - } - - minGallop += 2; - } - - this.minGallop = minGallop; - - if (minGallop < 1) { - this.minGallop = 1; - } - - if (length2 === 1) { - dest -= length1; - cursor1 -= length1; - customDest = dest + 1; - customCursor = cursor1 + 1; - - for (i = length1 - 1; i >= 0; i--) { - array[customDest + i] = array[customCursor + i]; - } - - array[dest] = tmp[cursor2]; - - } else if (length2 === 0) { - throw new Error('mergeHigh preconditions were not respected'); - - } else { - customCursor = dest - (length2 - 1); - for (i = 0; i < length2; i++) { - array[customCursor + i] = tmp[i]; - } - } - }; - - /** - * Sort an array in the range [lo, hi) using TimSort. - * - * @param {array} array - The array to sort. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - * @param {function=} compare - Item comparison function. Default is alphabetical. - */ - function sort (array, lo, hi, compare) { - if (!Array.isArray(array)) { - throw new TypeError('Can only sort arrays'); - } - - /* - * Handle the case where a comparison function is not provided. We do - * lexicographic sorting - */ - - if (lo === undefined) { - lo = 0; - } - - if (hi === undefined) { - hi = array.length; - } - - if (compare === undefined) { - compare = alphabeticalCompare; - } - - var remaining = hi - lo; - - // The array is already sorted - if (remaining < 2) { - return; - } - - var runLength = 0; - // On small arrays binary sort can be used directly - if (remaining < DEFAULT_MIN_MERGE) { - runLength = makeAscendingRun(array, lo, hi, compare); - binaryInsertionSort(array, lo, hi, lo + runLength, compare); - return; - } - - var ts = new TimSort(array, compare); - - var minRun = minRunLength(remaining); - - do { - runLength = makeAscendingRun(array, lo, hi, compare); - if (runLength < minRun) { - var force = remaining; - if (force > minRun) { - force = minRun; + + count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare); + + if (count2 !== 0) { + dest -= count2; + cursor2 -= count2; + length2 -= count2; + customDest = dest + 1; + customCursor = cursor2 + 1; + + for (i = 0; i < count2; i++) { + array[customDest + i] = tmp[customCursor + i]; + } + + if (length2 <= 1) { + exit = true; + break; } - - binaryInsertionSort(array, lo, lo + force, lo + runLength, compare); - runLength = force; } - // Push new run and merge if necessary - ts.pushRun(lo, runLength); - ts.mergeRuns(); - - // Go find next run - remaining -= runLength; - lo += runLength; - - } while (remaining !== 0); - - // Force merging of remaining runs - ts.forceMergeRuns(); - } - - var FixedArray = function FixedArray(size) { - this._count = 0; - this._data = new Array(size); - }; - - var prototypeAccessors = { length: {},data: {} }; - - FixedArray.prototype._resize = function _resize (size) { - var this$1 = this; - - if (size > this._data.length) { - for (var i = this._data.length; i < size; ++i) { - this$1._data[i] = undefined; + + array[dest--] = array[cursor1--]; + + if (--length1 === 0) { + exit = true; + break; } + + minGallop--; + + } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); + + if (exit) { + break; } - }; - - prototypeAccessors.length.get = function () { - return this._count; - }; - - prototypeAccessors.data.get = function () { - return this._data; - }; - - FixedArray.prototype.reset = function reset () { - var this$1 = this; - - for (var i = 0; i < this._count; ++i) { + + if (minGallop < 0) { + minGallop = 0; + } + + minGallop += 2; + } + + this.minGallop = minGallop; + + if (minGallop < 1) { + this.minGallop = 1; + } + + if (length2 === 1) { + dest -= length1; + cursor1 -= length1; + customDest = dest + 1; + customCursor = cursor1 + 1; + + for (i = length1 - 1; i >= 0; i--) { + array[customDest + i] = array[customCursor + i]; + } + + array[dest] = tmp[cursor2]; + + } else if (length2 === 0) { + throw new Error('mergeHigh preconditions were not respected'); + + } else { + customCursor = dest - (length2 - 1); + for (i = 0; i < length2; i++) { + array[customCursor + i] = tmp[i]; + } + } +}; + +/** + * Sort an array in the range [lo, hi) using TimSort. + * + * @param {array} array - The array to sort. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + * @param {function=} compare - Item comparison function. Default is alphabetical. + */ +function sort (array, lo, hi, compare) { + if (!Array.isArray(array)) { + throw new TypeError('Can only sort arrays'); + } + + /* + * Handle the case where a comparison function is not provided. We do + * lexicographic sorting + */ + + if (lo === undefined) { + lo = 0; + } + + if (hi === undefined) { + hi = array.length; + } + + if (compare === undefined) { + compare = alphabeticalCompare; + } + + var remaining = hi - lo; + + // The array is already sorted + if (remaining < 2) { + return; + } + + var runLength = 0; + // On small arrays binary sort can be used directly + if (remaining < DEFAULT_MIN_MERGE) { + runLength = makeAscendingRun(array, lo, hi, compare); + binaryInsertionSort(array, lo, hi, lo + runLength, compare); + return; + } + + var ts = new TimSort(array, compare); + + var minRun = minRunLength(remaining); + + do { + runLength = makeAscendingRun(array, lo, hi, compare); + if (runLength < minRun) { + var force = remaining; + if (force > minRun) { + force = minRun; + } + + binaryInsertionSort(array, lo, lo + force, lo + runLength, compare); + runLength = force; + } + // Push new run and merge if necessary + ts.pushRun(lo, runLength); + ts.mergeRuns(); + + // Go find next run + remaining -= runLength; + lo += runLength; + + } while (remaining !== 0); + + // Force merging of remaining runs + ts.forceMergeRuns(); +} + +var FixedArray = function FixedArray(size) { + this._count = 0; + this._data = new Array(size); +}; + +var prototypeAccessors = { length: {},data: {} }; + +FixedArray.prototype._resize = function _resize (size) { + var this$1 = this; + + if (size > this._data.length) { + for (var i = this._data.length; i < size; ++i) { this$1._data[i] = undefined; } - - this._count = 0; - }; - - FixedArray.prototype.push = function push (val) { - if (this._count >= this._data.length) { - this._resize(this._data.length * 2); - } - - this._data[this._count] = val; - ++this._count; - }; - - FixedArray.prototype.pop = function pop () { - --this._count; - - if (this._count < 0) { - this._count = 0; - } - - var ret = this._data[this._count]; - this._data[this._count] = undefined; - - return ret; - }; - - FixedArray.prototype.fastRemove = function fastRemove (idx) { - if (idx >= this._count) { - return; - } - - var last = this._count - 1; - this._data[idx] = this._data[last]; - this._data[last] = undefined; - this._count -= 1; - }; - - FixedArray.prototype.indexOf = function indexOf (val) { - var idx = this._data.indexOf(val); - if (idx >= this._count) { - return -1; - } - - return idx; - }; - - FixedArray.prototype.sort = function sort$1 (cmp) { - return sort(this._data, 0, this._count, cmp); - }; - - Object.defineProperties( FixedArray.prototype, prototypeAccessors ); - - var Pool = function Pool(fn, size) { - var this$1 = this; - - this._fn = fn; - this._idx = size - 1; - this._frees = new Array(size); - - for (var i = 0; i < size; ++i) { - this$1._frees[i] = fn(); - } - }; - - Pool.prototype._expand = function _expand (size) { - var this$1 = this; - - var old = this._frees; - this._frees = new Array(size); - - var len = size - old.length; - for (var i = 0; i < len; ++i) { - this$1._frees[i] = this$1._fn(); - } - - for (var i$1 = len, j = 0; i$1 < size; ++i$1, ++j) { - this$1._frees[i$1] = old[j]; - } - - this._idx += len; - }; - - Pool.prototype.alloc = function alloc () { - // create some more space (expand by 20%, minimum 1) - if (this._idx < 0) { - this._expand(Math.round(this._frees.length * 1.2) + 1); - } - - var ret = this._frees[this._idx]; - this._frees[this._idx] = null; - --this._idx; - - return ret; - }; - - Pool.prototype.free = function free (obj) { - ++this._idx; - this._frees[this._idx] = obj; - }; - - // NOTE: you must have `_prev` and `_next` field in the object returns by `fn` - - var LinkedArray = function LinkedArray(fn, size) { - this._fn = fn; - this._count = 0; - this._head = null; - this._tail = null; - - this._pool = new Pool(fn, size); - }; - - var prototypeAccessors$1 = { head: {},tail: {},length: {} }; - - prototypeAccessors$1.head.get = function () { - return this._head; - }; - - prototypeAccessors$1.tail.get = function () { - return this._tail; - }; - - prototypeAccessors$1.length.get = function () { - return this._count; - }; - - LinkedArray.prototype.add = function add () { - var node = this._pool.alloc(); - - if (!this._tail) { - this._head = node; - } else { - this._tail._next = node; - node._prev = this._tail; - } - this._tail = node; - this._count += 1; - - return node; - }; - - LinkedArray.prototype.remove = function remove (node) { - if (node._prev) { - node._prev._next = node._next; - } else { - this._head = node._next; - } - - if (node._next) { - node._next._prev = node._prev; - } else { - this._tail = node._prev; - } - - node._next = null; - node._prev = null; - this._pool.free(node); - this._count -= 1; - }; - - LinkedArray.prototype.forEach = function forEach (fn, binder) { - var this$1 = this; - - var cursor = this._head; - if (!cursor) { - return; - } - - if (binder) { - fn = fn.bind(binder); - } - - var idx = 0; - var next = cursor; - - while (cursor) { - next = cursor._next; - fn(cursor, idx, this$1); - - cursor = next; - ++idx; - } - }; - - Object.defineProperties( LinkedArray.prototype, prototypeAccessors$1 ); - - var RecyclePool = function RecyclePool(fn, size) { - var this$1 = this; - - this._fn = fn; - this._count = 0; - this._data = new Array(size); - - for (var i = 0; i < size; ++i) { - this$1._data[i] = fn(); - } - }; - - var prototypeAccessors$2 = { length: {},data: {} }; - - prototypeAccessors$2.length.get = function () { - return this._count; - }; - - prototypeAccessors$2.data.get = function () { - return this._data; - }; - - RecyclePool.prototype.reset = function reset () { - this._count = 0; - }; - - RecyclePool.prototype.resize = function resize (size) { - var this$1 = this; - - if (size > this._data.length) { - for (var i = this._data.length; i < size; ++i) { - this$1._data[i] = this$1._fn(); - } - } - }; - - RecyclePool.prototype.add = function add () { - if (this._count >= this._data.length) { - this.resize(this._data.length * 2); - } - - return this._data[this._count++]; - }; - - RecyclePool.prototype.remove = function remove (idx) { - if (idx >= this._count) { - return; - } - - var last = this._count - 1; - var tmp = this._data[idx]; - this._data[idx] = this._data[last]; - this._data[last] = tmp; - this._count -= 1; - }; - - RecyclePool.prototype.sort = function sort$1 (cmp) { - return sort(this._data, 0, this._count, cmp); - }; - - Object.defineProperties( RecyclePool.prototype, prototypeAccessors$2 ); - - var _bufferPools = Array(8); - for (var i = 0; i < 8; ++i) { - _bufferPools[i] = []; } - - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var _a16_view = new Float32Array(16); - var _a16_proj = new Float32Array(16); - var _a16_viewProj = new Float32Array(16); - - // Add stage to renderer - renderer.addStage('transparent'); - - var ForwardRenderer = (function (superclass) { - function ForwardRenderer (device, builtin) { - superclass.call(this, device, builtin); - this._registerStage('transparent', this._transparentStage.bind(this)); +}; + +prototypeAccessors.length.get = function () { + return this._count; +}; + +prototypeAccessors.data.get = function () { + return this._data; +}; + +FixedArray.prototype.reset = function reset () { + var this$1 = this; + + for (var i = 0; i < this._count; ++i) { + this$1._data[i] = undefined; + } + + this._count = 0; +}; + +FixedArray.prototype.push = function push (val) { + if (this._count >= this._data.length) { + this._resize(this._data.length * 2); + } + + this._data[this._count] = val; + ++this._count; +}; + +FixedArray.prototype.pop = function pop () { + --this._count; + + if (this._count < 0) { + this._count = 0; + } + + var ret = this._data[this._count]; + this._data[this._count] = undefined; + + return ret; +}; + +FixedArray.prototype.fastRemove = function fastRemove (idx) { + if (idx >= this._count) { + return; + } + + var last = this._count - 1; + this._data[idx] = this._data[last]; + this._data[last] = undefined; + this._count -= 1; +}; + +FixedArray.prototype.indexOf = function indexOf (val) { + var idx = this._data.indexOf(val); + if (idx >= this._count) { + return -1; + } + + return idx; +}; + +FixedArray.prototype.sort = function sort$1 (cmp) { + return sort(this._data, 0, this._count, cmp); +}; + +Object.defineProperties( FixedArray.prototype, prototypeAccessors ); + +var Pool = function Pool(fn, size) { + var this$1 = this; + + this._fn = fn; + this._idx = size - 1; + this._frees = new Array(size); + + for (var i = 0; i < size; ++i) { + this$1._frees[i] = fn(); + } +}; + +Pool.prototype._expand = function _expand (size) { + var this$1 = this; + + var old = this._frees; + this._frees = new Array(size); + + var len = size - old.length; + for (var i = 0; i < len; ++i) { + this$1._frees[i] = this$1._fn(); + } + + for (var i$1 = len, j = 0; i$1 < size; ++i$1, ++j) { + this$1._frees[i$1] = old[j]; + } + + this._idx += len; +}; + +Pool.prototype.alloc = function alloc () { + // create some more space (expand by 20%, minimum 1) + if (this._idx < 0) { + this._expand(Math.round(this._frees.length * 1.2) + 1); + } + + var ret = this._frees[this._idx]; + this._frees[this._idx] = null; + --this._idx; + + return ret; +}; + +Pool.prototype.free = function free (obj) { + ++this._idx; + this._frees[this._idx] = obj; +}; + +// NOTE: you must have `_prev` and `_next` field in the object returns by `fn` + +var LinkedArray = function LinkedArray(fn, size) { + this._fn = fn; + this._count = 0; + this._head = null; + this._tail = null; + + this._pool = new Pool(fn, size); +}; + +var prototypeAccessors$1 = { head: {},tail: {},length: {} }; + +prototypeAccessors$1.head.get = function () { + return this._head; +}; + +prototypeAccessors$1.tail.get = function () { + return this._tail; +}; + +prototypeAccessors$1.length.get = function () { + return this._count; +}; + +LinkedArray.prototype.add = function add () { + var node = this._pool.alloc(); + + if (!this._tail) { + this._head = node; + } else { + this._tail._next = node; + node._prev = this._tail; + } + this._tail = node; + this._count += 1; + + return node; +}; + +LinkedArray.prototype.remove = function remove (node) { + if (node._prev) { + node._prev._next = node._next; + } else { + this._head = node._next; + } + + if (node._next) { + node._next._prev = node._prev; + } else { + this._tail = node._prev; + } + + node._next = null; + node._prev = null; + this._pool.free(node); + this._count -= 1; +}; + +LinkedArray.prototype.forEach = function forEach (fn, binder) { + var this$1 = this; + + var cursor = this._head; + if (!cursor) { + return; + } + + if (binder) { + fn = fn.bind(binder); + } + + var idx = 0; + var next = cursor; + + while (cursor) { + next = cursor._next; + fn(cursor, idx, this$1); + + cursor = next; + ++idx; + } +}; + +Object.defineProperties( LinkedArray.prototype, prototypeAccessors$1 ); + +var RecyclePool = function RecyclePool(fn, size) { + var this$1 = this; + + this._fn = fn; + this._count = 0; + this._data = new Array(size); + + for (var i = 0; i < size; ++i) { + this$1._data[i] = fn(); + } +}; + +var prototypeAccessors$2 = { length: {},data: {} }; + +prototypeAccessors$2.length.get = function () { + return this._count; +}; + +prototypeAccessors$2.data.get = function () { + return this._data; +}; + +RecyclePool.prototype.reset = function reset () { + this._count = 0; +}; + +RecyclePool.prototype.resize = function resize (size) { + var this$1 = this; + + if (size > this._data.length) { + for (var i = this._data.length; i < size; ++i) { + this$1._data[i] = this$1._fn(); } - - if ( superclass ) ForwardRenderer.__proto__ = superclass; - ForwardRenderer.prototype = Object.create( superclass && superclass.prototype ); - ForwardRenderer.prototype.constructor = ForwardRenderer; - - ForwardRenderer.prototype.reset = function reset () { - this._reset(); - }; - - ForwardRenderer.prototype.render = function render (scene) { - var this$1 = this; - - this._reset(); - - scene._cameras.sort(function (a, b) { - if (a._depth > b._depth) { return 1; } - else if (a._depth < b._depth) { return -1; } - else { return 0; } - }); - - for (var i = 0; i < scene._cameras.length; ++i) { - var camera = scene._cameras.data[i]; - this$1.renderCamera(camera, scene); - } - }; - - ForwardRenderer.prototype.renderCamera = function renderCamera (camera, scene) { - var canvas = this._device._gl.canvas; - - var view = camera.view; - var dirty = camera.dirty; - if (!view) { - view = this._requestView(); - dirty = true; - } - if (dirty) { - var width = canvas.width; - var height = canvas.height; - if (camera._framebuffer) { - width = camera._framebuffer._width; - height = camera._framebuffer._height; - } - camera.extractView(view, width, height); - } - this._render(view, scene); - }; - - ForwardRenderer.prototype._transparentStage = function _transparentStage (view, items) { - var this$1 = this; - - // update uniforms - this._device.setUniform('view', mat4.array(_a16_view, view._matView)); - this._device.setUniform('proj', mat4.array(_a16_proj, view._matProj)); - this._device.setUniform('viewProj', mat4.array(_a16_viewProj, view._matViewProj)); - - // draw it - for (var i = 0; i < items.length; ++i) { - var item = items.data[i]; - this$1._draw(item); - } - }; - - return ForwardRenderer; - }(renderer.Base)); - - var chunks = { + } +}; + +RecyclePool.prototype.add = function add () { + if (this._count >= this._data.length) { + this.resize(this._data.length * 2); + } + + return this._data[this._count++]; +}; + +RecyclePool.prototype.remove = function remove (idx) { + if (idx >= this._count) { + return; + } + + var last = this._count - 1; + var tmp = this._data[idx]; + this._data[idx] = this._data[last]; + this._data[last] = tmp; + this._count -= 1; +}; + +RecyclePool.prototype.sort = function sort$1 (cmp) { + return sort(this._data, 0, this._count, cmp); +}; + +Object.defineProperties( RecyclePool.prototype, prototypeAccessors$2 ); + +var _bufferPools = Array(8); +for (var i = 0; i < 8; ++i) { + _bufferPools[i] = []; +} + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var _a16_view = new Float32Array(16); +var _a16_proj = new Float32Array(16); +var _a16_viewProj = new Float32Array(16); + +// Add stage to renderer +renderer.addStage('transparent'); + +var ForwardRenderer = (function (superclass) { + function ForwardRenderer (device, builtin) { + superclass.call(this, device, builtin); + this._registerStage('transparent', this._transparentStage.bind(this)); + } + + if ( superclass ) ForwardRenderer.__proto__ = superclass; + ForwardRenderer.prototype = Object.create( superclass && superclass.prototype ); + ForwardRenderer.prototype.constructor = ForwardRenderer; + + ForwardRenderer.prototype.reset = function reset () { + this._reset(); }; - - var templates = [ - { - name: 'gray_sprite', - vert: '\n \nuniform mat4 viewProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\nattribute vec2 a_uv0;\nvarying vec2 uv0;\nvoid main () {\n vec4 pos = viewProj * vec4(a_position, 1);\n v_fragmentColor = a_color;\n uv0 = a_uv0;\n gl_Position = pos;\n}', - frag: '\n \nuniform sampler2D texture;\nvarying vec2 uv0;\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 c = v_fragmentColor * texture2D(texture, uv0);\n float gray = 0.2126*c.r + 0.7152*c.g + 0.0722*c.b;\n gl_FragColor = vec4(gray, gray, gray, c.a);\n}', - defines: [ - ], - }, - { - name: 'sprite', - vert: '\n \nuniform mat4 viewProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\n#ifdef useModel\n uniform mat4 model;\n#endif\n#ifdef useTexture\n attribute vec2 a_uv0;\n varying vec2 uv0;\n#endif\nvoid main () {\n mat4 mvp;\n #ifdef useModel\n mvp = viewProj * model;\n #else\n mvp = viewProj;\n #endif\n vec4 pos = mvp * vec4(a_position, 1);\n v_fragmentColor = a_color;\n \n #ifdef useTexture\n uv0 = a_uv0;\n #endif\n gl_Position = pos;\n}', - frag: '\n \n#ifdef useTexture\n uniform sampler2D texture;\n varying vec2 uv0;\n#endif\n#ifdef alphaTest\n uniform float alphaThreshold;\n#endif\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 o = v_fragmentColor;\n #ifdef useTexture\n o *= texture2D(texture, uv0);\n #endif\n #ifdef alphaTest\n if (o.a <= alphaThreshold)\n discard;\n #endif\n gl_FragColor = o;\n}', - defines: [ - { name: 'useTexture', }, - { name: 'useModel', }, - { name: 'alphaTest', } ], - }, - { - name: 'vfx_emitter', - vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', - frag: '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D noise;\nuniform sampler2D state;\nuniform vec2 statesize;\nuniform vec2 noisesize;\nuniform bool stopped;\nuniform float dt;\nuniform float mode;\nuniform float noiseId;\nuniform float emitVar;\nuniform float life;\nuniform float lifeVar;\nuniform vec2 pos;\nuniform vec2 posVar;\nuniform vec4 color;\nuniform vec4 colorVar;\n \nuniform vec4 endColor;\nuniform vec4 endColorVar;\nuniform float size;\nuniform float sizeVar;\nuniform float endSize;\nuniform float endSizeVar;\nuniform float rot;\nuniform float rotVar;\nuniform float endRot;\nuniform float endRotVar;\nuniform float angle;\nuniform float angleVar;\nuniform float speed;\nuniform float speedVar;\nuniform float radial;\nuniform float radialVar;\nuniform float tangent;\nuniform float tangentVar;\nuniform float radius;\nuniform float radiusVar;\nuniform float endRadius;\nuniform float endRadiusVar;\nuniform float rotatePS;\nuniform float rotatePSVar;\nuniform float sizeScale;\nuniform float accelScale;\nuniform float radiusScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float NOISE_SCALE = 10000.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nconst float COLOR_SCALE = 1.0;\nconst float LIFE_SCALE = 100.0;\nconst float START_SIZE_EQUAL_TO_END_SIZE = -1.0;\nconst float START_RADIUS_EQUAL_TO_END_RADIUS = -1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nfloat randomMinus1To1(vec2 randomD) {\n float random = decode(randomD, NOISE_SCALE);\n return (random - 0.5) * 2.0;\n}\nbool doEmit (vec4 randomD) {\n float random1 = decode(randomD.rg, NOISE_SCALE);\n if (!stopped && (life + lifeVar) * random1 < life) {\n return true;\n }\n else {\n return false;\n }\n}\nvec4 initLife (vec4 data, vec4 randomD) {\n \n if (doEmit(randomD)) {\n float random2 = decode(randomD.ba, NOISE_SCALE);\n float plife = life + lifeVar * random2;\n vec2 l = encode(plife, LIFE_SCALE);\n return vec4(l, l);\n }\n else {\n return data;\n }\n}\nvec4 initColor (float randr, float randg, float randb, float randa) {\n vec4 random = vec4(randr, randg, randb, randa);\n vec4 result = clamp(color + colorVar * random, 0.0, 255.0);\n return result / 255.0;\n}\nvec4 initDeltaRG (vec2 startR, vec2 random) {\n vec2 start = clamp(color.rg + colorVar.rg * startR, 0.0, 255.0);\n vec2 end = clamp(endColor.rg + endColorVar.rg * random, 0.0, 255.0);\n vec2 delta = end - start;\n return vec4(encode(delta.x, COLOR_SCALE), encode(delta.y, COLOR_SCALE));\n}\nvec4 initDeltaBA (vec2 startR, vec2 random) {\n vec2 start = clamp(color.ba + colorVar.ba * startR, 0.0, 255.0);\n vec2 end = clamp(endColor.ba + endColorVar.ba * random, 0.0, 255.0);\n vec2 delta = end - start;\n return vec4(encode(delta.x, COLOR_SCALE), encode(delta.y, COLOR_SCALE));\n}\nvec4 initSize (float rand1, float rand2) {\n float start = max(0.0, size + sizeVar * rand1);\n if (endSize == START_SIZE_EQUAL_TO_END_SIZE) {\n float delta = 0.0;\n return vec4(encode(start, sizeScale), encode(delta, sizeScale));\n }\n else {\n float end = max(0.0, endSize + endSizeVar * rand2);\n float delta = end - start;\n return vec4(encode(start, sizeScale), encode(delta, sizeScale));\n }\n}\nvec4 initRotation (float rand1, float rand2) {\n float start = rot + rotVar * rand1;\n float end = endRot + endRotVar * rand2;\n float delta = end - start;\n return vec4(encode(start, ROTATION_SCALE), encode(delta, ROTATION_SCALE));\n}\nvec4 initControl1 (float rand1, float rand2) {\n \n if (mode == 0.0) {\n float pAngle = angle + angleVar * rand1;\n float dirX = cos(pAngle);\n float dirY = sin(pAngle);\n float pSpeed = speed + speedVar * rand2;\n return vec4(encode(dirX * pSpeed, POSITION_SCALE), encode(dirY * pSpeed, POSITION_SCALE));\n }\n \n else {\n float pAngle = angle + angleVar * rand1;\n float pRadius = radius + radiusVar * rand2;\n return vec4(encode(pAngle, ROTATION_SCALE), encode(pRadius, radiusScale));\n }\n}\nvec4 initControl2 (float startR1, float rand1, float rand2) {\n \n if (mode == 0.0) {\n float pRadial = radial + radialVar * rand1;\n float pTangent = tangent + tangentVar * rand2;\n return vec4(encode(pRadial, accelScale), encode(pTangent, accelScale));\n }\n \n else {\n float degreesPerSecond = rotatePS + rotatePSVar * rand1;\n float pDeltaRadius;\n if (endRadius == START_RADIUS_EQUAL_TO_END_RADIUS) {\n pDeltaRadius = 0.0;\n }\n else {\n float pRadius = radius + radiusVar * startR1;\n pDeltaRadius = (endRadius + endRadiusVar * rand2 - pRadius);\n }\n return vec4(encode(degreesPerSecond, ROTATION_SCALE), encode(pDeltaRadius, radiusScale));\n }\n}\nvec4 initPos (float rand1, float rand2) {\n vec2 result = pos + posVar * vec2(rand1, rand2);\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n}\nvoid main() {\n vec2 pixel = floor(index * statesize);\n vec2 pindex = floor(pixel / 3.0);\n vec2 temp = mod(pixel, vec2(3.0, 3.0));\n float id = floor(temp.y * 3.0 + temp.x);\n vec2 noffset = vec2(floor(noiseId / 4.0), mod(noiseId, 4.0));\n vec2 nid = pixel + noffset;\n vec4 randomD = texture2D(noise, nid / noisesize);\n \n vec4 lifeData = texture2D(state, pindex * 3.0 / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n float life = decode(lifeData.ba, LIFE_SCALE);\n \n if (id == 0.0) {\n vec4 data = texture2D(state, index);\n if (rest <= 0.0) {\n gl_FragColor = initLife(data, randomD);\n }\n else {\n gl_FragColor = data;\n }\n return;\n }\n \n if (rest > 0.0) {\n vec4 data = texture2D(state, index);\n gl_FragColor = data;\n return;\n }\n vec2 lifeNid = pindex * 3.0 + noffset;\n vec4 lifeRandomD = texture2D(noise, lifeNid / noisesize);\n bool emitting = doEmit(lifeRandomD);\n if (!emitting) {\n vec4 data = texture2D(state, index);\n gl_FragColor = data;\n return;\n }\n \n float random1 = randomMinus1To1(randomD.rg);\n float random2 = randomMinus1To1(randomD.ba);\n \n if (id == 1.0) {\n vec4 randomD3 = texture2D(noise, vec2(nid.x - 1.0, nid.y + 1.0) / noisesize);\n float random3 = randomMinus1To1(randomD3.rg);\n float random4 = randomMinus1To1(randomD3.ba);\n gl_FragColor = initColor(random1, random2, random3, random4);\n return;\n }\n \n if (id == 2.0) {\n vec4 randomD1 = texture2D(noise, vec2(nid.x - 1.0, nid.y) / noisesize);\n float startR1 = randomMinus1To1(randomD1.rg);\n float startR2 = randomMinus1To1(randomD1.ba);\n vec2 startR = vec2(startR1, startR2);\n gl_FragColor = initDeltaRG(startR, vec2(random1, random2));\n return;\n }\n \n if (id == 3.0) {\n vec2 startR = vec2(random1, random2);\n gl_FragColor = initDeltaBA(startR, vec2(random1, random2));\n return;\n }\n \n if (id == 4.0) {\n gl_FragColor = initSize(random1, random2);\n return;\n }\n \n if (id == 5.0) {\n gl_FragColor = initRotation(random1, random2);\n return;\n }\n \n if (id == 6.0) {\n gl_FragColor = initControl1(random1, random2);\n return;\n }\n \n if (id == 7.0) {\n vec4 randomD6 = texture2D(noise, vec2(nid.x - 1.0, nid.y) / noisesize);\n float startR1 = randomMinus1To1(randomD6.rg);\n gl_FragColor = initControl2(startR1, random1, random2);\n return;\n }\n \n if (id == 8.0) {\n gl_FragColor = initPos(random1, random2);\n return;\n }\n}', - defines: [ - ], - }, - { - name: 'vfx_particle', - vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nuniform mat4 model;\nuniform mat4 viewProj;\nuniform sampler2D state;\nuniform sampler2D quad;\nuniform vec2 statesize;\nuniform vec2 quadsize;\nuniform float z;\nuniform vec2 lb;\nuniform vec2 rt;\nvarying lowp vec4 v_fragmentColor;\nvarying vec2 uv0;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvoid main() {\n vec2 sIndex = floor(a_quad / 2.0) * 3.0;\n vec4 lifeData = texture2D(state, sIndex / statesize);\n float life = decode(lifeData.rg, LIFE_SCALE);\n if (life <= 0.0) {\n v_fragmentColor = vec4(0.0, 0.0, 0.0, 0.0);\n uv0 = vec2(0.0, 0.0);\n gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n }\n else {\n vec2 posIndex = a_quad / quadsize;\n vec4 posData = texture2D(quad, posIndex);\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n vec2 cIndex = vec2(sIndex.x + 1.0, sIndex.y) / statesize;\n vec4 color = texture2D(state, cIndex);\n v_fragmentColor = color;\n float u, v;\n vec2 uvId = mod(a_quad, vec2(2.0));\n if (uvId.x == 0.0) {\n u = lb.x;\n }\n else {\n u = rt.x;\n }\n if (uvId.y == 0.0) {\n v = lb.y;\n }\n else {\n v = rt.y;\n }\n uv0 = vec2(u, v);\n gl_Position = viewProj * model * vec4(pos, z, 1.0);\n } \n}\n', - frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D texture;\nvarying vec2 uv0;\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 o = v_fragmentColor;\n o *= texture2D(texture, uv0);\n gl_FragColor = o;\n}', - defines: [ - ], - }, - { - name: 'vfx_quad', - vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', - frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D state;\nuniform vec2 quadsize;\nuniform vec2 statesize;\nuniform float sizeScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nvoid main() {\n vec2 pixel = floor(index * quadsize);\n vec2 pIndex = floor(pixel / 2.0) * 3.0;\n vec4 lifeData = texture2D(state, pIndex / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n if (rest <= 0.0) {\n gl_FragColor = vec4(encode(0.0, POSITION_SCALE), encode(0.0, POSITION_SCALE));\n return;\n }\n vec2 dataIndex = (pIndex + 2.0) / statesize;\n vec4 posData = texture2D(state, dataIndex);\n float x = decode(posData.rg, POSITION_SCALE);\n float y = decode(posData.ba, POSITION_SCALE);\n vec2 pos = vec2(x, y);\n dataIndex = (pIndex + 1.0) / statesize;\n vec4 sizeData = texture2D(state, dataIndex);\n float size = decode(sizeData.rg, sizeScale);\n dataIndex.x = (pIndex.x + 2.0) / statesize.x;\n dataIndex.y = (pIndex.y + 1.0) / statesize.y;\n vec4 rotData = texture2D(state, dataIndex);\n float rot = radians(mod(decode(rotData.rg, ROTATION_SCALE), 180.0));\n float a = cos(rot);\n float b = -sin(rot);\n float c = -b;\n float d = a;\n vec2 vert = (mod(pixel, vec2(2.0)) - 0.5) * size;\n x = vert.x * a + vert.y * c + pos.x;\n y = vert.x * b + vert.y * d + pos.y;\n gl_FragColor = vec4(encode(x, POSITION_SCALE), encode(y, POSITION_SCALE));\n}\n', - defines: [ - ], - }, - { - name: 'vfx_update', - vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', - frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D state;\nuniform vec2 statesize;\nuniform float dt;\nuniform float mode;\nuniform vec2 gravity;\nuniform float sizeScale;\nuniform float accelScale;\nuniform float radiusScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float MAX_VALUE = BASE * BASE;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nconst float COLOR_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nvec4 updateLife (vec4 data) {\n float rest = decode(data.rg, LIFE_SCALE);\n rest -= dt;\n return vec4(encode(rest, LIFE_SCALE), data.ba);\n}\nvec4 updateColor (vec4 color, vec4 deltaRG, vec4 deltaBA, float life) {\n float r = decode(deltaRG.rg, COLOR_SCALE);\n float g = decode(deltaRG.ba, COLOR_SCALE);\n float b = decode(deltaBA.rg, COLOR_SCALE);\n float a = decode(deltaBA.ba, COLOR_SCALE);\n vec4 deltaColor = vec4(r, g, b, a) / 255.0;\n \n color = clamp(color + deltaColor * dt / life, 0.0, 1.0);\n return color;\n}\nvec4 updateSize (vec4 data, float life) {\n float size = decode(data.rg, sizeScale);\n float deltaSize = decode(data.ba, sizeScale);\n size = clamp(size + deltaSize * dt / life, 0.0, MAX_VALUE);\n return vec4(encode(size, sizeScale), data.ba);\n}\nvec4 updateRotation (vec4 data, float life) {\n float rotation = decode(data.rg, ROTATION_SCALE);\n float deltaRotation = decode(data.ba, ROTATION_SCALE);\n rotation = mod(rotation + deltaRotation * dt / life, 180.0);\n return vec4(encode(rotation, ROTATION_SCALE), data.ba);\n}\nvec4 updateControl (vec4 control1, vec4 control2, vec4 posData, float life) {\n \n if (mode == 0.0) {\n vec2 dir = vec2(decode(control1.rg, POSITION_SCALE), decode(control1.ba, POSITION_SCALE));\n float radialAccel = decode(control2.rg, accelScale);\n float tangentialAccel = decode(control2.ba, accelScale);\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n vec2 radial = normalize(pos);\n vec2 tangential = vec2(-radial.y, radial.x);\n radial = radial * radialAccel;\n tangential = tangential * tangentialAccel;\n vec2 result = dir + (radial + tangentialAccel + gravity) * dt;\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n }\n \n else {\n float angle = mod(decode(control1.rg, ROTATION_SCALE), 180.0);\n float radius = decode(control1.ba, radiusScale);\n float degreesPerSecond = decode(control2.rg, ROTATION_SCALE);\n float deltaRadius = decode(control2.ba, radiusScale);\n angle += degreesPerSecond * dt;\n radius += deltaRadius * dt / life;\n return vec4(encode(angle, ROTATION_SCALE), encode(radius, radiusScale));\n }\n}\nvec4 updatePos (vec4 posData, vec4 control) {\n vec2 result;\n \n if (mode == 0.0) {\n vec2 dir = vec2(decode(control.rg, POSITION_SCALE), decode(control.ba, POSITION_SCALE));\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n result = pos + dir * dt;\n }\n \n else {\n float angle = radians(mod(decode(control.rg, ROTATION_SCALE), 180.0));\n float radius = decode(control.ba, radiusScale);\n result.x = -cos(angle) * radius;\n result.y = -sin(angle) * radius;\n }\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n}\nvoid main() {\n vec2 pixel = floor(index * statesize);\n vec2 pindex = floor(pixel / 3.0);\n vec2 temp = mod(pixel, vec2(3.0));\n float id = floor(temp.y * 3.0 + temp.x);\n \n vec4 data = texture2D(state, index);\n vec4 lifeData = texture2D(state, pindex * 3.0 / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n if (rest <= 0.0) {\n gl_FragColor = data;\n return;\n }\n \n if (id == 2.0 || id == 3.0 || id == 7.0) {\n gl_FragColor = data;\n return;\n }\n float life = decode(lifeData.ba, LIFE_SCALE);\n \n if (id == 0.0) {\n gl_FragColor = updateLife(data);\n return;\n }\n \n if (id == 1.0) {\n vec2 rgIndex = vec2(pixel.x + 1.0, pixel.y) / statesize;\n vec4 deltaRG = texture2D(state, rgIndex);\n vec2 baIndex = vec2(pixel.x - 1.0, pixel.y + 1.0) / statesize;\n vec4 deltaBA = texture2D(state, baIndex);\n gl_FragColor = updateColor(data, deltaRG, deltaBA, life);\n return;\n }\n \n if (id == 4.0) {\n gl_FragColor = updateSize(data, life);\n return;\n }\n \n if (id == 5.0) {\n gl_FragColor = updateRotation(data, life);\n return;\n }\n \n if (id == 6.0) {\n vec2 ctrlIndex = vec2(pixel.x + 1.0, pixel.y) / statesize;\n vec4 control2 = texture2D(state, ctrlIndex);\n vec2 posIndex = vec2(pixel.x + 2.0, pixel.y) / statesize;\n vec4 pos = texture2D(state, posIndex);\n gl_FragColor = updateControl(data, control2, pos, life);\n return;\n }\n \n if (id == 8.0) {\n vec2 ctrlIndex = vec2(pixel.x - 2.0, pixel.y) / statesize;\n vec4 control1 = texture2D(state, ctrlIndex);\n gl_FragColor = updatePos(data, control1);\n return;\n }\n}\n', - defines: [ - ], - } ]; - - var shaders = { - chunks: chunks, - templates: templates + + ForwardRenderer.prototype.render = function render (scene) { + var this$1 = this; + + this._reset(); + + scene._cameras.sort(function (a, b) { + if (a._depth > b._depth) { return 1; } + else if (a._depth < b._depth) { return -1; } + else { return 0; } + }); + + for (var i = 0; i < scene._cameras.length; ++i) { + var camera = scene._cameras.data[i]; + this$1.renderCamera(camera, scene); + } }; - - // Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - /** - * BaseRenderData is a core data abstraction for renderer, this is a abstract class. - * An inherited render data type should define raw vertex datas. - * User should also define the effect, vertex count and index count. - */ - var BaseRenderData = function BaseRenderData () { - this.material = null; - this.vertexCount = 0; - this.indiceCount = 0; + + ForwardRenderer.prototype.renderCamera = function renderCamera (camera, scene) { + var canvas = this._device._gl.canvas; + + var view = camera.view; + var dirty = camera.dirty; + if (!view) { + view = this._requestView(); + dirty = true; + } + if (dirty) { + var width = canvas.width; + var height = canvas.height; + if (camera._framebuffer) { + width = camera._framebuffer._width; + height = camera._framebuffer._height; + } + camera.extractView(view, width, height); + } + this._render(view, scene); }; - - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var _pool; - var _dataPool = new Pool(function () { - return { - x: 0.0, - y: 0.0, - u: 0.0, - v: 0.0, - color: 0 - }; - }, 128); - - /** - * RenderData is most widely used render data type. - * It describes raw vertex data with a fixed data layout. - * Each vertex is described by five property: x, y, u, v, color. The data layout might be extended in the future. - * Vertex data objects are managed automatically by RenderData, user only need to set the dataLength property. - * User can also define rendering index orders for the vertex list. - */ - var RenderData = (function (BaseRenderData$$1) { - function RenderData () { - BaseRenderData$$1.call(this); - this._data = []; - this._indices = []; - - this._pivotX = 0; - this._pivotY = 0; - this._width = 0; - this._height = 0; - - this.uvDirty = true; + + ForwardRenderer.prototype._transparentStage = function _transparentStage (view, items) { + var this$1 = this; + + // update uniforms + this._device.setUniform('view', mat4.array(_a16_view, view._matView)); + this._device.setUniform('proj', mat4.array(_a16_proj, view._matProj)); + this._device.setUniform('viewProj', mat4.array(_a16_viewProj, view._matViewProj)); + + // draw it + for (var i = 0; i < items.length; ++i) { + var item = items.data[i]; + this$1._draw(item); + } + }; + + return ForwardRenderer; +}(renderer.Base)); + +var chunks = { +}; + +var templates = [ + { + name: 'gray_sprite', + vert: '\n \nuniform mat4 viewProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\nattribute vec2 a_uv0;\nvarying vec2 uv0;\nvoid main () {\n vec4 pos = viewProj * vec4(a_position, 1);\n v_fragmentColor = a_color;\n uv0 = a_uv0;\n gl_Position = pos;\n}', + frag: '\n \nuniform sampler2D texture;\nvarying vec2 uv0;\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 c = v_fragmentColor * texture2D(texture, uv0);\n float gray = 0.2126*c.r + 0.7152*c.g + 0.0722*c.b;\n gl_FragColor = vec4(gray, gray, gray, c.a);\n}', + defines: [ + ], + }, + { + name: 'sprite', + vert: '\n \nuniform mat4 viewProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\n#ifdef useModel\n uniform mat4 model;\n#endif\n#ifdef useTexture\n attribute vec2 a_uv0;\n varying vec2 uv0;\n#endif\nvoid main () {\n mat4 mvp;\n #ifdef useModel\n mvp = viewProj * model;\n #else\n mvp = viewProj;\n #endif\n vec4 pos = mvp * vec4(a_position, 1);\n v_fragmentColor = a_color;\n \n #ifdef useTexture\n uv0 = a_uv0;\n #endif\n gl_Position = pos;\n}', + frag: '\n \n#ifdef useTexture\n uniform sampler2D texture;\n varying vec2 uv0;\n#endif\n#ifdef alphaTest\n uniform float alphaThreshold;\n#endif\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 o = v_fragmentColor;\n #ifdef useTexture\n o *= texture2D(texture, uv0);\n #endif\n #ifdef alphaTest\n if (o.a <= alphaThreshold)\n discard;\n #endif\n gl_FragColor = o;\n}', + defines: [ + { name: 'useTexture', }, + { name: 'useModel', }, + { name: 'alphaTest', } ], + }, + { + name: 'vfx_emitter', + vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', + frag: '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D noise;\nuniform sampler2D state;\nuniform vec2 statesize;\nuniform vec2 noisesize;\nuniform bool stopped;\nuniform float dt;\nuniform float mode;\nuniform float noiseId;\nuniform float emitVar;\nuniform float life;\nuniform float lifeVar;\nuniform vec2 pos;\nuniform vec2 posVar;\nuniform vec4 color;\nuniform vec4 colorVar;\n \nuniform vec4 endColor;\nuniform vec4 endColorVar;\nuniform float size;\nuniform float sizeVar;\nuniform float endSize;\nuniform float endSizeVar;\nuniform float rot;\nuniform float rotVar;\nuniform float endRot;\nuniform float endRotVar;\nuniform float angle;\nuniform float angleVar;\nuniform float speed;\nuniform float speedVar;\nuniform float radial;\nuniform float radialVar;\nuniform float tangent;\nuniform float tangentVar;\nuniform float radius;\nuniform float radiusVar;\nuniform float endRadius;\nuniform float endRadiusVar;\nuniform float rotatePS;\nuniform float rotatePSVar;\nuniform float sizeScale;\nuniform float accelScale;\nuniform float radiusScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float NOISE_SCALE = 10000.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nconst float COLOR_SCALE = 1.0;\nconst float LIFE_SCALE = 100.0;\nconst float START_SIZE_EQUAL_TO_END_SIZE = -1.0;\nconst float START_RADIUS_EQUAL_TO_END_RADIUS = -1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nfloat randomMinus1To1(vec2 randomD) {\n float random = decode(randomD, NOISE_SCALE);\n return (random - 0.5) * 2.0;\n}\nbool doEmit (vec4 randomD) {\n float random1 = decode(randomD.rg, NOISE_SCALE);\n if (!stopped && (life + lifeVar) * random1 < life) {\n return true;\n }\n else {\n return false;\n }\n}\nvec4 initLife (vec4 data, vec4 randomD) {\n \n if (doEmit(randomD)) {\n float random2 = decode(randomD.ba, NOISE_SCALE);\n float plife = life + lifeVar * random2;\n vec2 l = encode(plife, LIFE_SCALE);\n return vec4(l, l);\n }\n else {\n return data;\n }\n}\nvec4 initColor (float randr, float randg, float randb, float randa) {\n vec4 random = vec4(randr, randg, randb, randa);\n vec4 result = clamp(color + colorVar * random, 0.0, 255.0);\n return result / 255.0;\n}\nvec4 initDeltaRG (vec2 startR, vec2 random) {\n vec2 start = clamp(color.rg + colorVar.rg * startR, 0.0, 255.0);\n vec2 end = clamp(endColor.rg + endColorVar.rg * random, 0.0, 255.0);\n vec2 delta = end - start;\n return vec4(encode(delta.x, COLOR_SCALE), encode(delta.y, COLOR_SCALE));\n}\nvec4 initDeltaBA (vec2 startR, vec2 random) {\n vec2 start = clamp(color.ba + colorVar.ba * startR, 0.0, 255.0);\n vec2 end = clamp(endColor.ba + endColorVar.ba * random, 0.0, 255.0);\n vec2 delta = end - start;\n return vec4(encode(delta.x, COLOR_SCALE), encode(delta.y, COLOR_SCALE));\n}\nvec4 initSize (float rand1, float rand2) {\n float start = max(0.0, size + sizeVar * rand1);\n if (endSize == START_SIZE_EQUAL_TO_END_SIZE) {\n float delta = 0.0;\n return vec4(encode(start, sizeScale), encode(delta, sizeScale));\n }\n else {\n float end = max(0.0, endSize + endSizeVar * rand2);\n float delta = end - start;\n return vec4(encode(start, sizeScale), encode(delta, sizeScale));\n }\n}\nvec4 initRotation (float rand1, float rand2) {\n float start = rot + rotVar * rand1;\n float end = endRot + endRotVar * rand2;\n float delta = end - start;\n return vec4(encode(start, ROTATION_SCALE), encode(delta, ROTATION_SCALE));\n}\nvec4 initControl1 (float rand1, float rand2) {\n \n if (mode == 0.0) {\n float pAngle = angle + angleVar * rand1;\n float dirX = cos(pAngle);\n float dirY = sin(pAngle);\n float pSpeed = speed + speedVar * rand2;\n return vec4(encode(dirX * pSpeed, POSITION_SCALE), encode(dirY * pSpeed, POSITION_SCALE));\n }\n \n else {\n float pAngle = angle + angleVar * rand1;\n float pRadius = radius + radiusVar * rand2;\n return vec4(encode(pAngle, ROTATION_SCALE), encode(pRadius, radiusScale));\n }\n}\nvec4 initControl2 (float startR1, float rand1, float rand2) {\n \n if (mode == 0.0) {\n float pRadial = radial + radialVar * rand1;\n float pTangent = tangent + tangentVar * rand2;\n return vec4(encode(pRadial, accelScale), encode(pTangent, accelScale));\n }\n \n else {\n float degreesPerSecond = rotatePS + rotatePSVar * rand1;\n float pDeltaRadius;\n if (endRadius == START_RADIUS_EQUAL_TO_END_RADIUS) {\n pDeltaRadius = 0.0;\n }\n else {\n float pRadius = radius + radiusVar * startR1;\n pDeltaRadius = (endRadius + endRadiusVar * rand2 - pRadius);\n }\n return vec4(encode(degreesPerSecond, ROTATION_SCALE), encode(pDeltaRadius, radiusScale));\n }\n}\nvec4 initPos (float rand1, float rand2) {\n vec2 result = pos + posVar * vec2(rand1, rand2);\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n}\nvoid main() {\n vec2 pixel = floor(index * statesize);\n vec2 pindex = floor(pixel / 3.0);\n vec2 temp = mod(pixel, vec2(3.0, 3.0));\n float id = floor(temp.y * 3.0 + temp.x);\n vec2 noffset = vec2(floor(noiseId / 4.0), mod(noiseId, 4.0));\n vec2 nid = pixel + noffset;\n vec4 randomD = texture2D(noise, nid / noisesize);\n \n vec4 lifeData = texture2D(state, pindex * 3.0 / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n float life = decode(lifeData.ba, LIFE_SCALE);\n \n if (id == 0.0) {\n vec4 data = texture2D(state, index);\n if (rest <= 0.0) {\n gl_FragColor = initLife(data, randomD);\n }\n else {\n gl_FragColor = data;\n }\n return;\n }\n \n if (rest > 0.0) {\n vec4 data = texture2D(state, index);\n gl_FragColor = data;\n return;\n }\n vec2 lifeNid = pindex * 3.0 + noffset;\n vec4 lifeRandomD = texture2D(noise, lifeNid / noisesize);\n bool emitting = doEmit(lifeRandomD);\n if (!emitting) {\n vec4 data = texture2D(state, index);\n gl_FragColor = data;\n return;\n }\n \n float random1 = randomMinus1To1(randomD.rg);\n float random2 = randomMinus1To1(randomD.ba);\n \n if (id == 1.0) {\n vec4 randomD3 = texture2D(noise, vec2(nid.x - 1.0, nid.y + 1.0) / noisesize);\n float random3 = randomMinus1To1(randomD3.rg);\n float random4 = randomMinus1To1(randomD3.ba);\n gl_FragColor = initColor(random1, random2, random3, random4);\n return;\n }\n \n if (id == 2.0) {\n vec4 randomD1 = texture2D(noise, vec2(nid.x - 1.0, nid.y) / noisesize);\n float startR1 = randomMinus1To1(randomD1.rg);\n float startR2 = randomMinus1To1(randomD1.ba);\n vec2 startR = vec2(startR1, startR2);\n gl_FragColor = initDeltaRG(startR, vec2(random1, random2));\n return;\n }\n \n if (id == 3.0) {\n vec2 startR = vec2(random1, random2);\n gl_FragColor = initDeltaBA(startR, vec2(random1, random2));\n return;\n }\n \n if (id == 4.0) {\n gl_FragColor = initSize(random1, random2);\n return;\n }\n \n if (id == 5.0) {\n gl_FragColor = initRotation(random1, random2);\n return;\n }\n \n if (id == 6.0) {\n gl_FragColor = initControl1(random1, random2);\n return;\n }\n \n if (id == 7.0) {\n vec4 randomD6 = texture2D(noise, vec2(nid.x - 1.0, nid.y) / noisesize);\n float startR1 = randomMinus1To1(randomD6.rg);\n gl_FragColor = initControl2(startR1, random1, random2);\n return;\n }\n \n if (id == 8.0) {\n gl_FragColor = initPos(random1, random2);\n return;\n }\n}', + defines: [ + ], + }, + { + name: 'vfx_particle', + vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nuniform mat4 model;\nuniform mat4 viewProj;\nuniform sampler2D state;\nuniform sampler2D quad;\nuniform vec2 statesize;\nuniform vec2 quadsize;\nuniform float z;\nuniform vec2 lb;\nuniform vec2 rt;\nvarying lowp vec4 v_fragmentColor;\nvarying vec2 uv0;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvoid main() {\n vec2 sIndex = floor(a_quad / 2.0) * 3.0;\n vec4 lifeData = texture2D(state, sIndex / statesize);\n float life = decode(lifeData.rg, LIFE_SCALE);\n if (life <= 0.0) {\n v_fragmentColor = vec4(0.0, 0.0, 0.0, 0.0);\n uv0 = vec2(0.0, 0.0);\n gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n }\n else {\n vec2 posIndex = a_quad / quadsize;\n vec4 posData = texture2D(quad, posIndex);\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n vec2 cIndex = vec2(sIndex.x + 1.0, sIndex.y) / statesize;\n vec4 color = texture2D(state, cIndex);\n v_fragmentColor = color;\n float u, v;\n vec2 uvId = mod(a_quad, vec2(2.0));\n if (uvId.x == 0.0) {\n u = lb.x;\n }\n else {\n u = rt.x;\n }\n if (uvId.y == 0.0) {\n v = lb.y;\n }\n else {\n v = rt.y;\n }\n uv0 = vec2(u, v);\n gl_Position = viewProj * model * vec4(pos, z, 1.0);\n } \n}\n', + frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D texture;\nvarying vec2 uv0;\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 o = v_fragmentColor;\n o *= texture2D(texture, uv0);\n gl_FragColor = o;\n}', + defines: [ + ], + }, + { + name: 'vfx_quad', + vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', + frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D state;\nuniform vec2 quadsize;\nuniform vec2 statesize;\nuniform float sizeScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nvoid main() {\n vec2 pixel = floor(index * quadsize);\n vec2 pIndex = floor(pixel / 2.0) * 3.0;\n vec4 lifeData = texture2D(state, pIndex / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n if (rest <= 0.0) {\n gl_FragColor = vec4(encode(0.0, POSITION_SCALE), encode(0.0, POSITION_SCALE));\n return;\n }\n vec2 dataIndex = (pIndex + 2.0) / statesize;\n vec4 posData = texture2D(state, dataIndex);\n float x = decode(posData.rg, POSITION_SCALE);\n float y = decode(posData.ba, POSITION_SCALE);\n vec2 pos = vec2(x, y);\n dataIndex = (pIndex + 1.0) / statesize;\n vec4 sizeData = texture2D(state, dataIndex);\n float size = decode(sizeData.rg, sizeScale);\n dataIndex.x = (pIndex.x + 2.0) / statesize.x;\n dataIndex.y = (pIndex.y + 1.0) / statesize.y;\n vec4 rotData = texture2D(state, dataIndex);\n float rot = radians(mod(decode(rotData.rg, ROTATION_SCALE), 180.0));\n float a = cos(rot);\n float b = -sin(rot);\n float c = -b;\n float d = a;\n vec2 vert = (mod(pixel, vec2(2.0)) - 0.5) * size;\n x = vert.x * a + vert.y * c + pos.x;\n y = vert.x * b + vert.y * d + pos.y;\n gl_FragColor = vec4(encode(x, POSITION_SCALE), encode(y, POSITION_SCALE));\n}\n', + defines: [ + ], + }, + { + name: 'vfx_update', + vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', + frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D state;\nuniform vec2 statesize;\nuniform float dt;\nuniform float mode;\nuniform vec2 gravity;\nuniform float sizeScale;\nuniform float accelScale;\nuniform float radiusScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float MAX_VALUE = BASE * BASE;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nconst float COLOR_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nvec4 updateLife (vec4 data) {\n float rest = decode(data.rg, LIFE_SCALE);\n rest -= dt;\n return vec4(encode(rest, LIFE_SCALE), data.ba);\n}\nvec4 updateColor (vec4 color, vec4 deltaRG, vec4 deltaBA, float life) {\n float r = decode(deltaRG.rg, COLOR_SCALE);\n float g = decode(deltaRG.ba, COLOR_SCALE);\n float b = decode(deltaBA.rg, COLOR_SCALE);\n float a = decode(deltaBA.ba, COLOR_SCALE);\n vec4 deltaColor = vec4(r, g, b, a) / 255.0;\n \n color = clamp(color + deltaColor * dt / life, 0.0, 1.0);\n return color;\n}\nvec4 updateSize (vec4 data, float life) {\n float size = decode(data.rg, sizeScale);\n float deltaSize = decode(data.ba, sizeScale);\n size = clamp(size + deltaSize * dt / life, 0.0, MAX_VALUE);\n return vec4(encode(size, sizeScale), data.ba);\n}\nvec4 updateRotation (vec4 data, float life) {\n float rotation = decode(data.rg, ROTATION_SCALE);\n float deltaRotation = decode(data.ba, ROTATION_SCALE);\n rotation = mod(rotation + deltaRotation * dt / life, 180.0);\n return vec4(encode(rotation, ROTATION_SCALE), data.ba);\n}\nvec4 updateControl (vec4 control1, vec4 control2, vec4 posData, float life) {\n \n if (mode == 0.0) {\n vec2 dir = vec2(decode(control1.rg, POSITION_SCALE), decode(control1.ba, POSITION_SCALE));\n float radialAccel = decode(control2.rg, accelScale);\n float tangentialAccel = decode(control2.ba, accelScale);\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n vec2 radial = normalize(pos);\n vec2 tangential = vec2(-radial.y, radial.x);\n radial = radial * radialAccel;\n tangential = tangential * tangentialAccel;\n vec2 result = dir + (radial + tangentialAccel + gravity) * dt;\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n }\n \n else {\n float angle = mod(decode(control1.rg, ROTATION_SCALE), 180.0);\n float radius = decode(control1.ba, radiusScale);\n float degreesPerSecond = decode(control2.rg, ROTATION_SCALE);\n float deltaRadius = decode(control2.ba, radiusScale);\n angle += degreesPerSecond * dt;\n radius += deltaRadius * dt / life;\n return vec4(encode(angle, ROTATION_SCALE), encode(radius, radiusScale));\n }\n}\nvec4 updatePos (vec4 posData, vec4 control) {\n vec2 result;\n \n if (mode == 0.0) {\n vec2 dir = vec2(decode(control.rg, POSITION_SCALE), decode(control.ba, POSITION_SCALE));\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n result = pos + dir * dt;\n }\n \n else {\n float angle = radians(mod(decode(control.rg, ROTATION_SCALE), 180.0));\n float radius = decode(control.ba, radiusScale);\n result.x = -cos(angle) * radius;\n result.y = -sin(angle) * radius;\n }\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n}\nvoid main() {\n vec2 pixel = floor(index * statesize);\n vec2 pindex = floor(pixel / 3.0);\n vec2 temp = mod(pixel, vec2(3.0));\n float id = floor(temp.y * 3.0 + temp.x);\n \n vec4 data = texture2D(state, index);\n vec4 lifeData = texture2D(state, pindex * 3.0 / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n if (rest <= 0.0) {\n gl_FragColor = data;\n return;\n }\n \n if (id == 2.0 || id == 3.0 || id == 7.0) {\n gl_FragColor = data;\n return;\n }\n float life = decode(lifeData.ba, LIFE_SCALE);\n \n if (id == 0.0) {\n gl_FragColor = updateLife(data);\n return;\n }\n \n if (id == 1.0) {\n vec2 rgIndex = vec2(pixel.x + 1.0, pixel.y) / statesize;\n vec4 deltaRG = texture2D(state, rgIndex);\n vec2 baIndex = vec2(pixel.x - 1.0, pixel.y + 1.0) / statesize;\n vec4 deltaBA = texture2D(state, baIndex);\n gl_FragColor = updateColor(data, deltaRG, deltaBA, life);\n return;\n }\n \n if (id == 4.0) {\n gl_FragColor = updateSize(data, life);\n return;\n }\n \n if (id == 5.0) {\n gl_FragColor = updateRotation(data, life);\n return;\n }\n \n if (id == 6.0) {\n vec2 ctrlIndex = vec2(pixel.x + 1.0, pixel.y) / statesize;\n vec4 control2 = texture2D(state, ctrlIndex);\n vec2 posIndex = vec2(pixel.x + 2.0, pixel.y) / statesize;\n vec4 pos = texture2D(state, posIndex);\n gl_FragColor = updateControl(data, control2, pos, life);\n return;\n }\n \n if (id == 8.0) {\n vec2 ctrlIndex = vec2(pixel.x - 2.0, pixel.y) / statesize;\n vec4 control1 = texture2D(state, ctrlIndex);\n gl_FragColor = updatePos(data, control1);\n return;\n }\n}\n', + defines: [ + ], + } ]; + +var shaders = { + chunks: chunks, + templates: templates +}; + +// Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + +/** + * BaseRenderData is a core data abstraction for renderer, this is a abstract class. + * An inherited render data type should define raw vertex datas. + * User should also define the effect, vertex count and index count. + */ +var BaseRenderData = function BaseRenderData () { + this.material = null; + this.vertexCount = 0; + this.indiceCount = 0; +}; + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var _pool; +var _dataPool = new Pool(function () { + return { + x: 0.0, + y: 0.0, + u: 0.0, + v: 0.0, + color: 0 + }; +}, 128); + +/** + * RenderData is most widely used render data type. + * It describes raw vertex data with a fixed data layout. + * Each vertex is described by five property: x, y, u, v, color. The data layout might be extended in the future. + * Vertex data objects are managed automatically by RenderData, user only need to set the dataLength property. + * User can also define rendering index orders for the vertex list. + */ +var RenderData = (function (BaseRenderData$$1) { + function RenderData () { + BaseRenderData$$1.call(this); + this._data = []; + this._indices = []; + + this._pivotX = 0; + this._pivotY = 0; + this._width = 0; + this._height = 0; + + this.uvDirty = true; + this.vertDirty = true; + } + + if ( BaseRenderData$$1 ) RenderData.__proto__ = BaseRenderData$$1; + RenderData.prototype = Object.create( BaseRenderData$$1 && BaseRenderData$$1.prototype ); + RenderData.prototype.constructor = RenderData; + + var prototypeAccessors = { type: {},dataLength: {} }; + + prototypeAccessors.type.get = function () { + return RenderData.type; + }; + + prototypeAccessors.dataLength.get = function () { + return this._data.length; + }; + + prototypeAccessors.dataLength.set = function (length) { + var data = this._data; + if (data.length !== length) { + // Free extra data + for (var i = length; i < data.length; i++) { + _dataPool.free(data[i]); + } + // Alloc needed data + for (var i$1 = data.length; i$1 < length; i$1++) { + data[i$1] = _dataPool.alloc(); + } + data.length = length; + } + }; + + RenderData.prototype.updateSizeNPivot = function updateSizeNPivot (width, height, pivotX, pivotY) { + if (width !== this._width || + height !== this._height || + pivotX !== this._pivotX || + pivotY !== this._pivotY) + { + this._width = width; + this._height = height; + this._pivotX = pivotX; + this._pivotY = pivotY; this.vertDirty = true; } + }; - if ( BaseRenderData$$1 ) RenderData.__proto__ = BaseRenderData$$1; - RenderData.prototype = Object.create( BaseRenderData$$1 && BaseRenderData$$1.prototype ); - RenderData.prototype.constructor = RenderData; - - var prototypeAccessors = { type: {},dataLength: {} }; - + RenderData.alloc = function alloc () { + return _pool.alloc(); + }; + + RenderData.free = function free (data) { + if (data instanceof RenderData) { + for (var i = data.length-1; i > 0; i--) { + _dataPool.free(data._data[i]); + } + data._data.length = 0; + data._indices.length = 0; + data.material = null; + data.uvDirty = true; + data.vertDirty = true; + data.vertexCount = 0; + data.indiceCount = 0; + _pool.free(data); + } + }; + + Object.defineProperties( RenderData.prototype, prototypeAccessors ); + + return RenderData; +}(BaseRenderData)); + +RenderData.type = 'RenderData'; + +_pool = new Pool(function () { + return new RenderData(); +}, 32); + +// Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + +/** + * IARenderData is user customized render data type, user should provide the entier input assembler. + * IARenderData just defines a property `ia` for accessing the input assembler. + * It doesn't manage memory so users should manage the memory of input assembler by themselves. + */ +var IARenderData = (function (BaseRenderData$$1) { + function IARenderData () { + BaseRenderData$$1.call(this); + this.ia = null; + } + + if ( BaseRenderData$$1 ) IARenderData.__proto__ = BaseRenderData$$1; + IARenderData.prototype = Object.create( BaseRenderData$$1 && BaseRenderData$$1.prototype ); + IARenderData.prototype.constructor = IARenderData; + + var prototypeAccessors = { type: {} }; + prototypeAccessors.type.get = function () { - return RenderData.type; - }; - - prototypeAccessors.dataLength.get = function () { - return this._data.length; - }; - - prototypeAccessors.dataLength.set = function (length) { - var data = this._data; - if (data.length !== length) { - // Free extra data - for (var i = length; i < data.length; i++) { - _dataPool.free(data[i]); - } - // Alloc needed data - for (var i$1 = data.length; i$1 < length; i$1++) { - data[i$1] = _dataPool.alloc(); - } - data.length = length; - } - }; - - RenderData.prototype.updateSizeNPivot = function updateSizeNPivot (width, height, pivotX, pivotY) { - if (width !== this._width || - height !== this._height || - pivotX !== this._pivotX || - pivotY !== this._pivotY) - { - this._width = width; - this._height = height; - this._pivotX = pivotX; - this._pivotY = pivotY; - this.vertDirty = true; - } + return IARenderData.type; }; + + Object.defineProperties( IARenderData.prototype, prototypeAccessors ); + + return IARenderData; +}(BaseRenderData)); + +IARenderData.type = 'IARenderData'; + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var BASE = 255; +var NOISE_SCALE = 10000; +var POS_SCALE = 1; +var LIFE_SCALE = 100; +var COLOR_SCALE = 1; +var ROTATION_SCALE = 1; +var MAX_SCALE = 500; +var _vertexFmt = new gfx.VertexFormat([ + { name: 'a_quad', type: gfx.ATTR_TYPE_FLOAT32, num: 2 } +]); + +var _dataOpts = { + width: 0, + height: 0, + minFilter: gfx.FILTER_NEAREST, + magFilter: gfx.FILTER_NEAREST, + wrapS: gfx.WRAP_CLAMP, + wrapT: gfx.WRAP_CLAMP, + format: gfx.TEXTURE_FMT_RGBA8, + images: [] +}; + +function encode (value, scale, outArr, offset) { + value = value * scale + BASE * BASE / 2; + outArr[offset] = Math.floor((value % BASE) / BASE * 255); + outArr[offset+1] = Math.floor(Math.floor(value / BASE) / BASE * 255); +} + +function decode (arr, offset, scale) { + return (((arr[offset] / 255) * BASE + + (arr[offset+1] / 255) * BASE * BASE) - BASE * BASE / 2) / scale; +} + +function clampf (value, min_inclusive, max_inclusive) { + return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive; +} + +var Particles = function Particles (device, renderer$$1, config) { + this._device = device; + this._config = config; + this._sizeScale = 1; + this._accelScale = 1; + this._radiusScale = 1; - RenderData.alloc = function alloc () { - return _pool.alloc(); - }; - - RenderData.free = function free (data) { - if (data instanceof RenderData) { - for (var i = data.length-1; i > 0; i--) { - _dataPool.free(data._data[i]); - } - data._data.length = 0; - data._indices.length = 0; - data.material = null; - data.uvDirty = true; - data.vertDirty = true; - data.vertexCount = 0; - data.indiceCount = 0; - _pool.free(data); + var opts = {}; + var programLib = renderer$$1._programLib; + this.programs = { + emitter: programLib.getProgram('vfx_emitter', opts), + update: programLib.getProgram('vfx_update', opts), + quad: programLib.getProgram('vfx_quad', opts), + }; + + this.textures = { + // need swap + state0: new gfx.Texture2D(device, opts), + state1: new gfx.Texture2D(device, opts), + // no swap needed + noise: new gfx.Texture2D(device, opts), + quads: new gfx.Texture2D(device, opts), + }; + + this.framebuffers = { + state0: new gfx.FrameBuffer(device, 0, 0, { + colors: [this.textures.state0] + }), + state1: new gfx.FrameBuffer(device, 0, 0, { + colors: [this.textures.state1] + }), + quads: new gfx.FrameBuffer(device, 0, 0, { + colors: [this.textures.quads] + }) + }; + + var verts = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]); + var indices = new Uint8Array([ 0, 1, 2, 1, 3, 2]); + this.buffers = { + updateVB: new gfx.VertexBuffer(device, _vertexFmt, gfx.USAGE_STATIC, verts, 4), + updateIB: new gfx.IndexBuffer(device, gfx.INDEX_FMT_UINT8, gfx.USAGE_STATIC, indices, 6), + indexes: null, + particleCache: null + }; + + this._elapsed = 0; + this._stopped = false; + + this.updateMaxParticle(config); + this.updateSizeScale(config); + this.updateRadiusScale(config); + this.updateAccelScale(config); + + // Vector uniforms + this._pos = new Float32Array([config.sourcePos.x, config.sourcePos.y]); + this._posVar = new Float32Array([config.posVar.x, config.posVar.y]); + this._gravity = new Float32Array([config.gravity.x, config.gravity.y]); + this._color = new Float32Array([config.startColor.r, config.startColor.g, config.startColor.b, config.startColor.a]); + this._colorVar = new Float32Array([config.startColorVar.r, config.startColorVar.g, config.startColorVar.b, config.startColorVar.a]); + this._endColor = new Float32Array([config.endColor.r, config.endColor.g, config.endColor.b, config.endColor.a]); + this._endColorVar = new Float32Array([config.endColorVar.r, config.endColorVar.g, config.endColorVar.b, config.endColorVar.a]); +}; + +var prototypeAccessors$3 = { vertexFormat: {},particleCount: {},stopped: {},pos: {},posVar: {},gravity: {},startColor: {},startColorVar: {},endColor: {},endColorVar: {} }; + +prototypeAccessors$3.vertexFormat.get = function () { + return _vertexFmt; +}; + +// TODO: it's too slow, need other approach to retrieve the real particle count +prototypeAccessors$3.particleCount.get = function () { + var particleCount = 0; + var device = this._device; + device.setFrameBuffer(this.framebuffers.state0); + var w = this.statesize[0], h = this.statesize[1], + tw = this._tw, th = this._th, + rgba = this.buffers.particleCache; + device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); + for (var y = 0; y < th; y++) { + for (var x = 0; x < tw; x++) { + var offset = y * 3 * tw * 12 + x * 12; + var rest = decode(rgba, offset, LIFE_SCALE); + if (rest > 0) { + particleCount++; } - }; - - Object.defineProperties( RenderData.prototype, prototypeAccessors ); - - return RenderData; - }(BaseRenderData)); - - RenderData.type = 'RenderData'; - - _pool = new Pool(function () { - return new RenderData(); - }, 32); - - // Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - /** - * IARenderData is user customized render data type, user should provide the entier input assembler. - * IARenderData just defines a property `ia` for accessing the input assembler. - * It doesn't manage memory so users should manage the memory of input assembler by themselves. - */ - var IARenderData = (function (BaseRenderData$$1) { - function IARenderData () { - BaseRenderData$$1.call(this); - this.ia = null; - } - - if ( BaseRenderData$$1 ) IARenderData.__proto__ = BaseRenderData$$1; - IARenderData.prototype = Object.create( BaseRenderData$$1 && BaseRenderData$$1.prototype ); - IARenderData.prototype.constructor = IARenderData; - - var prototypeAccessors = { type: {} }; - - prototypeAccessors.type.get = function () { - return IARenderData.type; + } + } + return particleCount; +}; + +prototypeAccessors$3.stopped.get = function () { + return this._stopped; +}; + +Particles.prototype.updateMaxParticle = function updateMaxParticle (config) { + var emissionMax = Math.floor(config.emissionRate * (config.life + config.lifeVar)); + var maxParticle; + if (config.totalParticles > emissionMax) { + maxParticle = emissionMax; + this._emitVar = config.lifeVar; + } + else { + maxParticle = config.totalParticles; + this._emitVar = 0; + } + if (maxParticle !== this._maxParticle) { + this._maxParticle = maxParticle; + this._tw = Math.ceil(Math.sqrt(maxParticle)); + this._th = Math.floor(Math.sqrt(maxParticle)); + this.initTextures(); + this.initBuffers(); + } +}; + +prototypeAccessors$3.pos.set = function (pos) { + this._pos[0] = pos.x; + this._pos[1] = pos.y; +}; + +prototypeAccessors$3.posVar.set = function (posVar) { + this._posVar[0] = posVar.x; + this._posVar[1] = posVar.y; +}; + +prototypeAccessors$3.gravity.set = function (gravity) { + this._gravity[0] = gravity.x; + this._gravity[1] = gravity.y; +}; + +prototypeAccessors$3.startColor.set = function (color) { + this._color[0] = color.r; + this._color[1] = color.g; + this._color[2] = color.b; + this._color[3] = color.a; +}; + +prototypeAccessors$3.startColorVar.set = function (color) { + this._colorVar[0] = color.r; + this._colorVar[1] = color.g; + this._colorVar[2] = color.b; + this._colorVar[3] = color.a; +}; + +prototypeAccessors$3.endColor.set = function (color) { + this._endColor[0] = color.r; + this._endColor[1] = color.g; + this._endColor[2] = color.b; + this._endColor[3] = color.a; +}; + +prototypeAccessors$3.endColorVar.set = function (color) { + this._endColorVar[0] = color.r; + this._endColorVar[1] = color.g; + this._endColorVar[2] = color.b; + this._endColorVar[3] = color.a; +}; + +Particles.prototype._updateTex = function _updateTex (tex, data, width, height) { + _dataOpts.images.length = 1; + _dataOpts.images[0] = data; + _dataOpts.width = width; + _dataOpts.height = height; + tex.update(_dataOpts); +}; + +Particles.prototype._initNoise = function _initNoise () { + var tw = this._tw, th = this._th; + var w = (tw + 1) * 3, h = (th + 1) * 3; + var data = new Uint8Array(w * h * 4); + var offset = 0; + for (var y = 0; y < h; y++) { + for (var x = 0; x < w; x++) { + encode(Math.random(), NOISE_SCALE, data, offset); + encode(Math.random(), NOISE_SCALE, data, offset + 2); + offset += 4; + } + } + this._noisesize = new Float32Array([w, h]); + this._updateTex(this.textures.noise, data, w, h); +}; + +Particles.prototype.initTextures = function initTextures () { + var tw = this._tw, th = this._th; + this.statesize = new Float32Array([tw * 3, th * 3]); + this.quadsize = new Float32Array([tw * 2, th * 2]); + var data = new Uint8Array(tw * 3 * th * 3 * 4); + // decode([97, 97], 0, LIFE_SCALE); equals to -128, just for initalize a negative value in life + data.fill(97); + this._updateTex(this.textures.state0, data, tw * 3, th * 3); + this._updateTex(this.textures.state1, data, tw * 3, th * 3); + this._updateTex(this.textures.quads, null, tw * 2, th * 2); + this._initNoise(); +}; + +Particles.prototype.initBuffers = function initBuffers () { + var w = this.quadsize[0], h = this.quadsize[1], + indexes = new Float32Array(w * h * 2), + i = 0; + for (var y = 0; y < h; y++) { + for (var x = 0; x < w; x++) { + indexes[i + 0] = x; + indexes[i + 1] = y; + i += 2; + } + } + this.buffers.indexes = indexes; + this.buffers.particleCache = new Uint8Array(this.statesize[0] * this.statesize[1] * 4); +}; + +Particles.prototype.updateSizeScale = function updateSizeScale (config) { + var size = config.startSize, + sizeVar = config.startSizeVar, + endSize = config.endSize, + endSizeVar = config.endSizeVar; + var scale = Math.floor(Math.pow(BASE, 2) / Math.max(size + sizeVar, endSize + endSizeVar)); + this._sizeScale = clampf(scale, 1, MAX_SCALE); +}; + +Particles.prototype.updateAccelScale = function updateAccelScale (config) { + var radial = config.radialAccel, + radialVar = config.radialAccelVar, + tangential = config.tangentialAccel, + tangentialVar = config.tangentialAccelVar; + var accelScale = Math.floor(Math.pow(BASE, 2) / Math.max(Math.abs(radial) + radialVar, Math.abs(tangential) + tangentialVar) / 2); + this._accelScale = clampf(accelScale, 1, MAX_SCALE); +}; + +Particles.prototype.updateRadiusScale = function updateRadiusScale (config) { + var radius = config.startRadius, + radiusVar = config.startRadiusVar, + endRadius = config.endRadius, + endRadiusVar = config.endRadiusVar; + var scale = Math.floor(Math.pow(BASE, 2) / Math.max(Math.abs(radius) + radiusVar, Math.abs(endRadius) + endRadiusVar)); + this._radiusScale = clampf(scale, 1, MAX_SCALE); +}; + +Particles.prototype.resetSystem = function resetSystem () { + this._stopped = false; +}; + +Particles.prototype.stopSystem = function stopSystem () { + this._stopped = true; +}; + +Particles.prototype.getState = function getState (framebuffer) { + var this$1 = this; + + var device = this._device; + device.setFrameBuffer(framebuffer); + var w = this.statesize[0], h = this.statesize[1], + tw = this._tw, th = this._th, + rgba = new Uint8Array(w * h * 4); + device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); + var particles = []; + for (var y = 0; y < th; y++) { + for (var x = 0; x < tw; x++) { + var offset = y * 3 * tw * 12 + x * 12; + var colorI = offset + 1 * 4; + var deltaRGI = offset + 2 * 4; + var deltaBAI = offset + tw * 12; + var sizeI = offset + tw * 12 + 1 * 4; + var rotI = offset + tw * 12 + 2 * 4; + var control1I = offset + 2 * tw * 12; + var control2I = offset + 2 * tw * 12 + 1 * 4; + var posI = offset + 2 * tw * 12 + 2 * 4; + + var rest = decode(rgba, offset, LIFE_SCALE); + var life = decode(rgba, offset + 2, LIFE_SCALE); + var color = { + r: rgba[colorI], + g: rgba[colorI+1], + b: rgba[colorI+2], + a: rgba[colorI+3] }; - - Object.defineProperties( IARenderData.prototype, prototypeAccessors ); - - return IARenderData; - }(BaseRenderData)); - - IARenderData.type = 'IARenderData'; - - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var BASE = 255; - var NOISE_SCALE = 10000; - var POS_SCALE = 1; - var LIFE_SCALE = 100; - var COLOR_SCALE = 1; - var ROTATION_SCALE = 1; - var MAX_SCALE = 500; - var _vertexFmt = new gfx.VertexFormat([ - { name: 'a_quad', type: gfx.ATTR_TYPE_FLOAT32, num: 2 } - ]); - - var _dataOpts = { - width: 0, - height: 0, - minFilter: gfx.FILTER_NEAREST, - magFilter: gfx.FILTER_NEAREST, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - format: gfx.TEXTURE_FMT_RGBA8, - images: [] - }; - - function encode (value, scale, outArr, offset) { - value = value * scale + BASE * BASE / 2; - outArr[offset] = Math.floor((value % BASE) / BASE * 255); - outArr[offset+1] = Math.floor(Math.floor(value / BASE) / BASE * 255); - } - - function decode (arr, offset, scale) { - return (((arr[offset] / 255) * BASE + - (arr[offset+1] / 255) * BASE * BASE) - BASE * BASE / 2) / scale; - } - - function clampf (value, min_inclusive, max_inclusive) { - return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive; - } - - var Particles = function Particles (device, renderer$$1, config) { - this._device = device; - this._config = config; - this._sizeScale = 1; - this._accelScale = 1; - this._radiusScale = 1; - - var opts = {}; - var programLib = renderer$$1._programLib; - this.programs = { - emitter: programLib.getProgram('vfx_emitter', opts), - update: programLib.getProgram('vfx_update', opts), - quad: programLib.getProgram('vfx_quad', opts), - }; - - this.textures = { - // need swap - state0: new gfx.Texture2D(device, opts), - state1: new gfx.Texture2D(device, opts), - // no swap needed - noise: new gfx.Texture2D(device, opts), - quads: new gfx.Texture2D(device, opts), - }; - - this.framebuffers = { - state0: new gfx.FrameBuffer(device, 0, 0, { - colors: [this.textures.state0] - }), - state1: new gfx.FrameBuffer(device, 0, 0, { - colors: [this.textures.state1] - }), - quads: new gfx.FrameBuffer(device, 0, 0, { - colors: [this.textures.quads] - }) - }; - - var verts = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]); - var indices = new Uint8Array([ 0, 1, 2, 1, 3, 2]); - this.buffers = { - updateVB: new gfx.VertexBuffer(device, _vertexFmt, gfx.USAGE_STATIC, verts, 4), - updateIB: new gfx.IndexBuffer(device, gfx.INDEX_FMT_UINT8, gfx.USAGE_STATIC, indices, 6), - indexes: null, - particleCache: null - }; - - this._elapsed = 0; - this._stopped = false; - - this.updateMaxParticle(config); - this.updateSizeScale(config); - this.updateRadiusScale(config); - this.updateAccelScale(config); - - // Vector uniforms - this._pos = new Float32Array([config.sourcePos.x, config.sourcePos.y]); - this._posVar = new Float32Array([config.posVar.x, config.posVar.y]); - this._gravity = new Float32Array([config.gravity.x, config.gravity.y]); - this._color = new Float32Array([config.startColor.r, config.startColor.g, config.startColor.b, config.startColor.a]); - this._colorVar = new Float32Array([config.startColorVar.r, config.startColorVar.g, config.startColorVar.b, config.startColorVar.a]); - this._endColor = new Float32Array([config.endColor.r, config.endColor.g, config.endColor.b, config.endColor.a]); - this._endColorVar = new Float32Array([config.endColorVar.r, config.endColorVar.g, config.endColorVar.b, config.endColorVar.a]); - }; - - var prototypeAccessors$3 = { vertexFormat: {},particleCount: {},stopped: {},pos: {},posVar: {},gravity: {},startColor: {},startColorVar: {},endColor: {},endColorVar: {} }; - - prototypeAccessors$3.vertexFormat.get = function () { - return _vertexFmt; - }; - - // TODO: it's too slow, need other approach to retrieve the real particle count - prototypeAccessors$3.particleCount.get = function () { - var particleCount = 0; - var device = this._device; - device.setFrameBuffer(this.framebuffers.state0); - var w = this.statesize[0], h = this.statesize[1], - tw = this._tw, th = this._th, - rgba = this.buffers.particleCache; - device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); - for (var y = 0; y < th; y++) { - for (var x = 0; x < tw; x++) { - var offset = y * 3 * tw * 12 + x * 12; - var rest = decode(rgba, offset, LIFE_SCALE); - if (rest > 0) { - particleCount++; - } + var deltaColor = { + r: decode(rgba, deltaRGI, COLOR_SCALE), + g: decode(rgba, deltaRGI + 2, COLOR_SCALE), + b: decode(rgba, deltaBAI, COLOR_SCALE), + a: decode(rgba, deltaBAI + 2, COLOR_SCALE) + }; + var size = decode(rgba, sizeI, this$1._sizeScale); + var deltaSize = decode(rgba, sizeI + 2, this$1._sizeScale); + var rot = decode(rgba, rotI, ROTATION_SCALE); + var deltaRot = decode(rgba, rotI + 2, ROTATION_SCALE); + var control = (void 0); + if (this$1._config.emitterMode === 0) { + control = [ + decode(rgba, control1I, POS_SCALE), + decode(rgba, control1I + 2, POS_SCALE), + decode(rgba, control2I, this$1._accelScale), + decode(rgba, control2I + 2, this$1._accelScale) + ]; } - } - return particleCount; - }; - - prototypeAccessors$3.stopped.get = function () { - return this._stopped; - }; - - Particles.prototype.updateMaxParticle = function updateMaxParticle (config) { - var emissionMax = Math.floor(config.emissionRate * (config.life + config.lifeVar)); - var maxParticle; - if (config.totalParticles > emissionMax) { - maxParticle = emissionMax; - this._emitVar = config.lifeVar; - } - else { - maxParticle = config.totalParticles; - this._emitVar = 0; - } - if (maxParticle !== this._maxParticle) { - this._maxParticle = maxParticle; - this._tw = Math.ceil(Math.sqrt(maxParticle)); - this._th = Math.floor(Math.sqrt(maxParticle)); - this.initTextures(); - this.initBuffers(); - } - }; - - prototypeAccessors$3.pos.set = function (pos) { - this._pos[0] = pos.x; - this._pos[1] = pos.y; - }; - - prototypeAccessors$3.posVar.set = function (posVar) { - this._posVar[0] = posVar.x; - this._posVar[1] = posVar.y; - }; - - prototypeAccessors$3.gravity.set = function (gravity) { - this._gravity[0] = gravity.x; - this._gravity[1] = gravity.y; - }; - - prototypeAccessors$3.startColor.set = function (color) { - this._color[0] = color.r; - this._color[1] = color.g; - this._color[2] = color.b; - this._color[3] = color.a; - }; - - prototypeAccessors$3.startColorVar.set = function (color) { - this._colorVar[0] = color.r; - this._colorVar[1] = color.g; - this._colorVar[2] = color.b; - this._colorVar[3] = color.a; - }; - - prototypeAccessors$3.endColor.set = function (color) { - this._endColor[0] = color.r; - this._endColor[1] = color.g; - this._endColor[2] = color.b; - this._endColor[3] = color.a; - }; - - prototypeAccessors$3.endColorVar.set = function (color) { - this._endColorVar[0] = color.r; - this._endColorVar[1] = color.g; - this._endColorVar[2] = color.b; - this._endColorVar[3] = color.a; - }; - - Particles.prototype._updateTex = function _updateTex (tex, data, width, height) { - _dataOpts.images.length = 1; - _dataOpts.images[0] = data; - _dataOpts.width = width; - _dataOpts.height = height; - tex.update(_dataOpts); - }; - - Particles.prototype._initNoise = function _initNoise () { - var tw = this._tw, th = this._th; - var w = (tw + 1) * 3, h = (th + 1) * 3; - var data = new Uint8Array(w * h * 4); - var offset = 0; - for (var y = 0; y < h; y++) { - for (var x = 0; x < w; x++) { - encode(Math.random(), NOISE_SCALE, data, offset); - encode(Math.random(), NOISE_SCALE, data, offset + 2); - offset += 4; + else { + control = [ + decode(rgba, control1I, ROTATION_SCALE), + decode(rgba, control1I + 2, this$1._radiusScale), + decode(rgba, control2I, ROTATION_SCALE), + decode(rgba, control2I + 2, this$1._radiusScale) + ]; } - } - this._noisesize = new Float32Array([w, h]); - this._updateTex(this.textures.noise, data, w, h); - }; - - Particles.prototype.initTextures = function initTextures () { - var tw = this._tw, th = this._th; - this.statesize = new Float32Array([tw * 3, th * 3]); - this.quadsize = new Float32Array([tw * 2, th * 2]); - var data = new Uint8Array(tw * 3 * th * 3 * 4); - // decode([97, 97], 0, LIFE_SCALE); equals to -128, just for initalize a negative value in life - data.fill(97); - this._updateTex(this.textures.state0, data, tw * 3, th * 3); - this._updateTex(this.textures.state1, data, tw * 3, th * 3); - this._updateTex(this.textures.quads, null, tw * 2, th * 2); - this._initNoise(); - }; - - Particles.prototype.initBuffers = function initBuffers () { - var w = this.quadsize[0], h = this.quadsize[1], - indexes = new Float32Array(w * h * 2), - i = 0; - for (var y = 0; y < h; y++) { - for (var x = 0; x < w; x++) { - indexes[i + 0] = x; - indexes[i + 1] = y; - i += 2; - } - } - this.buffers.indexes = indexes; - this.buffers.particleCache = new Uint8Array(this.statesize[0] * this.statesize[1] * 4); - }; - - Particles.prototype.updateSizeScale = function updateSizeScale (config) { - var size = config.startSize, - sizeVar = config.startSizeVar, - endSize = config.endSize, - endSizeVar = config.endSizeVar; - var scale = Math.floor(Math.pow(BASE, 2) / Math.max(size + sizeVar, endSize + endSizeVar)); - this._sizeScale = clampf(scale, 1, MAX_SCALE); - }; - - Particles.prototype.updateAccelScale = function updateAccelScale (config) { - var radial = config.radialAccel, - radialVar = config.radialAccelVar, - tangential = config.tangentialAccel, - tangentialVar = config.tangentialAccelVar; - var accelScale = Math.floor(Math.pow(BASE, 2) / Math.max(Math.abs(radial) + radialVar, Math.abs(tangential) + tangentialVar) / 2); - this._accelScale = clampf(accelScale, 1, MAX_SCALE); - }; - - Particles.prototype.updateRadiusScale = function updateRadiusScale (config) { - var radius = config.startRadius, - radiusVar = config.startRadiusVar, - endRadius = config.endRadius, - endRadiusVar = config.endRadiusVar; - var scale = Math.floor(Math.pow(BASE, 2) / Math.max(Math.abs(radius) + radiusVar, Math.abs(endRadius) + endRadiusVar)); - this._radiusScale = clampf(scale, 1, MAX_SCALE); - }; - - Particles.prototype.resetSystem = function resetSystem () { - this._stopped = false; - }; - - Particles.prototype.stopSystem = function stopSystem () { - this._stopped = true; - }; - - Particles.prototype.getState = function getState (framebuffer) { - var this$1 = this; - - var device = this._device; - device.setFrameBuffer(framebuffer); - var w = this.statesize[0], h = this.statesize[1], - tw = this._tw, th = this._th, - rgba = new Uint8Array(w * h * 4); - device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); - var particles = []; - for (var y = 0; y < th; y++) { - for (var x = 0; x < tw; x++) { - var offset = y * 3 * tw * 12 + x * 12; - var colorI = offset + 1 * 4; - var deltaRGI = offset + 2 * 4; - var deltaBAI = offset + tw * 12; - var sizeI = offset + tw * 12 + 1 * 4; - var rotI = offset + tw * 12 + 2 * 4; - var control1I = offset + 2 * tw * 12; - var control2I = offset + 2 * tw * 12 + 1 * 4; - var posI = offset + 2 * tw * 12 + 2 * 4; - - var rest = decode(rgba, offset, LIFE_SCALE); - var life = decode(rgba, offset + 2, LIFE_SCALE); - var color = { - r: rgba[colorI], - g: rgba[colorI+1], - b: rgba[colorI+2], - a: rgba[colorI+3] - }; - var deltaColor = { - r: decode(rgba, deltaRGI, COLOR_SCALE), - g: decode(rgba, deltaRGI + 2, COLOR_SCALE), - b: decode(rgba, deltaBAI, COLOR_SCALE), - a: decode(rgba, deltaBAI + 2, COLOR_SCALE) - }; - var size = decode(rgba, sizeI, this$1._sizeScale); - var deltaSize = decode(rgba, sizeI + 2, this$1._sizeScale); - var rot = decode(rgba, rotI, ROTATION_SCALE); - var deltaRot = decode(rgba, rotI + 2, ROTATION_SCALE); - var control = (void 0); - if (this$1._config.emitterMode === 0) { - control = [ - decode(rgba, control1I, POS_SCALE), - decode(rgba, control1I + 2, POS_SCALE), - decode(rgba, control2I, this$1._accelScale), - decode(rgba, control2I + 2, this$1._accelScale) - ]; - } - else { - control = [ - decode(rgba, control1I, ROTATION_SCALE), - decode(rgba, control1I + 2, this$1._radiusScale), - decode(rgba, control2I, ROTATION_SCALE), - decode(rgba, control2I + 2, this$1._radiusScale) - ]; - } - var pos = { - x: decode(rgba, posI, POS_SCALE), - y: decode(rgba, posI + 2, POS_SCALE) - }; - particles.push({ - rest: rest, - life: life, - color: color, - deltaColor: deltaColor, - size: size, - deltaSize: deltaSize, - rot: rot, - deltaRot: deltaRot, - control: control, - pos: pos - }); - } - } - return particles; - }; - - Particles.prototype.getNoise = function getNoise () { - var device = this._device; - var framebuffer = new gfx.FrameBuffer(device, 0, 0, { - colors: [this.textures.noise] + var pos = { + x: decode(rgba, posI, POS_SCALE), + y: decode(rgba, posI + 2, POS_SCALE) + }; + particles.push({ + rest: rest, + life: life, + color: color, + deltaColor: deltaColor, + size: size, + deltaSize: deltaSize, + rot: rot, + deltaRot: deltaRot, + control: control, + pos: pos }); - device.setFrameBuffer(framebuffer); - var w = this._noisesize[0], h = this._noisesize[1], - rgba = new Uint8Array(w * h * 4); - device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); - var noises = []; - var offset = 0; - for (var y = 0; y < h; y++) { - for (var x = 0; x < w; x++) { - noises.push(decode(rgba, offset, 10000)); - noises.push(decode(rgba, offset+2, 10000)); - offset += 4; - } } - return noises; - }; - - Particles.prototype.getQuads = function getQuads () { - var device = this._device; - var framebuffer = new gfx.FrameBuffer(device, 0, 0, { - colors: [this.textures.quads] - }); - device.setFrameBuffer(framebuffer); - var w = this.quadsize[0], h = this.quadsize[1], - rgba = new Uint8Array(w * h * 4); - device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); - var quads = []; - var off1 = 0, off2 = 0; - for (var y = 0; y < h; y += 2) { - for (var x = 0; x < w; x += 2) { - off1 = (y * w + x) * 4; - off2 = ((y + 1) * w + x) * 4; - quads.push([ - decode(rgba, off1, POS_SCALE), - decode(rgba, off1+2, POS_SCALE), - decode(rgba, off1+4, POS_SCALE), - decode(rgba, off1+6, POS_SCALE), - decode(rgba, off2, POS_SCALE), - decode(rgba, off2+2, POS_SCALE), - decode(rgba, off2+4, POS_SCALE), - decode(rgba, off2+6, POS_SCALE) - ]); - } + } + return particles; +}; + +Particles.prototype.getNoise = function getNoise () { + var device = this._device; + var framebuffer = new gfx.FrameBuffer(device, 0, 0, { + colors: [this.textures.noise] + }); + device.setFrameBuffer(framebuffer); + var w = this._noisesize[0], h = this._noisesize[1], + rgba = new Uint8Array(w * h * 4); + device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); + var noises = []; + var offset = 0; + for (var y = 0; y < h; y++) { + for (var x = 0; x < w; x++) { + noises.push(decode(rgba, offset, 10000)); + noises.push(decode(rgba, offset+2, 10000)); + offset += 4; } - return quads; - }; - - Particles.prototype.step = function step (dt) { - var config = this._config; - var device = this._device; - - // setup - device.setViewport(0, 0, this.statesize[0], this.statesize[1]); - - // Emitter - device.setFrameBuffer(this.framebuffers.state1); - device.setTexture('noise', this.textures.noise, 0); - device.setTexture('state', this.textures.state0, 1); - device.setUniform('statesize', this.statesize); - device.setUniform('noisesize', this._noisesize); - device.setUniform('stopped', this._stopped); - device.setUniform('dt', dt); - device.setUniform('mode', config.emitterMode); - device.setUniform('noiseId', Math.floor(Math.random() * 16)); - device.setUniform('emitVar', this._emitVar); - device.setUniform('life', config.life); - device.setUniform('lifeVar', config.lifeVar); - device.setUniform('pos', this._pos); - device.setUniform('posVar', this._posVar); - device.setUniform('color', this._color); - device.setUniform('colorVar', this._colorVar); - device.setUniform('endColor', this._endColor); - device.setUniform('endColorVar', this._endColorVar); - device.setUniform('size', config.startSize); - device.setUniform('sizeVar', config.startSizeVar); - device.setUniform('endSize', config.endSize); - device.setUniform('endSizeVar', config.endSizeVar); - device.setUniform('rot', config.startSpin); - device.setUniform('rotVar', config.startSpinVar); - device.setUniform('endRot', config.endSpin); - device.setUniform('endRotVar', config.endSpinVar); - device.setUniform('angle', config.angle); - device.setUniform('angleVar', config.angleVar); - device.setUniform('speed', config.speed); - device.setUniform('speedVar', config.speedVar); - device.setUniform('radial', config.radialAccel); - device.setUniform('radialVar', config.radialAccelVar); - device.setUniform('tangent', config.tangentialAccel); - device.setUniform('tangentVar', config.tangentialAccelVar); - device.setUniform('radius', config.startRadius); - device.setUniform('radiusVar', config.startRadiusVar); - device.setUniform('endRadius', config.endRadius); - device.setUniform('endRadiusVar', config.endRadiusVar); - device.setUniform('rotatePS', config.rotatePerS); - device.setUniform('rotatePSVar', config.rotatePerSVar); - device.setUniform('sizeScale', this._sizeScale); - device.setUniform('accelScale', this._accelScale); - device.setUniform('radiusScale', this._radiusScale); - device.setVertexBuffer(0, this.buffers.updateVB); - device.setIndexBuffer(this.buffers.updateIB); - device.setProgram(this.programs.emitter); - device.draw(0, this.buffers.updateIB.count); - - // Update - device.setFrameBuffer(this.framebuffers.state0); - device.setTexture('state', this.textures.state1, 0); - device.setUniform('statesize', this.statesize); - device.setUniform('dt', dt); - device.setUniform('mode', config.emitterMode); - device.setUniform('gravity', this._gravity); - device.setUniform('sizeScale', this._sizeScale); - device.setUniform('accelScale', this._accelScale); - device.setUniform('radiusScale', this._radiusScale); - device.setVertexBuffer(0, this.buffers.updateVB); - device.setIndexBuffer(this.buffers.updateIB); - device.setProgram(this.programs.update); - device.draw(0, this.buffers.updateIB.count); - - // Draw quad - device.setViewport(0, 0, this._tw * 2, this._th * 2); - device.setFrameBuffer(this.framebuffers.quads); - device.setTexture('state', this.textures.state0, 0); - device.setUniform('quadsize', this.quadsize); - device.setUniform('statesize', this.statesize); - device.setUniform('sizeScale', this._sizeScale); - device.setVertexBuffer(0, this.buffers.updateVB); - device.setIndexBuffer(this.buffers.updateIB); - device.setProgram(this.programs.quad); - device.draw(0, this.buffers.updateIB.count); - - this._elapsed += dt; - if (config.duration !== -1 && config.duration < this._elapsed) { - this.stopSystem(); + } + return noises; +}; + +Particles.prototype.getQuads = function getQuads () { + var device = this._device; + var framebuffer = new gfx.FrameBuffer(device, 0, 0, { + colors: [this.textures.quads] + }); + device.setFrameBuffer(framebuffer); + var w = this.quadsize[0], h = this.quadsize[1], + rgba = new Uint8Array(w * h * 4); + device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); + var quads = []; + var off1 = 0, off2 = 0; + for (var y = 0; y < h; y += 2) { + for (var x = 0; x < w; x += 2) { + off1 = (y * w + x) * 4; + off2 = ((y + 1) * w + x) * 4; + quads.push([ + decode(rgba, off1, POS_SCALE), + decode(rgba, off1+2, POS_SCALE), + decode(rgba, off1+4, POS_SCALE), + decode(rgba, off1+6, POS_SCALE), + decode(rgba, off2, POS_SCALE), + decode(rgba, off2+2, POS_SCALE), + decode(rgba, off2+4, POS_SCALE), + decode(rgba, off2+6, POS_SCALE) + ]); } - }; - - Object.defineProperties( Particles.prototype, prototypeAccessors$3 ); - - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var Asset = function Asset(persist) { + } + return quads; +}; + +Particles.prototype.step = function step (dt) { + var config = this._config; + var device = this._device; + + // setup + device.setViewport(0, 0, this.statesize[0], this.statesize[1]); + + // Emitter + device.setFrameBuffer(this.framebuffers.state1); + device.setTexture('noise', this.textures.noise, 0); + device.setTexture('state', this.textures.state0, 1); + device.setUniform('statesize', this.statesize); + device.setUniform('noisesize', this._noisesize); + device.setUniform('stopped', this._stopped); + device.setUniform('dt', dt); + device.setUniform('mode', config.emitterMode); + device.setUniform('noiseId', Math.floor(Math.random() * 16)); + device.setUniform('emitVar', this._emitVar); + device.setUniform('life', config.life); + device.setUniform('lifeVar', config.lifeVar); + device.setUniform('pos', this._pos); + device.setUniform('posVar', this._posVar); + device.setUniform('color', this._color); + device.setUniform('colorVar', this._colorVar); + device.setUniform('endColor', this._endColor); + device.setUniform('endColorVar', this._endColorVar); + device.setUniform('size', config.startSize); + device.setUniform('sizeVar', config.startSizeVar); + device.setUniform('endSize', config.endSize); + device.setUniform('endSizeVar', config.endSizeVar); + device.setUniform('rot', config.startSpin); + device.setUniform('rotVar', config.startSpinVar); + device.setUniform('endRot', config.endSpin); + device.setUniform('endRotVar', config.endSpinVar); + device.setUniform('angle', config.angle); + device.setUniform('angleVar', config.angleVar); + device.setUniform('speed', config.speed); + device.setUniform('speedVar', config.speedVar); + device.setUniform('radial', config.radialAccel); + device.setUniform('radialVar', config.radialAccelVar); + device.setUniform('tangent', config.tangentialAccel); + device.setUniform('tangentVar', config.tangentialAccelVar); + device.setUniform('radius', config.startRadius); + device.setUniform('radiusVar', config.startRadiusVar); + device.setUniform('endRadius', config.endRadius); + device.setUniform('endRadiusVar', config.endRadiusVar); + device.setUniform('rotatePS', config.rotatePerS); + device.setUniform('rotatePSVar', config.rotatePerSVar); + device.setUniform('sizeScale', this._sizeScale); + device.setUniform('accelScale', this._accelScale); + device.setUniform('radiusScale', this._radiusScale); + device.setVertexBuffer(0, this.buffers.updateVB); + device.setIndexBuffer(this.buffers.updateIB); + device.setProgram(this.programs.emitter); + device.draw(0, this.buffers.updateIB.count); + + // Update + device.setFrameBuffer(this.framebuffers.state0); + device.setTexture('state', this.textures.state1, 0); + device.setUniform('statesize', this.statesize); + device.setUniform('dt', dt); + device.setUniform('mode', config.emitterMode); + device.setUniform('gravity', this._gravity); + device.setUniform('sizeScale', this._sizeScale); + device.setUniform('accelScale', this._accelScale); + device.setUniform('radiusScale', this._radiusScale); + device.setVertexBuffer(0, this.buffers.updateVB); + device.setIndexBuffer(this.buffers.updateIB); + device.setProgram(this.programs.update); + device.draw(0, this.buffers.updateIB.count); + + // Draw quad + device.setViewport(0, 0, this._tw * 2, this._th * 2); + device.setFrameBuffer(this.framebuffers.quads); + device.setTexture('state', this.textures.state0, 0); + device.setUniform('quadsize', this.quadsize); + device.setUniform('statesize', this.statesize); + device.setUniform('sizeScale', this._sizeScale); + device.setVertexBuffer(0, this.buffers.updateVB); + device.setIndexBuffer(this.buffers.updateIB); + device.setProgram(this.programs.quad); + device.draw(0, this.buffers.updateIB.count); + + this._elapsed += dt; + if (config.duration !== -1 && config.duration < this._elapsed) { + this.stopSystem(); + } +}; + +Object.defineProperties( Particles.prototype, prototypeAccessors$3 ); + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var Asset = function Asset(persist) { + if ( persist === void 0 ) persist = true; + + this._loaded = false; + this._persist = persist; +}; + +Asset.prototype.unload = function unload () { + this._loaded = false; +}; + +Asset.prototype.reload = function reload () { + // TODO +}; + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var Texture = (function (Asset$$1) { + function Texture(persist) { if ( persist === void 0 ) persist = true; - - this._loaded = false; - this._persist = persist; + + Asset$$1.call(this, persist); + + this._texture = null; + } + + if ( Asset$$1 ) Texture.__proto__ = Asset$$1; + Texture.prototype = Object.create( Asset$$1 && Asset$$1.prototype ); + Texture.prototype.constructor = Texture; + + Texture.prototype.getImpl = function getImpl () { + return this._texture; }; - - Asset.prototype.unload = function unload () { - this._loaded = false; + + Texture.prototype.getId = function getId () {}; + + Texture.prototype.destroy = function destroy () { + this._texture && this._texture.destroy(); }; + + return Texture; +}(Asset)); + +/** + * JS Implementation of MurmurHash2 + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} str ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ + +function murmurhash2_32_gc(str, seed) { + var + l = str.length, + h = seed ^ l, + i = 0, + k; - Asset.prototype.reload = function reload () { - // TODO - }; - - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var Texture = (function (Asset$$1) { - function Texture(persist) { - if ( persist === void 0 ) persist = true; - - Asset$$1.call(this, persist); - - this._texture = null; - } - - if ( Asset$$1 ) Texture.__proto__ = Asset$$1; - Texture.prototype = Object.create( Asset$$1 && Asset$$1.prototype ); - Texture.prototype.constructor = Texture; - - Texture.prototype.getImpl = function getImpl () { - return this._texture; - }; - - Texture.prototype.getId = function getId () {}; - - Texture.prototype.destroy = function destroy () { - this._texture && this._texture.destroy(); - }; - - return Texture; - }(Asset)); - - /** - * JS Implementation of MurmurHash2 - * - * @author Gary Court - * @see http://github.com/garycourt/murmurhash-js - * @author Austin Appleby - * @see http://sites.google.com/site/murmurhash/ - * - * @param {string} str ASCII only - * @param {number} seed Positive integer only - * @return {number} 32-bit positive integer hash - */ - - function murmurhash2_32_gc(str, seed) { - var - l = str.length, - h = seed ^ l, - i = 0, - k; + while (l >= 4) { + k = + ((str.charCodeAt(i) & 0xff)) | + ((str.charCodeAt(++i) & 0xff) << 8) | + ((str.charCodeAt(++i) & 0xff) << 16) | + ((str.charCodeAt(++i) & 0xff) << 24); - while (l >= 4) { - k = - ((str.charCodeAt(i) & 0xff)) | - ((str.charCodeAt(++i) & 0xff) << 8) | - ((str.charCodeAt(++i) & 0xff) << 16) | - ((str.charCodeAt(++i) & 0xff) << 24); - - k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); - k ^= k >>> 24; - k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); - - h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; - - l -= 4; - ++i; - } - - switch (l) { - case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; - case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; - case 1: h ^= (str.charCodeAt(i) & 0xff); - h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); - } - - h ^= h >>> 13; - h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); - h ^= h >>> 15; - - return h >>> 0; + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k ^= k >>> 24; + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; + + l -= 4; + ++i; } - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - // function genHashCode (str) { - // var hash = 0; - // if (str.length == 0) { - // return hash; - // } - // for (var i = 0; i < str.length; i++) { - // var char = str.charCodeAt(i); - // hash = ((hash<<5)-hash)+char; - // hash = hash & hash; // Convert to 32bit integer - // } - // return hash; - // } - - function serializeDefines (defines) { - var str = ''; - for (var i = 0; i < defines.length; i++) { - str += defines[i].name + defines[i].value; - } - return str; + switch (l) { + case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; + case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; + case 1: h ^= (str.charCodeAt(i) & 0xff); + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); } - - function serializePass (pass) { - var str = pass._programName + pass._cullMode; - if (pass._blend) { - str += pass._blendEq + pass._blendAlphaEq + pass._blendSrc + pass._blendDst - + pass._blendSrcAlpha + pass._blendDstAlpha + pass._blendColor; - } - if (pass._depthTest) { - str += pass._depthWrite + pass._depthFunc; - } - if (pass._stencilTest) { - str += pass._stencilFuncFront + pass._stencilRefFront + pass._stencilMaskFront - + pass._stencilFailOpFront + pass._stencilZFailOpFront + pass._stencilZPassOpFront - + pass._stencilWriteMaskFront - + pass._stencilFuncBack + pass._stencilRefBack + pass._stencilMaskBack - + pass._stencilFailOpBack + pass._stencilZFailOpBack + pass._stencilZPassOpBack - + pass._stencilWriteMaskBack; - } - return str; + + h ^= h >>> 13; + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + h ^= h >>> 15; + + return h >>> 0; +} + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +// function genHashCode (str) { +// var hash = 0; +// if (str.length == 0) { +// return hash; +// } +// for (var i = 0; i < str.length; i++) { +// var char = str.charCodeAt(i); +// hash = ((hash<<5)-hash)+char; +// hash = hash & hash; // Convert to 32bit integer +// } +// return hash; +// } + +function serializeDefines (defines) { + var str = ''; + for (var i = 0; i < defines.length; i++) { + str += defines[i].name + defines[i].value; + } + return str; +} + +function serializePass (pass) { + var str = pass._programName + pass._cullMode; + if (pass._blend) { + str += pass._blendEq + pass._blendAlphaEq + pass._blendSrc + pass._blendDst + + pass._blendSrcAlpha + pass._blendDstAlpha + pass._blendColor; + } + if (pass._depthTest) { + str += pass._depthWrite + pass._depthFunc; + } + if (pass._stencilTest) { + str += pass._stencilFuncFront + pass._stencilRefFront + pass._stencilMaskFront + + pass._stencilFailOpFront + pass._stencilZFailOpFront + pass._stencilZPassOpFront + + pass._stencilWriteMaskFront + + pass._stencilFuncBack + pass._stencilRefBack + pass._stencilMaskBack + + pass._stencilFailOpBack + pass._stencilZFailOpBack + pass._stencilZPassOpBack + + pass._stencilWriteMaskBack; + } + return str; +} + +function computeHash(material) { + var effect = material._effect; + var hashData = ''; + if (effect) { + var i, j, techData, param, prop, propKey; + + // effect._defines + hashData += serializeDefines(effect._defines); + // effect._techniques + for (i = 0; i < effect._techniques.length; i++) { + techData = effect._techniques[i]; + // technique.stageIDs + hashData += techData.stageIDs; + // technique._layer + // hashData += + techData._layer + "_"; + // technique.passes + for (j = 0; j < techData.passes.length; j++) { + hashData += serializePass(techData.passes[j]); + } + //technique._parameters + for (j = 0; j < techData._parameters.length; j++) { + param = techData._parameters[j]; + propKey = param.name; + prop = effect._properties[propKey]; + if (!prop) { + continue; + } + switch(param.type) { + case renderer.PARAM_INT: + case renderer.PARAM_FLOAT: + hashData += prop + ';'; + break; + case renderer.PARAM_INT2: + case renderer.PARAM_FLOAT2: + hashData += prop.x + ',' + prop.y + ';'; + break; + case renderer.PARAM_INT4: + case renderer.PARAM_FLOAT4: + hashData += prop.x + ',' + prop.y + ',' + prop.z + ',' + prop.w + ';'; + break; + case renderer.PARAM_COLOR4: + hashData += prop.r + ',' + prop.g + ',' + prop.b + ',' + prop.a + ';'; + break; + case renderer.PARAM_MAT2: + hashData += prop.m00 + ',' + prop.m01 + ',' + prop.m02 + ',' + prop.m03 + ';'; + break; + case renderer.PARAM_TEXTURE_2D: + case renderer.PARAM_TEXTURE_CUBE: + hashData += material._texIds[propKey] + ';'; + break; + case renderer.PARAM_INT3: + case renderer.PARAM_FLOAT3: + case renderer.PARAM_COLOR3: + case renderer.PARAM_MAT3: + case renderer.PARAM_MAT4: + hashData += JSON.stringify(prop) + ';'; + break; + default: + break; + } + } + } + } + return hashData ? murmurhash2_32_gc(hashData, 666) : hashData; +} + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var Material = (function (Asset$$1) { + function Material(persist) { + if ( persist === void 0 ) persist = false; + + Asset$$1.call(this, persist); + + this._effect = null; // renderer.Effect + this._texIds = {}; // ids collected from texture defines + this._hash = ''; } - - function computeHash(material) { - var effect = material._effect; - var hashData = ''; - if (effect) { - var i, j, techData, param, prop, propKey; - - // effect._defines - hashData += serializeDefines(effect._defines); - // effect._techniques - for (i = 0; i < effect._techniques.length; i++) { - techData = effect._techniques[i]; - // technique.stageIDs - hashData += techData.stageIDs; - // technique._layer - // hashData += + techData._layer + "_"; - // technique.passes - for (j = 0; j < techData.passes.length; j++) { - hashData += serializePass(techData.passes[j]); - } - //technique._parameters - for (j = 0; j < techData._parameters.length; j++) { - param = techData._parameters[j]; - propKey = param.name; - prop = effect._properties[propKey]; - if (!prop) { - continue; - } - switch(param.type) { - case renderer.PARAM_INT: - case renderer.PARAM_FLOAT: - hashData += prop + ';'; - break; - case renderer.PARAM_INT2: - case renderer.PARAM_FLOAT2: - hashData += prop.x + ',' + prop.y + ';'; - break; - case renderer.PARAM_INT4: - case renderer.PARAM_FLOAT4: - hashData += prop.x + ',' + prop.y + ',' + prop.z + ',' + prop.w + ';'; - break; - case renderer.PARAM_COLOR4: - hashData += prop.r + ',' + prop.g + ',' + prop.b + ',' + prop.a + ';'; - break; - case renderer.PARAM_MAT2: - hashData += prop.m00 + ',' + prop.m01 + ',' + prop.m02 + ',' + prop.m03 + ';'; - break; - case renderer.PARAM_TEXTURE_2D: - case renderer.PARAM_TEXTURE_CUBE: - hashData += material._texIds[propKey] + ';'; - break; - case renderer.PARAM_INT3: - case renderer.PARAM_FLOAT3: - case renderer.PARAM_COLOR3: - case renderer.PARAM_MAT3: - case renderer.PARAM_MAT4: - hashData += JSON.stringify(prop) + ';'; - break; - default: - break; - } - } - } - } - return hashData ? murmurhash2_32_gc(hashData, 666) : hashData; + + if ( Asset$$1 ) Material.__proto__ = Asset$$1; + Material.prototype = Object.create( Asset$$1 && Asset$$1.prototype ); + Material.prototype.constructor = Material; + + var prototypeAccessors = { hash: {} }; + + prototypeAccessors.hash.get = function () { + return this._hash; + }; + + Material.prototype.updateHash = function updateHash (value) { + this._hash = value || computeHash(this); + }; + + Object.defineProperties( Material.prototype, prototypeAccessors ); + + return Material; +}(Asset)); + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var SpriteMaterial = (function (Material$$1) { + function SpriteMaterial() { + Material$$1.call(this, false); + + var pass = new renderer.Pass('sprite'); + pass.setDepth(false, false); + pass.setCullMode(gfx.CULL_NONE); + pass.setBlend( + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA + ); + + var mainTech = new renderer.Technique( + ['transparent'], + [ + { name: 'texture', type: renderer.PARAM_TEXTURE_2D } ], + [ + pass + ] + ); + + this._effect = new renderer.Effect( + [ + mainTech ], + {}, + [ + { name: 'useTexture', value: true }, + { name: 'useModel', value: false }, + { name: 'alphaTest', value: false } ] + ); + + this._mainTech = mainTech; + this._texture = null; } + + if ( Material$$1 ) SpriteMaterial.__proto__ = Material$$1; + SpriteMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); + SpriteMaterial.prototype.constructor = SpriteMaterial; + + var prototypeAccessors = { effect: {},useTexture: {},useModel: {},texture: {} }; + + prototypeAccessors.effect.get = function () { + return this._effect; + }; - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var Material = (function (Asset$$1) { - function Material(persist) { - if ( persist === void 0 ) persist = false; + prototypeAccessors.useTexture.get = function () { + this._effect.getDefine('useTexture', val); + }; + + prototypeAccessors.useTexture.set = function (val) { + this._effect.define('useTexture', val); + }; - Asset$$1.call(this, persist); - - this._effect = null; // renderer.Effect - this._texIds = {}; // ids collected from texture defines - this._hash = ''; + prototypeAccessors.useModel.get = function () { + this._effect.getDefine('useModel', val); + }; + + prototypeAccessors.useModel.set = function (val) { + this._effect.define('useModel', val); + }; + + prototypeAccessors.texture.get = function () { + return this._texture; + }; + + prototypeAccessors.texture.set = function (val) { + if (this._texture !== val) { + this._texture = val; + this._effect.setProperty('texture', val.getImpl()); + this._texIds['texture'] = val.getId(); } - - if ( Asset$$1 ) Material.__proto__ = Asset$$1; - Material.prototype = Object.create( Asset$$1 && Asset$$1.prototype ); - Material.prototype.constructor = Material; - - var prototypeAccessors = { hash: {} }; - - prototypeAccessors.hash.get = function () { - return this._hash; - }; - - Material.prototype.updateHash = function updateHash (value) { - this._hash = value || computeHash(this); - }; - - Object.defineProperties( Material.prototype, prototypeAccessors ); - - return Material; - }(Asset)); - - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var SpriteMaterial = (function (Material$$1) { - function SpriteMaterial() { - Material$$1.call(this, false); - - var pass = new renderer.Pass('sprite'); - pass.setDepth(false, false); - pass.setCullMode(gfx.CULL_NONE); - pass.setBlend( - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA - ); - - var mainTech = new renderer.Technique( - ['transparent'], - [ - { name: 'texture', type: renderer.PARAM_TEXTURE_2D } ], - [ - pass - ] - ); - - this._effect = new renderer.Effect( - [ - mainTech ], - {}, - [ - { name: 'useTexture', value: true }, - { name: 'useModel', value: false }, - { name: 'alphaTest', value: false } ] - ); - - this._mainTech = mainTech; - this._texture = null; - } - - if ( Material$$1 ) SpriteMaterial.__proto__ = Material$$1; - SpriteMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); - SpriteMaterial.prototype.constructor = SpriteMaterial; - - var prototypeAccessors = { effect: {},useTexture: {},useModel: {},texture: {} }; - - prototypeAccessors.effect.get = function () { - return this._effect; - }; + }; + + SpriteMaterial.prototype.clone = function clone () { + var copy = new SpriteMaterial(); + copy.texture = this.texture; + copy.useTexture = this.useTexture; + copy.useModel = this.useModel; + copy.updateHash(); + return copy; + }; + + Object.defineProperties( SpriteMaterial.prototype, prototypeAccessors ); + + return SpriteMaterial; +}(Material)); + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var GraySpriteMaterial = (function (Material$$1) { + function GraySpriteMaterial() { + Material$$1.call(this, false); + + var pass = new renderer.Pass('gray_sprite'); + pass.setDepth(false, false); + pass.setCullMode(gfx.CULL_NONE); + pass.setBlend( + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA + ); + + var mainTech = new renderer.Technique( + ['transparent'], + [ + { name: 'texture', type: renderer.PARAM_TEXTURE_2D } ], + [ + pass + ] + ); + + this._effect = new renderer.Effect( + [ + mainTech ], + {}, + [] + ); - prototypeAccessors.useTexture.get = function () { - this._effect.getDefine('useTexture', val); - }; - - prototypeAccessors.useTexture.set = function (val) { - this._effect.define('useTexture', val); - }; + this._mainTech = mainTech; + this._texture = null; + } + + if ( Material$$1 ) GraySpriteMaterial.__proto__ = Material$$1; + GraySpriteMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); + GraySpriteMaterial.prototype.constructor = GraySpriteMaterial; + + var prototypeAccessors = { effect: {},texture: {} }; + + prototypeAccessors.effect.get = function () { + return this._effect; + }; + + prototypeAccessors.texture.get = function () { + return this._texture; + }; + + prototypeAccessors.texture.set = function (val) { + if (this._texture !== val) { + this._texture = val; + this._effect.setProperty('texture', val.getImpl()); + this._texIds['texture'] = val.getId(); + } + }; + + GraySpriteMaterial.prototype.clone = function clone () { + var copy = new GraySpriteMaterial(); + copy.texture = this.texture; + copy.updateHash(); + return copy; + }; + + Object.defineProperties( GraySpriteMaterial.prototype, prototypeAccessors ); + + return GraySpriteMaterial; +}(Material)); + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var StencilMaterial = (function (Material$$1) { + function StencilMaterial() { + Material$$1.call(this, false); + + this._pass = new renderer.Pass('sprite'); + this._pass.setDepth(false, false); + this._pass.setCullMode(gfx.CULL_NONE); + this._pass.setBlend( + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA + ); + + var mainTech = new renderer.Technique( + ['transparent'], + [ + { name: 'texture', type: renderer.PARAM_TEXTURE_2D }, + { name: 'alphaThreshold', type: renderer.PARAM_FLOAT } ], + [ + this._pass + ] + ); + + this._effect = new renderer.Effect( + [ + mainTech ], + {}, + [ + { name: 'useTexture', value: true }, + { name: 'useModel', value: false }, + { name: 'alphaTest', value: true } ] + ); - prototypeAccessors.useModel.get = function () { - this._effect.getDefine('useModel', val); - }; + this._mainTech = mainTech; + this._texture = null; + } + + if ( Material$$1 ) StencilMaterial.__proto__ = Material$$1; + StencilMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); + StencilMaterial.prototype.constructor = StencilMaterial; + + var prototypeAccessors = { effect: {},useTexture: {},texture: {},alphaThreshold: {} }; + + prototypeAccessors.effect.get = function () { + return this._effect; + }; - prototypeAccessors.useModel.set = function (val) { - this._effect.define('useModel', val); - }; - - prototypeAccessors.texture.get = function () { - return this._texture; - }; - - prototypeAccessors.texture.set = function (val) { - if (this._texture !== val) { - this._texture = val; - this._effect.setProperty('texture', val.getImpl()); - this._texIds['texture'] = val.getId(); - } - }; - - SpriteMaterial.prototype.clone = function clone () { - var copy = new SpriteMaterial(values); - copy.texture = this.texture; - copy.useTexture = this.useTexture; - copy.useModel = this.useModel; - copy.updateHash(); - return copy; - }; - - Object.defineProperties( SpriteMaterial.prototype, prototypeAccessors ); - - return SpriteMaterial; - }(Material)); - - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var GraySpriteMaterial = (function (Material$$1) { - function GraySpriteMaterial() { - Material$$1.call(this, false); - - var pass = new renderer.Pass('gray_sprite'); - pass.setDepth(false, false); - pass.setCullMode(gfx.CULL_NONE); - pass.setBlend( - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA - ); - - var mainTech = new renderer.Technique( - ['transparent'], - [ - { name: 'texture', type: renderer.PARAM_TEXTURE_2D } ], - [ - pass - ] - ); - - this._effect = new renderer.Effect( - [ - mainTech ], - {}, - [] - ); - - this._mainTech = mainTech; - this._texture = null; + prototypeAccessors.useTexture.get = function () { + this._effect.getDefine('useTexture', val); + }; + + prototypeAccessors.useTexture.set = function (val) { + this._effect.define('useTexture', val); + }; + + prototypeAccessors.texture.get = function () { + return this._texture; + }; + + prototypeAccessors.texture.set = function (val) { + if (this._texture !== val) { + this._texture = val; + this._effect.setProperty('texture', val.getImpl()); + this._texIds['texture'] = val.getId(); } + }; - if ( Material$$1 ) GraySpriteMaterial.__proto__ = Material$$1; - GraySpriteMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); - GraySpriteMaterial.prototype.constructor = GraySpriteMaterial; - - var prototypeAccessors = { effect: {},texture: {} }; - - prototypeAccessors.effect.get = function () { - return this._effect; - }; - - prototypeAccessors.texture.get = function () { - return this._texture; - }; - - prototypeAccessors.texture.set = function (val) { - if (this._texture !== val) { - this._texture = val; - this._effect.setProperty('texture', val.getImpl()); - this._texIds['texture'] = val.getId(); - } - }; - - GraySpriteMaterial.prototype.clone = function clone () { - var copy = new GraySpriteMaterial(values); - copy.texture = this.texture; - copy.updateHash(); - return copy; - }; - - Object.defineProperties( GraySpriteMaterial.prototype, prototypeAccessors ); - - return GraySpriteMaterial; - }(Material)); - - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var StencilMaterial = (function (Material$$1) { - function StencilMaterial() { - Material$$1.call(this, false); - - this._pass = new renderer.Pass('sprite'); - this._pass.setDepth(false, false); - this._pass.setCullMode(gfx.CULL_NONE); - this._pass.setBlend( - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA - ); - - var mainTech = new renderer.Technique( - ['transparent'], - [ - { name: 'texture', type: renderer.PARAM_TEXTURE_2D }, - { name: 'alphaThreshold', type: renderer.PARAM_FLOAT } ], - [ - this._pass - ] - ); - - this._effect = new renderer.Effect( - [ - mainTech ], - {}, - [ - { name: 'useTexture', value: true }, - { name: 'useModel', value: false }, - { name: 'alphaTest', value: true } ] - ); - - this._mainTech = mainTech; - this._texture = null; - } - - if ( Material$$1 ) StencilMaterial.__proto__ = Material$$1; - StencilMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); - StencilMaterial.prototype.constructor = StencilMaterial; - - var prototypeAccessors = { effect: {},useTexture: {},texture: {},alphaThreshold: {} }; - - prototypeAccessors.effect.get = function () { - return this._effect; - }; + prototypeAccessors.alphaThreshold.get = function () { + return this._effect.getProperty('alphaThreshold'); + }; + + prototypeAccessors.alphaThreshold.set = function (val) { + this._effect.setProperty('alphaThreshold', val); + }; + + StencilMaterial.prototype.clone = function clone () { + var copy = new StencilMaterial(); + copy.useTexture = this.useTexture; + copy.texture = this.texture; + copy.alphaThreshold = this.alphaThreshold; + copy.updateHash(); + return copy; + }; + + Object.defineProperties( StencilMaterial.prototype, prototypeAccessors ); + + return StencilMaterial; +}(Material)); + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var ParticleMaterial = (function (Material$$1) { + function ParticleMaterial() { + Material$$1.call(this, false); + + var pass = new renderer.Pass('vfx_particle'); + pass.setDepth(false, false); + pass.setCullMode(gfx.CULL_NONE); + pass.setBlend( + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA + ); + + var mainTech = new renderer.Technique( + ['transparent'], + [ + { name: 'texture', type: renderer.PARAM_TEXTURE_2D }, + { name: 'state', type: renderer.PARAM_TEXTURE_2D }, + { name: 'quad', type: renderer.PARAM_TEXTURE_2D }, + { name: 'z', type: renderer.PARAM_FLOAT }, + { name: 'statesize', type: renderer.PARAM_FLOAT2 }, + { name: 'quadsize', type: renderer.PARAM_FLOAT2 }, + { name: 'lb', type: renderer.PARAM_FLOAT2 }, + { name: 'rt', type: renderer.PARAM_FLOAT2 } ], + [ + pass + ] + ); + + this._effect = new renderer.Effect( + [ + mainTech ], + {}, + [] + ); - prototypeAccessors.useTexture.get = function () { - this._effect.getDefine('useTexture', val); - }; - - prototypeAccessors.useTexture.set = function (val) { - this._effect.define('useTexture', val); - }; - - prototypeAccessors.texture.get = function () { - return this._texture; - }; - - prototypeAccessors.texture.set = function (val) { - if (this._texture !== val) { - this._texture = val; - this._effect.setProperty('texture', val.getImpl()); - this._texIds['texture'] = val.getId(); - } - }; + this._mainTech = mainTech; + this._texture = null; + this._lb = vec2.create(); + this._rt = vec2.create(); + } + + if ( Material$$1 ) ParticleMaterial.__proto__ = Material$$1; + ParticleMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); + ParticleMaterial.prototype.constructor = ParticleMaterial; + + var prototypeAccessors = { effect: {},texture: {},stateMap: {},quadMap: {},stateSize: {},quadSize: {},z: {},uv: {} }; + + prototypeAccessors.effect.get = function () { + return this._effect; + }; + + prototypeAccessors.texture.get = function () { + return this._texture; + }; + + prototypeAccessors.texture.set = function (val) { + if (this._texture !== val) { + this._texture = val; + this._effect.setProperty('texture', val.getImpl()); + this._texIds['texture'] = val.getId(); + } + }; + + prototypeAccessors.stateMap.get = function () { + return this._effect.getProperty('state'); + }; + + prototypeAccessors.stateMap.set = function (val) { + this._effect.setProperty('state', val); + }; + + prototypeAccessors.quadMap.get = function () { + return this._effect.getProperty('quad'); + }; + + prototypeAccessors.quadMap.set = function (val) { + this._effect.setProperty('quad', val); + }; + + prototypeAccessors.stateSize.get = function () { + return this._effect.getProperty('statesize'); + }; + + prototypeAccessors.stateSize.set = function (val) { + this._effect.setProperty('statesize', val); + }; + + prototypeAccessors.quadSize.get = function () { + return this._effect.getProperty('quadsize'); + }; + + prototypeAccessors.quadSize.set = function (val) { + this._effect.setProperty('quadsize', val); + }; + + prototypeAccessors.z.get = function () { + return this._effect.getProperty('z'); + }; + + prototypeAccessors.z.set = function (val) { + this._effect.setProperty('z', val); + }; + + prototypeAccessors.uv.get = function () { + var lb = this._effect.getProperty('lb'); + var rt = this._effect.getProperty('rt'); + return { + l: lb.x, + r: rt.x, + b: lb.y, + t: rt.y + } + }; + + prototypeAccessors.uv.set = function (val) { + this._lb.x = val.l; + this._lb.y = val.b; + this._rt.x = val.r; + this._rt.y = val.t; + this._effect.setProperty('lb', this._lb); + this._effect.setProperty('rt', this._rt); + }; + + ParticleMaterial.prototype.clone = function clone () { + var copy = new ParticleMaterial(); + copy.texture = this.texture; + copy.stateMap = this.stateMap; + copy.quadMap = this.quadMap; + copy.stateSize = this.stateSize; + copy.quadSize = this.quadSize; + copy.z = this.z; + copy.uv = this.uv; + copy.updateHash(); + return copy; + }; + + Object.defineProperties( ParticleMaterial.prototype, prototypeAccessors ); + + return ParticleMaterial; +}(Material)); + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var Device = function Device(canvasEL) { + var ctx; + + try { + ctx = canvasEL.getContext('2d'); + } catch (err) { + console.error(err); + return; + } + + // statics + this._canvas = canvasEL; + this._ctx = ctx; + this._caps = {}; // capability + this._stats = { + drawcalls: 0, + }; + + // runtime + this._vx = this._vy = this._vw = this._vh = 0; + this._sx = this._sy = this._sw = this._sh = 0; +}; + +Device.prototype._restoreTexture = function _restoreTexture (unit) { +}; + +// =============================== +// Immediate Settings +// =============================== + +/** + * @method setViewport + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + */ +Device.prototype.setViewport = function setViewport (x, y, w, h) { + if ( + this._vx !== x || + this._vy !== y || + this._vw !== w || + this._vh !== h + ) { + this._vx = x; + this._vy = y; + this._vw = w; + this._vh = h; + } +}; + +/** + * @method setScissor + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + */ +Device.prototype.setScissor = function setScissor (x, y, w, h) { + if ( + this._sx !== x || + this._sy !== y || + this._sw !== w || + this._sh !== h + ) { + this._sx = x; + this._sy = y; + this._sw = w; + this._sh = h; + } +}; + +Device.prototype.clear = function clear (color) { + var ctx = this._ctx; + ctx.clearRect(this._vx, this._vy, this._vw, this._vh); + if (color && (color[0] !== 0 || color[1] !== 0 || color[2] !== 0)) { + ctx.fillStyle = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] +')'; + ctx.globalAlpha = color[3]; + ctx.fillRect(this._vx, this._vy, this._vw, this._vh); + } +}; + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var Texture2D = function Texture2D(device, options) { + this._device = device; - prototypeAccessors.alphaThreshold.get = function () { - return this._effect.getProperty('alphaThreshold'); - }; - - prototypeAccessors.alphaThreshold.set = function (val) { - this._effect.setProperty('alphaThreshold', val); - }; - - StencilMaterial.prototype.clone = function clone () { - var copy = new StencilMaterial(values); - copy.useTexture = this.useTexture; - copy.texture = this.texture; - copy.alphaThreshold = this.alphaThreshold; - copy.updateHash(); - return copy; - }; - - Object.defineProperties( StencilMaterial.prototype, prototypeAccessors ); - - return StencilMaterial; - }(Material)); - - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var ParticleMaterial = (function (Material$$1) { - function ParticleMaterial() { - Material$$1.call(this, false); - - var pass = new renderer.Pass('vfx_particle'); - pass.setDepth(false, false); - pass.setCullMode(gfx.CULL_NONE); - pass.setBlend( - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA - ); - - var mainTech = new renderer.Technique( - ['transparent'], - [ - { name: 'texture', type: renderer.PARAM_TEXTURE_2D }, - { name: 'state', type: renderer.PARAM_TEXTURE_2D }, - { name: 'quad', type: renderer.PARAM_TEXTURE_2D }, - { name: 'z', type: renderer.PARAM_FLOAT }, - { name: 'statesize', type: renderer.PARAM_FLOAT2 }, - { name: 'quadsize', type: renderer.PARAM_FLOAT2 }, - { name: 'lb', type: renderer.PARAM_FLOAT2 }, - { name: 'rt', type: renderer.PARAM_FLOAT2 } ], - [ - pass - ] - ); - - this._effect = new renderer.Effect( - [ - mainTech ], - {}, - [] - ); - - this._mainTech = mainTech; - this._texture = null; - this._lb = vec2.create(); - this._rt = vec2.create(); + this._width = 4; + this._height = 4; + + this._image = null; + + if (options) { + if (options.width !== undefined) { + this._width = options.width; } - - if ( Material$$1 ) ParticleMaterial.__proto__ = Material$$1; - ParticleMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); - ParticleMaterial.prototype.constructor = ParticleMaterial; - - var prototypeAccessors = { effect: {},texture: {},stateMap: {},quadMap: {},stateSize: {},quadSize: {},z: {},uv: {} }; - - prototypeAccessors.effect.get = function () { - return this._effect; - }; - - prototypeAccessors.texture.get = function () { - return this._texture; - }; - - prototypeAccessors.texture.set = function (val) { - if (this._texture !== val) { - this._texture = val; - this._effect.setProperty('texture', val.getImpl()); - this._texIds['texture'] = val.getId(); - } - }; - - prototypeAccessors.stateMap.get = function () { - return this._effect.getProperty('state'); - }; - - prototypeAccessors.stateMap.set = function (val) { - this._effect.setProperty('state', val); - }; - - prototypeAccessors.quadMap.get = function () { - return this._effect.getProperty('quad'); - }; - - prototypeAccessors.quadMap.set = function (val) { - this._effect.setProperty('quad', val); - }; - - prototypeAccessors.stateSize.get = function () { - return this._effect.getProperty('statesize'); - }; - - prototypeAccessors.stateSize.set = function (val) { - this._effect.setProperty('statesize', val); - }; - - prototypeAccessors.quadSize.get = function () { - return this._effect.getProperty('quadsize'); - }; - - prototypeAccessors.quadSize.set = function (val) { - this._effect.setProperty('quadsize', val); - }; - - prototypeAccessors.z.get = function () { - return this._effect.getProperty('z'); - }; - - prototypeAccessors.z.set = function (val) { - this._effect.setProperty('z', val); - }; - - prototypeAccessors.uv.get = function () { - var lb = this._effect.getProperty('lb'); - var rt = this._effect.getProperty('rt'); - return { - l: lb.x, - r: rt.x, - b: lb.y, - t: rt.y - } - }; - - prototypeAccessors.uv.set = function (val) { - this._lb.x = val.l; - this._lb.y = val.b; - this._rt.x = val.r; - this._rt.y = val.t; - this._effect.setProperty('lb', this._lb); - this._effect.setProperty('rt', this._rt); - }; - - ParticleMaterial.prototype.clone = function clone () { - var copy = new ParticleMaterial(values); - copy.texture = this.texture; - copy.stateMap = this.stateMap; - copy.quadMap = this.quadMap; - copy.stateSize = this.stateSize; - copy.quadSize = this.quadSize; - copy.z = this.z; - copy.uv = this.uv; - copy.updateHash(); - return copy; - }; - - Object.defineProperties( ParticleMaterial.prototype, prototypeAccessors ); - - return ParticleMaterial; - }(Material)); - - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var Device = function Device(canvasEL) { - var ctx; - - try { - ctx = canvasEL.getContext('2d'); - } catch (err) { - console.error(err); - return; + if (options.height !== undefined) { + this._height = options.height; } - - // statics - this._canvas = canvasEL; - this._ctx = ctx; - this._caps = {}; // capability - this._stats = { - drawcalls: 0, - }; - - // runtime - this._vx = this._vy = this._vw = this._vh = 0; - this._sx = this._sy = this._sw = this._sh = 0; - }; - - Device.prototype._restoreTexture = function _restoreTexture (unit) { - }; - - // =============================== - // Immediate Settings - // =============================== - - /** - * @method setViewport - * @param {Number} x - * @param {Number} y - * @param {Number} w - * @param {Number} h - */ - Device.prototype.setViewport = function setViewport (x, y, w, h) { - if ( - this._vx !== x || - this._vy !== y || - this._vw !== w || - this._vh !== h - ) { - this._vx = x; - this._vy = y; - this._vw = w; - this._vh = h; - } - }; - - /** - * @method setScissor - * @param {Number} x - * @param {Number} y - * @param {Number} w - * @param {Number} h - */ - Device.prototype.setScissor = function setScissor (x, y, w, h) { - if ( - this._sx !== x || - this._sy !== y || - this._sw !== w || - this._sh !== h - ) { - this._sx = x; - this._sy = y; - this._sw = w; - this._sh = h; - } - }; - - Device.prototype.clear = function clear (color) { - var ctx = this._ctx; - ctx.clearRect(this._vx, this._vy, this._vw, this._vh); - if (color && (color[0] !== 0 || color[1] !== 0 || color[2] !== 0)) { - ctx.fillStyle = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] +')'; - ctx.globalAlpha = color[3]; - ctx.fillRect(this._vx, this._vy, this._vw, this._vh); - } - }; - - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - var Texture2D = function Texture2D(device, options) { - this._device = device; - - this._width = 4; - this._height = 4; - - this._image = null; - - if (options) { - if (options.width !== undefined) { - this._width = options.width; - } - if (options.height !== undefined) { - this._height = options.height; - } - - this.updateImage(options); - } - }; - - Texture2D.prototype.update = function update (options) { + this.updateImage(options); - }; - - Texture2D.prototype.updateImage = function updateImage (options) { - if (options.images && options.images[0]) { - var image = options.images[0]; - if (image && image !== this._image) { - this._image = image; - } + } +}; + +Texture2D.prototype.update = function update (options) { + this.updateImage(options); +}; + +Texture2D.prototype.updateImage = function updateImage (options) { + if (options.images && options.images[0]) { + var image = options.images[0]; + if (image && image !== this._image) { + this._image = image; } - }; + } +}; + +Texture2D.prototype.destroy = function destroy () { + this._image = null; +}; + +var canvas = { + Device: Device, + Texture2D: Texture2D +}; + +// intenral +// deps +var Scene = renderer.Scene; +var Camera = renderer.Camera; +var View = renderer.View; +var Texture2D$2 = gfx.Texture2D; +var Device$2 = gfx.Device; +var Model = renderer.Model; +var InputAssembler = renderer.InputAssembler; + +var renderEngine = { + // core classes + Device: Device$2, + ForwardRenderer: ForwardRenderer, + Texture2D: Texture2D$2, + + // Canvas render support + canvas: canvas, + + // render scene + Scene: Scene, + Camera: Camera, + View: View, + Model: Model, + RenderData: RenderData, + IARenderData: IARenderData, + InputAssembler: InputAssembler, + + // vfx + Particles: Particles, - Texture2D.prototype.destroy = function destroy () { - this._image = null; - }; + // assets + Asset: Asset, + TextureAsset: Texture, + Material: Material, - var canvas = { - Device: Device, - Texture2D: Texture2D - }; - - // intenral - // deps - var Scene = renderer.Scene; - var Camera = renderer.Camera; - var View = renderer.View; - var Texture2D$2 = gfx.Texture2D; - var Device$2 = gfx.Device; - var Model = renderer.Model; - var InputAssembler = renderer.InputAssembler; - - var renderEngine = { - // core classes - Device: Device$2, - ForwardRenderer: ForwardRenderer, - Texture2D: Texture2D$2, - - // Canvas render support - canvas: canvas, - - // render scene - Scene: Scene, - Camera: Camera, - View: View, - Model: Model, - RenderData: RenderData, - IARenderData: IARenderData, - InputAssembler: InputAssembler, - - // vfx - Particles: Particles, - - // assets - Asset: Asset, - TextureAsset: Texture, - Material: Material, - - // materials - SpriteMaterial: SpriteMaterial, - GraySpriteMaterial: GraySpriteMaterial, - StencilMaterial: StencilMaterial, - ParticleMaterial: ParticleMaterial, - - // shaders - shaders: shaders, - - // memop - RecyclePool: RecyclePool, - Pool: Pool, - - // modules - math: math, - renderer: renderer, - gfx: gfx, - }; - - return renderEngine; - - }()); - \ No newline at end of file + // materials + SpriteMaterial: SpriteMaterial, + GraySpriteMaterial: GraySpriteMaterial, + StencilMaterial: StencilMaterial, + ParticleMaterial: ParticleMaterial, + + // shaders + shaders: shaders, + + // memop + RecyclePool: RecyclePool, + Pool: Pool, + + // modules + math: math, + renderer: renderer, + gfx: gfx, +}; + +return renderEngine; + +}()); diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index 8417681692..7593cc4914 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -271,6 +271,8 @@ if (CC_DEV) { // cc.Node markAsRemoved(cc._BaseNode, [ 'tag', + 'getTag', + 'setTag', 'getChildByTag', 'removeChildByTag' ]); @@ -291,6 +293,7 @@ if (CC_DEV) { 'isIgnoreAnchorPointForPosition', 'ignoreAnchorPointForPosition', 'isRunning', + '_sgNode', ]); markFunctionWarning(cc.Node.prototype, { @@ -317,6 +320,10 @@ if (CC_DEV) { setSkewX: 'skewX', getSkewY: 'skewY', setSkewY: 'skewY', + getScaleX: 'scaleX', + setScaleX: 'scaleX', + getScaleY: 'scaleY', + setScaleY: 'scaleY', getOpacity: 'opacity', setOpacity: 'opacity', getColor: 'color', From fbbdf7e8c8a9ea0ccd94dd25a04b486451bfcc0a Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Fri, 30 Mar 2018 15:16:19 +0800 Subject: [PATCH 04/35] adjust motion streak structure --- .../components}/CCMotionStreak.js | 6 ++--- cocos2d/core/components/index.js | 1 + cocos2d/core/renderer/assemblers/index.js | 1 + .../renderer/assemblers/motion-streak.js} | 9 ++++--- cocos2d/motion-streak/index.js | 27 ------------------- extends.js | 1 - modules.json | 3 ++- 7 files changed, 12 insertions(+), 36 deletions(-) rename cocos2d/{motion-streak => core/components}/CCMotionStreak.js (97%) rename cocos2d/{motion-streak/motion-streak-assembler.js => core/renderer/assemblers/motion-streak.js} (96%) delete mode 100644 cocos2d/motion-streak/index.js diff --git a/cocos2d/motion-streak/CCMotionStreak.js b/cocos2d/core/components/CCMotionStreak.js similarity index 97% rename from cocos2d/motion-streak/CCMotionStreak.js rename to cocos2d/core/components/CCMotionStreak.js index a663159855..24623e2b80 100644 --- a/cocos2d/motion-streak/CCMotionStreak.js +++ b/cocos2d/core/components/CCMotionStreak.js @@ -24,9 +24,9 @@ THE SOFTWARE. ****************************************************************************/ -const RenderComponent = require('../core/components/CCRenderComponent'); -const renderer = require('../core/renderer'); -const renderEngine = require('../core/renderer/render-engine'); +const RenderComponent = require('../components/CCRenderComponent'); +const renderer = require('../renderer'); +const renderEngine = require('../renderer/render-engine'); const SpriteMaterial = renderEngine.SpriteMaterial; /** diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js index dac7750edb..d5bfad41bb 100644 --- a/cocos2d/core/components/index.js +++ b/cocos2d/core/components/index.js @@ -51,6 +51,7 @@ var components = [ require('./CCToggleGroup'), require('./CCToggle'), require('./CCBlockInputEvents'), + require('./CCMotionStreak') ]; // Delay require render components assemblers diff --git a/cocos2d/core/renderer/assemblers/index.js b/cocos2d/core/renderer/assemblers/index.js index 55f9daabd7..65a9b28071 100644 --- a/cocos2d/core/renderer/assemblers/index.js +++ b/cocos2d/core/renderer/assemblers/index.js @@ -27,3 +27,4 @@ require('./sprite'); require('./mask-assembler'); require('./graphics'); require('./label'); +require('./motion-streak'); diff --git a/cocos2d/motion-streak/motion-streak-assembler.js b/cocos2d/core/renderer/assemblers/motion-streak.js similarity index 96% rename from cocos2d/motion-streak/motion-streak-assembler.js rename to cocos2d/core/renderer/assemblers/motion-streak.js index f62131cc25..3bbbf903ce 100644 --- a/cocos2d/motion-streak/motion-streak-assembler.js +++ b/cocos2d/core/renderer/assemblers/motion-streak.js @@ -23,10 +23,11 @@ THE SOFTWARE. ****************************************************************************/ -const js = require('../core/platform/js'); -const assembler = require('../core/renderer/assemblers/assembler'); -const MotionStreak = require('./CCMotionStreak'); -const renderEngine = require('../core/renderer/render-engine'); +const js = require('../../platform/js'); +const assembler = require('../../renderer/assemblers/assembler'); +const renderEngine = require('../../renderer/render-engine'); + +const MotionStreak = require('../../components/CCMotionStreak'); function Point (point, dir) { this.point = point || cc.v2(); diff --git a/cocos2d/motion-streak/index.js b/cocos2d/motion-streak/index.js deleted file mode 100644 index 505944d9e3..0000000000 --- a/cocos2d/motion-streak/index.js +++ /dev/null @@ -1,27 +0,0 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -require('./CCMotionStreak'); -require('./motion-streak-assembler'); \ No newline at end of file diff --git a/extends.js b/extends.js index f36895ddea..7da1a785dc 100644 --- a/extends.js +++ b/extends.js @@ -36,7 +36,6 @@ else { require('./cocos2d/tilemap'); require('./cocos2d/videoplayer/CCVideoPlayer'); require('./cocos2d/webview/CCWebView'); - require('./cocos2d/motion-streak'); require('./cocos2d/core/components/CCStudioComponent'); require('./extensions/ccpool/CCNodePool'); if (!CC_JSB) { diff --git a/modules.json b/modules.json index dc4fde30c1..71082176f0 100644 --- a/modules.json +++ b/modules.json @@ -172,7 +172,8 @@ { "name": "MotionStreak", "entries": [ - "./cocos2d/motion-streak/index.js" + "./cocos2d/core/components/motion-streak/CCMotionStreak.js", + "./cocos2d/core/renderer/assemblers/motion-streak.js" ] }, { From 0e0024fcbe7625bc8796ca3f241be00b4c9d915f Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Fri, 30 Mar 2018 15:23:50 +0800 Subject: [PATCH 05/35] adjust assembler requirements --- cocos2d/core/CCGame.js | 3 +-- cocos2d/core/components/index.js | 3 --- .../core/renderer/canvas/canvas-render-walker.js | 14 ++++++-------- cocos2d/core/renderer/canvas/renderers/index.js | 2 +- cocos2d/core/renderer/index.js | 6 +++++- 5 files changed, 13 insertions(+), 15 deletions(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index a96f6b8d69..bd8577517e 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -764,8 +764,7 @@ var game = { if (!this._renderContext) { game.renderType = game.RENDER_TYPE_CANVAS; // Could be ignored by module settings - var canvasRenderer = require('./renderer/canvas'); - renderer.initCanvas(localCanvas, canvasRenderer); + renderer.initCanvas(localCanvas); this._renderContext = renderer.device._ctx; } cc.renderer = renderer; diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js index d5bfad41bb..c36c0c2f38 100644 --- a/cocos2d/core/components/index.js +++ b/cocos2d/core/components/index.js @@ -54,7 +54,4 @@ var components = [ require('./CCMotionStreak') ]; -// Delay require render components assemblers -require('../renderer/assemblers'); - module.exports = components; \ No newline at end of file diff --git a/cocos2d/core/renderer/canvas/canvas-render-walker.js b/cocos2d/core/renderer/canvas/canvas-render-walker.js index 5868e3d264..135e949da0 100644 --- a/cocos2d/core/renderer/canvas/canvas-render-walker.js +++ b/cocos2d/core/renderer/canvas/canvas-render-walker.js @@ -25,8 +25,6 @@ const js = require('../../platform/js'); const renderers = require('./renderers'); -const rendererMap = renderers.map; -const postRendererMap = renderers.postMap; let RenderComponentWalker = function (device, defaultCamera) { this._device = device; @@ -50,18 +48,18 @@ RenderComponentWalker.prototype = { let comp = node._renderComponent; let opacity = node.opacity; - let compName = js.getClassName(comp); - if (opacity && compName && rendererMap[compName]) { - this._render(comp, rendererMap[compName]); + let assembler = comp && comp.constructor._assembler; + if (opacity && assembler) { + this._render(comp, assembler); } }, _postHandleRender (node) { let comp = node._renderComponent; let opacity = node.opacity; - let compName = js.getClassName(comp); - if (opacity && compName && postRendererMap[compName]) { - this._render(comp, postRendererMap[compName]); + let postAssembler = comp && comp.constructor._postAssembler; + if (opacity && postAssembler) { + this._render(comp, postAssembler); } }, diff --git a/cocos2d/core/renderer/canvas/renderers/index.js b/cocos2d/core/renderer/canvas/renderers/index.js index 36b701183d..61bd17a42b 100644 --- a/cocos2d/core/renderer/canvas/renderers/index.js +++ b/cocos2d/core/renderer/canvas/renderers/index.js @@ -49,7 +49,7 @@ function addRenderer (Component, handler, postHandler) { postMap[name] = postHandler; } Component._assembler = handler; - Component._postAssembler = handler; + Component._postAssembler = postHandler; } addRenderer(Sprite, spriteRenderer); diff --git a/cocos2d/core/renderer/index.js b/cocos2d/core/renderer/index.js index e1e7a6c1e8..630741377d 100644 --- a/cocos2d/core/renderer/index.js +++ b/cocos2d/core/renderer/index.js @@ -61,6 +61,8 @@ module.exports = { _forward: null, initWebGL (canvas, opts) { + require('./assemblers'); + this.Texture2D = renderEngine.Texture2D; this.canvas = canvas; @@ -96,7 +98,9 @@ module.exports = { this._forward = new renderEngine.ForwardRenderer(this.device, builtins); }, - initCanvas (canvas, canvasRenderer) { + initCanvas (canvas) { + let canvasRenderer = require('./canvas'); + this.Texture2D = renderEngine.canvas.Texture2D; this.canvas = canvas; From 2a3798b1a0e347665ecad3bf2b531e98bed13a31 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 30 Mar 2018 17:19:36 +0800 Subject: [PATCH 06/35] Support generate colorized frame image --- .../core/renderer/canvas/renderers/utils.js | 153 +++++++++++------- 1 file changed, 99 insertions(+), 54 deletions(-) diff --git a/cocos2d/core/renderer/canvas/renderers/utils.js b/cocos2d/core/renderer/canvas/renderers/utils.js index 242b98a404..75fff4970c 100644 --- a/cocos2d/core/renderer/canvas/renderers/utils.js +++ b/cocos2d/core/renderer/canvas/renderers/utils.js @@ -24,28 +24,59 @@ ****************************************************************************/ const WHITE = (255<<16) + (255<<8) + 255; +const MAX_CANVAS_COUNT = 32; -let textureColorizer = { - colorCanvas: {}, - colorUsed: {}, +function colorizedFrame (canvas, texture, color, sx, sy, sw, sh) { + let image = texture._image; + + let ctx = canvas.getContext("2d"); + canvas.width = sw; + canvas.height = sh; + + // Draw color + ctx.globalCompositeOperation = 'source-over'; + ctx.fillStyle = 'rgba(' + color.r + ',' + color.g + ',' + color.b + ')'; + ctx.fillRect(0, 0, sw, sh); + + // Multiply color with texture + ctx.globalCompositeOperation = 'multiply'; + ctx.drawImage(image, sx, sy, sw, sh, 0, 0, sw, sh); + + // Clip out transparent pixels + ctx.globalCompositeOperation = "destination-atop"; + ctx.drawImage(image, sx, sy, sw, sh, 0, 0, sw, sh); + return canvas; +} + +let canvasMgr = { + canvasMap: {}, + canvasUsed: {}, canvasPool: [], checking: false, check () { - for (let key in this.colorUsed) { - if (!this.colorUsed[key]) { - let canvas = this.colorCanvas[key]; + let exist = false; + for (let key in this.canvasUsed) { + exist = true; + if (!this.canvasUsed[key]) { + let canvas = this.canvasMap[key]; canvas.width = 0; canvas.height = 0; - this.canvasPool.push(canvas); - delete this.colorCanvas[key]; - delete this.colorUsed[key]; + if (this.canvasPool.length < 32) { + this.canvasPool.push(canvas); + } + delete this.canvasMap[key]; + delete this.canvasUsed[key]; } else { - this.colorUsed[key] = false; + this.canvasUsed[key] = false; } } + if (!exist) { + cc.director.off(cc.Director.EVENT_AFTER_DRAW, this.check, this); + this.checking = false; + } }, startCheck () { @@ -53,11 +84,33 @@ let textureColorizer = { this.checking = true; }, - getImage (texture, color) { + getCanvas (key) { + this.canvasUsed[key] = true; + return this.canvasMap[key]; + }, + + cacheCanvas (canvas, key) { + this.canvasMap[key] = canvas; + this.canvasUsed[key] = true; + if (!this.checking) { + this.startCheck(); + } + }, + + // dropImage (texture, color) { + // let key = texture.url + (color._val & 0x00ffffff); + // if (this.canvasMap[key]) { + // delete this.canvasMap[key]; + // } + // } +}; + +module.exports = { + getColorizedImage (texture, color) { if (!texture || !texture.url) { return null; } - + // original image let cval = color._val & 0x00ffffff; if (cval === WHITE) { @@ -66,50 +119,42 @@ let textureColorizer = { // get from cache let key = texture.url + cval; - if (this.colorCanvas[key]) { - this.colorUsed[key] = true; - return this.colorCanvas[key]; + let cache = canvasMgr.getCanvas(key); + if (!cache) { + cache = canvasMgr.canvasPool.pop() || document.createElement("canvas"); + colorizedFrame(cache, texture, color, 0, 0, texture.width, texture.height); + canvasMgr.cacheCanvas(cache, key); } - - let x = 0, y = 0, w = texture.width, h = texture.height; - let image = texture._image; - - let canvas = this.canvasPool.pop() || document.createElement("canvas"); - let ctx = canvas.getContext("2d"); - canvas.width = w; - canvas.height = h; - - // Draw color - ctx.globalCompositeOperation = 'source-over'; - ctx.fillStyle = 'rgba(' + color.r + ',' + color.g + ',' + color.b + ')'; - ctx.fillRect(x, y, w, h); - - // Multiply color with texture - ctx.globalCompositeOperation = 'multiply'; - ctx.drawImage(image, x, y, w, h); - - // Clip out transparent pixels - ctx.globalCompositeOperation = "destination-atop"; - ctx.drawImage(image, x, y, w, h); - - this.colorCanvas[key] = canvas; - this.colorUsed[key] = true; - if (!this.checking) { - this.startCheck(); - } - return canvas; + return cache; }, - - dropImage (texture, color) { - let key = texture.url + (color._val & 0x00ffffff); - if (this.colorCanvas[key]) { - delete this.colorCanvas[key]; - } - } -}; -module.exports = { - getColorizedImage (texture, color) { - return textureColorizer.getImage(texture, color); + getFrameCache (texture, color, sx, sy, sw, sh) { + if (!texture || !texture.url || sx < 0 || sy < 0 || sw <= 0 || sh <= 0) { + return null; + } + + let key = texture.url; + let generate = false; + let cval = color._val & 0x00ffffff; + if (cval !== WHITE) { + key += cval; + generate = true; + } + if (sx !== 0 || sy !== 0 && sw !== texture.width && sh !== texture.height) { + key += '_' + sx + '_' + sy + '_' + sw + '_' + sh; + generate = true; + } + if (!generate) { + return texture._image; + } + + // get from cache + let cache = canvasMgr.getCanvas(key); + if (!cache) { + cache = canvasMgr.canvasPool.pop() || document.createElement("canvas"); + colorizedFrame(cache, texture, color, sx, sy, sw, sh); + canvasMgr.cacheCanvas(cache, key); + } + return cache; } }; \ No newline at end of file From e02c2afa6d918fdde62b255dc960c278b9e8f034 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 30 Mar 2018 17:29:16 +0800 Subject: [PATCH 07/35] Support Tiled Sprite --- .../renderer/canvas/renderers/sprite/index.js | 20 +---- .../canvas/renderers/sprite/simple.js | 39 +++++++--- .../canvas/renderers/sprite/sliced.js | 3 + .../renderer/canvas/renderers/sprite/tiled.js | 73 +++++++++++++++++++ 4 files changed, 106 insertions(+), 29 deletions(-) create mode 100644 cocos2d/core/renderer/canvas/renderers/sprite/tiled.js diff --git a/cocos2d/core/renderer/canvas/renderers/sprite/index.js b/cocos2d/core/renderer/canvas/renderers/sprite/index.js index 38883213bd..04fe8680a1 100644 --- a/cocos2d/core/renderer/canvas/renderers/sprite/index.js +++ b/cocos2d/core/renderer/canvas/renderers/sprite/index.js @@ -26,6 +26,7 @@ let SpriteType = require('../../../../components/CCSprite').Type; let simple = require('./simple'); let sliced = require('./sliced'); +let tiled = require('./tiled'); module.exports = { getAssembler: function (sprite) { @@ -35,7 +36,7 @@ module.exports = { case SpriteType.SLICED: return sliced; case SpriteType.TILED: - return null; + return tiled; case SpriteType.FILLED: if (sprite._fillType === FillType.RADIAL) { return null; @@ -50,21 +51,6 @@ module.exports = { return sprite._assembler.createData(sprite); }, - update (sprite) { - let renderData = sprite._renderData; - if (!renderData) { - return; - } - - if (renderData.uvDirty) { - sprite._assembler.updateUVs(sprite); - } - - if (renderData.vertDirty) { - sprite._assembler.updateVerts(sprite); - } - }, - draw (ctx, sprite) { let node = sprite.node; // Check whether need to render @@ -72,7 +58,7 @@ module.exports = { return 0; } // update - this.update(sprite); + sprite._assembler.update(sprite); return sprite._assembler.draw(ctx, sprite); } diff --git a/cocos2d/core/renderer/canvas/renderers/sprite/simple.js b/cocos2d/core/renderer/canvas/renderers/sprite/simple.js index 1bb2760719..07d954ebb4 100644 --- a/cocos2d/core/renderer/canvas/renderers/sprite/simple.js +++ b/cocos2d/core/renderer/canvas/renderers/sprite/simple.js @@ -34,6 +34,21 @@ let renderer = { return renderData; }, + update (sprite) { + let renderData = sprite._renderData; + if (!renderData) { + return; + } + + if (renderData.uvDirty) { + this.updateUVs(sprite); + } + + if (renderData.vertDirty) { + this.updateVerts(sprite); + } + }, + updateUVs (sprite) { let frame = sprite.spriteFrame; let renderData = sprite._renderData; @@ -43,9 +58,9 @@ let renderer = { if (frame._rotated) { let l = rect.x; - let r = rect.x + rect.height; + let r = rect.height; let b = rect.y; - let t = rect.y + rect.width; + let t = rect.width; data[0].u = l; data[0].v = t; data[1].u = r; @@ -53,9 +68,9 @@ let renderer = { } else { let l = rect.x; - let r = rect.x + rect.width; + let r = rect.width; let b = rect.y; - let t = rect.y + rect.height; + let t = rect.height; data[0].u = l; data[0].v = b; data[1].u = r; @@ -75,8 +90,8 @@ let renderer = { if (sprite.trim) { l = -appx; b = -appy; - r = cw - appx; - t = ch - appy; + r = cw; + t = ch; } else { let frame = sprite.spriteFrame, @@ -90,8 +105,8 @@ let renderer = { let trimTop = offset.y - (oh - rh) / 2; l = trimLeft * scaleX - appx; b = trimBottom * scaleY - appy; - r = cw + trimRight * scaleX - appx; - t = ch + trimTop * scaleY - appy; + r = cw; + t = ch; } data[0].x = l; @@ -122,14 +137,14 @@ let renderer = { let x = data[0].x; let y = data[0].y; - let w = data[1].x - x; - let h = data[1].y - y; + let w = data[1].x; + let h = data[1].y; y = - y - h; let sx = data[0].u; let sy = data[0].v; - let sw = data[1].u - sx; - let sh = data[1].v - sy; + let sw = data[1].u; + let sh = data[1].v; ctx.drawImage(image, sx, sy, sw, sh, diff --git a/cocos2d/core/renderer/canvas/renderers/sprite/sliced.js b/cocos2d/core/renderer/canvas/renderers/sprite/sliced.js index 38cfd63df0..e47f412f36 100644 --- a/cocos2d/core/renderer/canvas/renderers/sprite/sliced.js +++ b/cocos2d/core/renderer/canvas/renderers/sprite/sliced.js @@ -24,6 +24,7 @@ ****************************************************************************/ const utils = require('../utils'); +const simple = require('./simple'); let renderer = { createData (sprite) { @@ -32,6 +33,8 @@ let renderer = { renderData.dataLength = 4; return renderData; }, + + update: simple.update, updateUVs (sprite) { let frame = sprite.spriteFrame; diff --git a/cocos2d/core/renderer/canvas/renderers/sprite/tiled.js b/cocos2d/core/renderer/canvas/renderers/sprite/tiled.js new file mode 100644 index 0000000000..c14627a175 --- /dev/null +++ b/cocos2d/core/renderer/canvas/renderers/sprite/tiled.js @@ -0,0 +1,73 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +const utils = require('../utils'); +const simple = require('./simple'); + +let renderer = { + createData (sprite) { + let renderData = sprite.requestRenderData(); + return renderData; + }, + + update (sprite) {}, + + draw (ctx, sprite) { + let node = sprite.node; + // Transform + let matrix = node._worldMatrix; + let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, + tx = matrix.m12, ty = matrix.m13; + ctx.transform(a, b, c, d, tx, -ty); + + // TODO: handle blend function + + // opacity + ctx.glphaAlpha = node.opacity / 255; + + let frame = sprite.spriteFrame; + let rect = frame._rect; + let tex = frame._texture; + let sx = rect.x; + let sy = rect.y; + let sw = frame._rotated ? rect.height : rect.width; + let sh = frame._rotated ? rect.width : rect.height; + + let image = utils.getFrameCache(tex, node.color, sx, sy, sw, sh); + + let w = node.width, + h = node.height, + x = -node.anchorX * w, + y = -node.anchorY * h; + y = - y - h; + + ctx.translate(x, y); + ctx.fillStyle = ctx.createPattern(image, 'repeat'); + ctx.fillRect(0, 0, w, h); + return 1; + } +} + +module.exports = renderer \ No newline at end of file From 55820e02eb2a51c9a5249584cb70ad64b4e00778 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Fri, 30 Mar 2018 18:37:32 +0800 Subject: [PATCH 08/35] optimize graphics --- cocos2d/core/graphics/graphics.js | 176 ++------------- .../core/renderer/assemblers/graphics/impl.js | 208 ++++++++++++++++++ .../renderer/assemblers/graphics/index.js | 103 +++++---- .../renderer/assemblers/mask-assembler.js | 2 +- 4 files changed, 287 insertions(+), 202 deletions(-) create mode 100644 cocos2d/core/renderer/assemblers/graphics/impl.js diff --git a/cocos2d/core/graphics/graphics.js b/cocos2d/core/graphics/graphics.js index 4eb331fb3f..487d3367a7 100644 --- a/cocos2d/core/graphics/graphics.js +++ b/cocos2d/core/graphics/graphics.js @@ -33,41 +33,6 @@ const Helper = require('./helper'); const Types = require('./types'); const LineCap = Types.LineCap; const LineJoin = Types.LineJoin; -const PointFlags = Types.PointFlags; - -// Point -function Point (x, y) { - cc.Vec2.call(this, x, y); - this.reset(); -} -cc.js.extend(Point, cc.Vec2); - -Point.prototype.reset = function () { - this.dx = 0; - this.dy = 0; - this.dmx = 0; - this.dmy = 0; - this.flags = 0; - this.len = 0; -}; - -// Path -function Path () { - this.reset(); -} -Path.prototype.reset = function () { - this.closed = false; - this.nbevel = 0; - this.complex = true; - - if (this.points) { - this.points.length = 0; - } - else { - this.points = []; - } -}; - /** * @class Graphics @@ -82,25 +47,7 @@ let Graphics = cc.Class({ }, ctor () { - // inner properties - this._tessTol = 0.25; - this._distTol = 0.01; - this._updatePathOffset = false; - - this._paths = null; - this._pathLength = 0; - this._pathOffset = 0; - - this._points = null; - this._pointsOffset = 0; - - this._commandx = 0; - this._commandy = 0; - - this._paths = []; - this._points = []; - - this._renderDatas = []; + this._impl = Graphics._assembler.createImpl(); }, properties: { @@ -228,8 +175,7 @@ let Graphics = cc.Class({ onDestroy () { this._super(); - // all requested render data will be destroyed by RenderComponent - this._renderDatas.length = 0; + this._impl = null; }, _activateMaterial () { @@ -248,16 +194,7 @@ let Graphics = cc.Class({ * @param {Number} [y] The y axis of the coordinate for the end point. */ moveTo (x, y) { - if (this._updatePathOffset) { - this._pathOffset = this._pathLength; - this._updatePathOffset = false; - } - - this._addPath(); - this._addPoint(x, y, PointFlags.PT_CORNER); - - this._commandx = x; - this._commandy = y; + this._impl.moveTo(x, y); }, /** @@ -268,10 +205,7 @@ let Graphics = cc.Class({ * @param {Number} [y] The y axis of the coordinate for the end point. */ lineTo (x, y) { - this._addPoint(x, y, PointFlags.PT_CORNER); - - this._commandx = x; - this._commandy = y; + this._impl.lineTo(x, y); }, /** @@ -286,18 +220,7 @@ let Graphics = cc.Class({ * @param {Number} [y] The y axis of the coordinate for the end point. */ bezierCurveTo (c1x, c1y, c2x, c2y, x, y) { - var path = this._curPath; - var last = path.points[path.points.length - 1]; - - if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) { - this.lineTo(x, y); - return; - } - - Helper.tesselateBezier(this, last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER); - - this._commandx = x; - this._commandy = y; + this._impl.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); }, /** @@ -310,9 +233,7 @@ let Graphics = cc.Class({ * @param {Number} [y] The y axis of the coordinate for the end point. */ quadraticCurveTo (cx, cy, x, y) { - var x0 = this._commandx; - var y0 = this._commandy; - this.bezierCurveTo(x0 + 2.0 / 3.0 * (cx - x0), y0 + 2.0 / 3.0 * (cy - y0), x + 2.0 / 3.0 * (cx - x), y + 2.0 / 3.0 * (cy - y), x, y); + this._impl.quadraticCurveTo(cx, cy, x, y); }, /** @@ -327,7 +248,7 @@ let Graphics = cc.Class({ * @param {Number} [counterclockwise] An optional Boolean which, if true, causes the arc to be drawn counter-clockwise between the two angles. By default it is drawn clockwise. */ arc (cx, cy, r, startAngle, endAngle, counterclockwise) { - Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); + this._impl.arc(cx, cy, r, startAngle, endAngle, counterclockwise); }, /** @@ -340,8 +261,7 @@ let Graphics = cc.Class({ * @param {Number} [ry] The ellipse's y-axis radius. */ ellipse (cx, cy, rx, ry) { - Helper.ellipse(this, cx, cy, rx, ry); - this._curPath.complex = false; + this._impl.ellipse(cx, cy, rx, ry); }, /** @@ -353,8 +273,7 @@ let Graphics = cc.Class({ * @param {Number} [r] The circle's radius. */ circle (cx, cy, r) { - Helper.ellipse(this, cx, cy, r, r); - this._curPath.complex = false; + this._impl.circle(cx, cy, r); }, /** @@ -367,12 +286,7 @@ let Graphics = cc.Class({ * @param {Number} [h] The rectangle's height. */ rect (x, y, w, h) { - this.moveTo(x, y); - this.lineTo(x, y + h); - this.lineTo(x + w, y + h); - this.lineTo(x + w, y); - this.close(); - this._curPath.complex = false; + this._impl.rect(x, y, w, h); }, /** @@ -386,8 +300,7 @@ let Graphics = cc.Class({ * @param {Number} [r] The radius of the rectangle. */ roundRect (x, y, w, h, r) { - Helper.roundRect(this, x, y, w, h, r); - this._curPath.complex = false; + this._impl.roundRect(x, y, w, h, r); }, /** @@ -411,29 +324,7 @@ let Graphics = cc.Class({ * @param {Boolean} [clean] Whether to clean the graphics inner cache. */ clear (clean) { - this._pathLength = 0; - this._pathOffset = 0; - this._pointsOffset = 0; - - this._curPath = null; - - let datas = this._renderDatas; - if (clean) { - this._paths.length = 0; - this._points.length = 0; - // manually destroy render datas - for (let i = 0, l = datas.length; i < l; i++) { - this.destroyRenderData(datas[i]); - } - datas.length = 0; - } - else { - for (let i = 0, l = datas.length; i < l; i++) { - let data = datas[i]; - data.vertexCount = data.indiceCount = data.dataLength = 0; - data._indices.length = 0; - } - } + this._impl.clear(this, clean); }, /** @@ -442,7 +333,7 @@ let Graphics = cc.Class({ * @method close */ close () { - this._curPath.closed = true; + this._impl.close(); }, /** @@ -461,47 +352,6 @@ let Graphics = cc.Class({ */ fill () { Graphics._assembler.fill(this); - }, - - _addPath () { - var offset = this._pathLength; - var path = this._paths[offset]; - - if (!path) { - path = new Path(); - - this._paths.push(path); - } else { - path.reset(); - } - - this._pathLength++; - this._curPath = path; - - return path; - }, - - _addPoint (x, y, flags) { - var path = this._curPath; - if (!path) return; - - var pt; - var points = this._points; - var pathPoints = path.points; - - var offset = this._pointsOffset++; - pt = points[offset]; - - if (!pt) { - pt = new Point(x, y); - points.push(pt); - } else { - pt.x = x; - pt.y = y; - } - - pt.flags = flags; - pathPoints.push(pt); } }); diff --git a/cocos2d/core/renderer/assemblers/graphics/impl.js b/cocos2d/core/renderer/assemblers/graphics/impl.js new file mode 100644 index 0000000000..b8775ca96a --- /dev/null +++ b/cocos2d/core/renderer/assemblers/graphics/impl.js @@ -0,0 +1,208 @@ + +const Helper = require('../../../graphics/helper'); +const PointFlags = require('../../../graphics/types').PointFlags; + +class Point extends cc.Vec2 { + constructor (x, y) { + super(x, y); + this.reset(); + } + + reset () { + this.dx = 0; + this.dy = 0; + this.dmx = 0; + this.dmy = 0; + this.flags = 0; + this.len = 0; + } +} + +class Path { + constructor () { + this.reset(); + } + + reset () { + this.closed = false; + this.nbevel = 0; + this.complex = true; + + if (this.points) { + this.points.length = 0; + } + else { + this.points = []; + } + } +} + +class Impl { + constructor () { + // inner properties + this._tessTol = 0.25; + this._distTol = 0.01; + this._updatePathOffset = false; + + this._paths = null; + this._pathLength = 0; + this._pathOffset = 0; + + this._points = null; + this._pointsOffset = 0; + + this._commandx = 0; + this._commandy = 0; + + this._paths = []; + this._points = []; + + this._renderDatas = []; + + this._dataOffset = 0; + } + + moveTo (x, y) { + if (this._updatePathOffset) { + this._pathOffset = this._pathLength; + this._updatePathOffset = false; + } + + this._addPath(); + this._addPoint(x, y, PointFlags.PT_CORNER); + + this._commandx = x; + this._commandy = y; + } + + lineTo (x, y) { + this._addPoint(x, y, PointFlags.PT_CORNER); + + this._commandx = x; + this._commandy = y; + } + + bezierCurveTo (c1x, c1y, c2x, c2y, x, y) { + var path = this._curPath; + var last = path.points[path.points.length - 1]; + + if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) { + this.lineTo(x, y); + return; + } + + Helper.tesselateBezier(this, last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER); + + this._commandx = x; + this._commandy = y; + } + + quadraticCurveTo (cx, cy, x, y) { + var x0 = this._commandx; + var y0 = this._commandy; + this.bezierCurveTo(x0 + 2.0 / 3.0 * (cx - x0), y0 + 2.0 / 3.0 * (cy - y0), x + 2.0 / 3.0 * (cx - x), y + 2.0 / 3.0 * (cy - y), x, y); + } + + arc (cx, cy, r, startAngle, endAngle, counterclockwise) { + Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); + } + + ellipse (cx, cy, rx, ry) { + Helper.ellipse(this, cx, cy, rx, ry); + this._curPath.complex = false; + } + + circle (cx, cy, r) { + Helper.ellipse(this, cx, cy, r, r); + this._curPath.complex = false; + } + + rect (x, y, w, h) { + this.moveTo(x, y); + this.lineTo(x, y + h); + this.lineTo(x + w, y + h); + this.lineTo(x + w, y); + this.close(); + this._curPath.complex = false; + } + + roundRect (x, y, w, h, r) { + Helper.roundRect(this, x, y, w, h, r); + this._curPath.complex = false; + } + + clear (comp, clean) { + this._pathLength = 0; + this._pathOffset = 0; + this._pointsOffset = 0; + + this._dataOffset = 0; + + this._curPath = null; + + let datas = this._renderDatas; + if (clean) { + this._paths.length = 0; + this._points.length = 0; + // manually destroy render datas + for (let i = 0, l = datas.length; i < l; i++) { + comp.destroyRenderData(datas[i]); + } + datas.length = 0; + } + else { + for (let i = 0, l = datas.length; i < l; i++) { + let data = datas[i]; + data.indiceCount = data._indices.length = 0; + data.vertexCount = 0; + } + } + } + + close () { + this._curPath.closed = true; + } + + _addPath () { + var offset = this._pathLength; + var path = this._paths[offset]; + + if (!path) { + path = new Path(); + + this._paths.push(path); + } else { + path.reset(); + } + + this._pathLength++; + this._curPath = path; + + return path; + } + + _addPoint (x, y, flags) { + var path = this._curPath; + if (!path) return; + + var pt; + var points = this._points; + var pathPoints = path.points; + + var offset = this._pointsOffset++; + pt = points[offset]; + + if (!pt) { + pt = new Point(x, y); + points.push(pt); + } else { + pt.x = x; + pt.y = y; + } + + pt.flags = flags; + pathPoints.push(pt); + } +} + +module.exports = Impl; diff --git a/cocos2d/core/renderer/assemblers/graphics/index.js b/cocos2d/core/renderer/assemblers/graphics/index.js index 5f9e8a5c19..752cba56e8 100644 --- a/cocos2d/core/renderer/assemblers/graphics/index.js +++ b/cocos2d/core/renderer/assemblers/graphics/index.js @@ -28,6 +28,7 @@ const PointFlags = require('../../../graphics/types').PointFlags; const LineJoin = Graphics.LineJoin; const LineCap = Graphics.LineCap; const Earcut = require('./earcut'); +const Impl = require('./impl'); const macro = require('../../../platform/CCMacro'); const MAX_VERTEX = macro.BATCH_VERTEX_COUNT; @@ -50,6 +51,7 @@ const abs = Math.abs; let _matrix = math.mat4.create(); let _renderData = null; +let _impl = null; let _curColor = 0; function curveDivs (r, arc, tol) { @@ -68,8 +70,12 @@ function clamp (v, min, max) { } let graphicsAssembler = js.addon({ + createImpl () { + return new Impl(); + }, + updateRenderData (graphics) { - let datas = graphics._renderDatas; + let datas = graphics._impl._renderDatas; if (datas.length === 0) { datas.push(graphics.requestRenderData()); } @@ -98,7 +104,7 @@ let graphicsAssembler = js.addon({ nodeG = nodeColor.g / 255, nodeB = nodeColor.b / 255, nodeA = nodeColor.a / 255; - for (let i = 0, l = data.length; i < l; i++) { + for (let i = 0, l = renderData.vertexCount; i < l; i++) { vbuf[offset++] = data[i].x * a + data[i].y * c + tx; vbuf[offset++] = data[i].x * b + data[i].y * d + ty; vbuf[offset++] = z; @@ -122,38 +128,55 @@ let graphicsAssembler = js.addon({ }, genRenderData (graphics, cverts) { - let renderDatas = graphics._renderDatas; - let renderData = renderDatas[renderDatas.length - 1]; - let maxVertsCount = renderData.dataLength + cverts; + let renderDatas = _impl._renderDatas; + let renderData = renderDatas[_impl._dataOffset]; + + let maxVertsCount = renderData.vertexCount + cverts; if (maxVertsCount > MAX_VERTEX || maxVertsCount * 3 > MAX_INDICE) { - renderData = graphics.requestRenderData(); + ++_impl._dataOffset; + maxVertsCount = cverts; + + if (_impl._dataOffset < renderDatas.length) { + renderData = renderDatas[_impl._dataOffset]; + } + else { + renderData = graphics.requestRenderData(); + renderDatas[_impl._dataOffset] = renderData; + } } + + if (maxVertsCount > renderData.dataLength) { + renderData.dataLength = maxVertsCount; + } + return renderData; }, stroke (graphics) { - if (graphics._renderDatas.length === 0) { - graphics._renderDatas.push(graphics.requestRenderData()); + let renderDatas = graphics._impl._renderDatas; + if (renderDatas.length === 0) { + renderDatas.push(graphics.requestRenderData()); } _curColor = graphics._strokeColor._val; - this._flattenPaths(graphics); + this._flattenPaths(graphics._impl); this._expandStroke(graphics); - graphics._updatePathOffset = true; + graphics._impl._updatePathOffset = true; }, fill (graphics) { - if (graphics._renderDatas.length === 0) { - graphics._renderDatas.push(graphics.requestRenderData()); + let renderDatas = graphics._impl._renderDatas; + if (renderDatas.length === 0) { + renderDatas.push(graphics.requestRenderData()); } _curColor = graphics._fillColor._val; this._expandFill(graphics); - this._updatePathOffset = true; + graphics._impl._updatePathOffset = true; }, _expandStroke (graphics) { @@ -161,16 +184,18 @@ let graphicsAssembler = js.addon({ lineCap = graphics.lineCap, lineJoin = graphics.lineJoin, miterLimit = graphics.miterLimit; + + _impl = graphics._impl; - let ncap = curveDivs(w, PI, graphics._tessTol); + let ncap = curveDivs(w, PI, _impl._tessTol); - this._calculateJoins(graphics, w, lineJoin, miterLimit); + this._calculateJoins(_impl, w, lineJoin, miterLimit); - let paths = graphics._paths; + let paths = _impl._paths; // Calculate max vertex usage. let cverts = 0; - for (let i = graphics._pathOffset, l = graphics._pathLength; i < l; i++) { + for (let i = _impl._pathOffset, l = _impl._pathLength; i < l; i++) { let path = paths[i]; let pointsLength = path.points.length; @@ -186,16 +211,16 @@ let graphicsAssembler = js.addon({ } } } - + let renderData = _renderData = this.genRenderData(graphics, cverts), data = renderData._data, indicesBuffer = renderData._indices; - for (let i = graphics._pathOffset, l = graphics._pathLength; i < l; i++) { + for (let i = _impl._pathOffset, l = _impl._pathLength; i < l; i++) { let path = paths[i]; let pts = path.points; let pointsLength = pts.length; - let offset = data.length; + let offset = renderData.vertexCount; let p0, p1; let start, end, loop; @@ -268,25 +293,27 @@ let graphicsAssembler = js.addon({ // stroke indices let indicesOffset = indicesBuffer.length; - for (let start = offset+2, end = data.length; start < end; start++) { + for (let start = offset+2, end = renderData.vertexCount; start < end; start++) { indicesBuffer[indicesOffset++] = start - 2; indicesBuffer[indicesOffset++] = start - 1; indicesBuffer[indicesOffset++] = start; } } - renderData.vertexCount = data.length; renderData.indiceCount = indicesBuffer.length; _renderData = null; + _impl = null; }, _expandFill (graphics) { - let paths = graphics._paths; + _impl = graphics._impl; + + let paths = _impl._paths; // Calculate max vertex usage. let cverts = 0; - for (let i = graphics._pathOffset, l = graphics._pathLength; i < l; i++) { + for (let i = _impl._pathOffset, l = _impl._pathLength; i < l; i++) { let path = paths[i]; let pointsLength = path.points.length; @@ -297,7 +324,7 @@ let graphicsAssembler = js.addon({ data = renderData._data, indicesBuffer = renderData._indices; - for (let i = graphics._pathOffset, l = graphics._pathLength; i < l; i++) { + for (let i = _impl._pathOffset, l = _impl._pathLength; i < l; i++) { let path = paths[i]; let pts = path.points; let pointsLength = pts.length; @@ -307,7 +334,7 @@ let graphicsAssembler = js.addon({ } // Calculate shape vertices. - let offset = data.length; + let offset = renderData.vertexCount; for (let j = 0; j < pointsLength; ++j) { this._vset(pts[j].x, pts[j].y); @@ -317,7 +344,7 @@ let graphicsAssembler = js.addon({ if (path.complex) { let earcutData = []; - for (let j = offset, end = data.length; j < end; j++) { + for (let j = offset, end = renderData.vertexCount; j < end; j++) { earcutData.push(data[j].x); earcutData.push(data[j].y); } @@ -334,7 +361,7 @@ let graphicsAssembler = js.addon({ } else { let first = offset; - for (let start = offset+2, end = data.length; start < end; start++) { + for (let start = offset+2, end = renderData.vertexCount; start < end; start++) { indicesBuffer[indicesOffset++] = first; indicesBuffer[indicesOffset++] = start - 1; indicesBuffer[indicesOffset++] = start; @@ -342,13 +369,13 @@ let graphicsAssembler = js.addon({ } } - renderData.vertexCount = data.length; renderData.indiceCount = indicesBuffer.length; _renderData = null; + _impl = null; }, - _calculateJoins (graphics, w, lineJoin, miterLimit) { + _calculateJoins (impl, w, lineJoin, miterLimit) { let iw = 0.0; if (w > 0.0) { @@ -356,8 +383,8 @@ let graphicsAssembler = js.addon({ } // Calculate which joins needs extra vertices to append, and gather vertex count. - let paths = graphics._paths; - for (let i = graphics._pathOffset, l = graphics._pathLength; i < l; i++) { + let paths = impl._paths; + for (let i = impl._pathOffset, l = impl._pathLength; i < l; i++) { let path = paths[i]; let pts = path.points; @@ -420,9 +447,9 @@ let graphicsAssembler = js.addon({ } }, - _flattenPaths (graphics) { - let paths = graphics._paths; - for (let i = graphics._pathOffset, l = graphics._pathLength; i < l; i++) { + _flattenPaths (impl) { + let paths = impl._paths; + for (let i = impl._pathOffset, l = impl._pathLength; i < l; i++) { let path = paths[i]; let pts = path.points; @@ -613,13 +640,13 @@ let graphicsAssembler = js.addon({ _vset (x, y) { let data = _renderData._data; - - let offset = data.length; - _renderData.dataLength = offset + 1; + let offset = _renderData.vertexCount; data[offset].x = x; data[offset].y = y; data[offset].color = _curColor; + + _renderData.vertexCount ++; } }, assembler); diff --git a/cocos2d/core/renderer/assemblers/mask-assembler.js b/cocos2d/core/renderer/assemblers/mask-assembler.js index 56365d61e1..c9251e19b5 100644 --- a/cocos2d/core/renderer/assemblers/mask-assembler.js +++ b/cocos2d/core/renderer/assemblers/mask-assembler.js @@ -149,7 +149,7 @@ let maskEndAssembler = js.addon({ datas = mask._renderDatas; } else { - datas = mask._graphics._renderDatas; + datas = mask._graphics._impl._renderDatas; } let material = mask.getMaterial(); for (let i = 0; i < datas.length; i++) { From 665b72690e89eabdc7f631dfca345873d0ff4c09 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Mon, 2 Apr 2018 11:11:31 +0800 Subject: [PATCH 09/35] add canvas pool for label --- cocos2d/core/components/CCLabel.js | 47 +++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index 73f00f1310..7b05dcffe3 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -147,6 +147,31 @@ function debounce (func, wait, immediate) { }; } +let _canvasPool = { + pool: [], + get () { + let data = this.pool.pop(); + + if (!data) { + let canvas = document.createElement("canvas"); + let context = canvas.getContext("2d"); + data = { + _canvas: canvas, + _context: context + } + } + + data.width = data.height = 1; + return data; + }, + put (canvas) { + if (this.pool.length >= 32) { + return; + } + this.pool.push(canvas); + } +}; + /** * !#en The Label Component. @@ -448,6 +473,17 @@ var Label = cc.Class({ this._activateMaterial(); }, + onDestroy () { + this._resetAssemblerData(); + }, + + _resetAssemblerData () { + if (this._assemblerData) { + _canvasPool.put(this._assemblerData); + } + this._assemblerData = null; + }, + _updateAssembler () { let assembler = Label._assembler.getAssembler(this); @@ -465,7 +501,7 @@ var Label = cc.Class({ _activateMaterial: function () { if (this._material) return; - this._assemblerData = null; + this._resetAssemblerData(); let material; let font = this.font; @@ -481,15 +517,10 @@ var Label = cc.Class({ material.texture = this._texture = spriteFrame._texture; } else { - let assemblerData = this._assemblerData = {}; - - assemblerData._canvas = document.createElement("canvas"); - // create canvas with size so that the default texture impl can be created and don't need activate material again - assemblerData._canvas.width = assemblerData._canvas.height = 1; - assemblerData._context = assemblerData._canvas.getContext("2d"); + this._assemblerData = _canvasPool.get(); this._texture = new cc.Texture2D(); - this._texture.initWithElement(assemblerData._canvas); + this._texture.initWithElement(this._assemblerData._canvas); this._texture.handleLoadedTexture(); material = new SpriteMaterial(); From 687f9a77dcbe76fde6877f5e0ee4fd647e6cf5a0 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Mon, 2 Apr 2018 13:50:13 +0800 Subject: [PATCH 10/35] add dropColorizedImage for canvas utils --- cocos2d/core/renderer/canvas/renderers/label/ttf.js | 2 +- cocos2d/core/renderer/canvas/renderers/utils.js | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/renderer/canvas/renderers/label/ttf.js b/cocos2d/core/renderer/canvas/renderers/label/ttf.js index 6f2d89ac28..9926781a72 100644 --- a/cocos2d/core/renderer/canvas/renderers/label/ttf.js +++ b/cocos2d/core/renderer/canvas/renderers/label/ttf.js @@ -28,7 +28,7 @@ module.exports = js.addon({ _updateTexture (comp) { ttfUtils._updateTexture(comp); - utils.dropImage(comp._texture, comp.node.color); + utils.dropColorizedImage(comp._texture, comp.node.color); }, draw (ctx, comp) { diff --git a/cocos2d/core/renderer/canvas/renderers/utils.js b/cocos2d/core/renderer/canvas/renderers/utils.js index 8f0867c4d9..c545b94529 100644 --- a/cocos2d/core/renderer/canvas/renderers/utils.js +++ b/cocos2d/core/renderer/canvas/renderers/utils.js @@ -97,8 +97,7 @@ let canvasMgr = { } }, - dropImage (texture, color) { - let key = texture.url + (color._val & 0x00ffffff); + dropImage (key) { if (this.canvasMap[key]) { delete this.canvasMap[key]; } @@ -158,7 +157,8 @@ module.exports = { return cache; }, - dropImage (texture, color) { - canvasMgr.dropImage(texture, color); + dropColorizedImage (texture, color) { + let key = texture.url + (color._val & 0x00ffffff); + canvasMgr.dropImage(key); } }; \ No newline at end of file From ac3d195f6d352dc6bb5289a6e47b120d0d21f1f5 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Mon, 2 Apr 2018 14:40:30 +0800 Subject: [PATCH 11/35] support canvas graphics --- cocos2d/core/graphics/graphics.js | 6 + .../canvas/renderers/graphics/impl.js | 131 ++++++++++++++++++ .../canvas/renderers/graphics/index.js | 65 +++++++++ .../core/renderer/canvas/renderers/index.js | 8 +- 4 files changed, 207 insertions(+), 3 deletions(-) create mode 100644 cocos2d/core/renderer/canvas/renderers/graphics/impl.js create mode 100644 cocos2d/core/renderer/canvas/renderers/graphics/index.js diff --git a/cocos2d/core/graphics/graphics.js b/cocos2d/core/graphics/graphics.js index 487d3367a7..f4c893e19b 100644 --- a/cocos2d/core/graphics/graphics.js +++ b/cocos2d/core/graphics/graphics.js @@ -72,6 +72,7 @@ let Graphics = cc.Class({ }, set (value) { this._lineWidth = value; + this._impl.lineWidth = value; } }, @@ -89,6 +90,7 @@ let Graphics = cc.Class({ }, set (value) { this._lineJoin = value; + this._impl.lineJoin = value; }, type: LineJoin }, @@ -107,6 +109,7 @@ let Graphics = cc.Class({ }, set (value) { this._lineCap = value; + this._impl.lineCap = value; }, type: LineCap }, @@ -125,6 +128,7 @@ let Graphics = cc.Class({ }, set (value) { this._strokeColor = cc.color(value); + this._impl.strokeColor = value; } }, @@ -142,6 +146,7 @@ let Graphics = cc.Class({ }, set (value) { this._fillColor = cc.color(value); + this._impl.fillColor = value; } }, @@ -159,6 +164,7 @@ let Graphics = cc.Class({ }, set (value) { this._miterLimit = value; + this._impl.miterLimit = value; } } }, diff --git a/cocos2d/core/renderer/canvas/renderers/graphics/impl.js b/cocos2d/core/renderer/canvas/renderers/graphics/impl.js new file mode 100644 index 0000000000..4e45b6e648 --- /dev/null +++ b/cocos2d/core/renderer/canvas/renderers/graphics/impl.js @@ -0,0 +1,131 @@ + +const Helper = require('../../../../graphics/helper'); +const Types = require('../../../../graphics/types'); +const PointFlags = Types.PointFlags; +const LineJoin = Types.LineJoin; +const LineCap = Types.LineCap; + +class Impl { + constructor () { + this.cmds = []; + + this.style = { + strokeStyle: 'black', + fillStyle: 'white', + lineCap: 'butt', + lineJoin: 'miter', + miterLimit: 10 + }; + } + + set strokeColor (v) { + var strokeStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')'; + this.cmds.push(['strokeStyle', strokeStyle]); + this.style.strokeStyle = strokeStyle; + } + + set fillColor (v) { + var fillStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')'; + this.cmds.push(['fillStyle', fillStyle]); + this.style.fillStyle = fillStyle; + } + + set lineWidth (v) { + this.cmds.push(['lineWidth', v]); + this.style.lineWidth = v; + } + + set lineCap (v) { + var lineCap = 'butt'; + if (v === LineCap.BUTT) { + lineCap = 'butt'; + } + else if (v === LineCap.ROUND) { + lineCap = 'round'; + } + else if (v === LineCap.SQUARE) { + lineCap = 'square'; + } + this.cmds.push(['lineCap', lineCap]); + this.style.lineCap = lineCap; + } + + set lineJoin (v) { + var lineJoin = 'bevel'; + if (v === LineJoin.BEVEL) { + lineJoin = 'bevel'; + } + else if (v === LineJoin.ROUND) { + lineJoin = 'round'; + } + else if (v === LineJoin.MITER) { + lineJoin = 'miter'; + } + + this.cmds.push(['lineJoin', lineJoin]); + this.style.lineJoin = lineJoin; + } + + set miterLimit (v) { + this.cmds.push(['miterLimit', v]); + this.style.miterLimit = v; + } + + moveTo (x, y) { + this.cmds.push(['moveTo', [x, y]]); + } + + lineTo (x, y) { + this.cmds.push(['lineTo', [x, y]]); + } + + bezierCurveTo (c1x, c1y, c2x, c2y, x, y) { + this.cmds.push(['bezierCurveTo', [c1x, c1y, c2x, c2y, x, y]]); + } + + quadraticCurveTo (cx, cy, x, y) { + this.cmds.push(['quadraticCurveTo', [cx, cy, x, y]]); + } + + arc (cx, cy, r, startAngle, endAngle, counterclockwise) { + Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); + } + + ellipse (cx, cy, rx, ry) { + Helper.ellipse(this, cx, cy, rx, ry); + } + + circle (cx, cy, r) { + Helper.ellipse(this, cx, cy, r, r); + } + + rect (x, y, w, h) { + this.moveTo(x, y); + this.lineTo(x, y + h); + this.lineTo(x + w, y + h); + this.lineTo(x + w, y); + this.close(); + } + + roundRect (x, y, w, h, r) { + Helper.roundRect(this, x, y, w, h, r); + } + + clear (comp, clean) { + this.cmds.length = 0; + } + + close () { + this.cmds.push(['closePath', []]); + } + + stroke () { + this.cmds.push(['stroke', []]); + } + + fill () { + this.cmds.push(['fill', []]); + } +} + +module.exports = Impl; diff --git a/cocos2d/core/renderer/canvas/renderers/graphics/index.js b/cocos2d/core/renderer/canvas/renderers/graphics/index.js new file mode 100644 index 0000000000..5899989b94 --- /dev/null +++ b/cocos2d/core/renderer/canvas/renderers/graphics/index.js @@ -0,0 +1,65 @@ +const Impl = require('./impl'); + +module.exports = { + createImpl () { + return new Impl(); + }, + + draw (ctx, comp) { + let node = comp.node; + // Transform + let matrix = node._worldMatrix; + let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, + tx = matrix.m12, ty = matrix.m13; + ctx.transform(a, b, c, d, tx, -ty); + + ctx.save(); + ctx.scale(1, -1); + + // TODO: handle blend function + + // opacity + ctx.glphaAlpha = node.opacity / 255; + + let style = comp._impl.style; + ctx.strokeStyle = style.strokeStyle; + ctx.fillStyle = style.fillStyle; + ctx.lineWidth = style.lineWidth; + ctx.lineJoin = style.lineJoin; + ctx.miterLimit = style.miterLimit; + + let endPath = true; + let cmds = comp._impl.cmds; + for (let i = 0, l = cmds.length; i < l; i++) { + let cmd = cmds[i]; + let ctxCmd = cmd[0], args = cmd[1]; + + if (ctxCmd === 'moveTo' && endPath) { + ctx.beginPath(); + endPath = false; + } + else if (ctxCmd === 'fill' || ctxCmd === 'stroke' || ctxCmd === 'fillRect') { + endPath = true; + } + + if (typeof ctx[ctxCmd] === 'function') { + ctx[ctxCmd].apply(ctx, args); + } + else { + ctx[ctxCmd] = args; + } + } + + ctx.restore(); + + return 1; + }, + + stroke (comp) { + comp._impl.stroke(); + }, + + fill (comp) { + comp._impl.fill(); + } +} diff --git a/cocos2d/core/renderer/canvas/renderers/index.js b/cocos2d/core/renderer/canvas/renderers/index.js index 61bd17a42b..ec75cc9b5c 100644 --- a/cocos2d/core/renderer/canvas/renderers/index.js +++ b/cocos2d/core/renderer/canvas/renderers/index.js @@ -30,14 +30,15 @@ let Label = require('../../../components/CCLabel'); let Mask = require('../../../components/CCMask'); let RichText = require('../../../components/CCRichText'); // the following should be placed into their own module folder -// let Graphics = require('../../../graphics/graphics'); +let Graphics = require('../../../graphics/graphics'); // let ParticleSystem = require('../../../../particle/CCParticleSystem'); // let TiledLayer = require('../../../../tilemap/CCTiledLayer'); // let Skeleton = require('../../../../../extensions/spine/Skeleton'); // let Armature = require('../../../../../extensions/dragonbones/ArmatureDisplay'); -let spriteRenderer = require('./sprite/'); -let labelRenderer = require('./label/'); +let spriteRenderer = require('./sprite'); +let labelRenderer = require('./label'); +let graphicsRenderer = require('./graphics'); let map = {}; let postMap = {}; @@ -56,6 +57,7 @@ addRenderer(Sprite, spriteRenderer); addRenderer(Label, labelRenderer); addRenderer(Mask, null); addRenderer(RichText, null); +addRenderer(Graphics, graphicsRenderer); module.exports = { map, From 42291c0a9b11391cbcaade1c099a6a47991362d5 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Tue, 3 Apr 2018 10:19:17 +0800 Subject: [PATCH 12/35] fixed tiledmap anchor point --- cocos2d/tilemap/CCTiledMap.js | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/cocos2d/tilemap/CCTiledMap.js b/cocos2d/tilemap/CCTiledMap.js index c291e26940..853ecc4814 100644 --- a/cocos2d/tilemap/CCTiledMap.js +++ b/cocos2d/tilemap/CCTiledMap.js @@ -428,6 +428,12 @@ let TiledMap = cc.Class({ // refresh layer entities this._applyFile(); } + + this.node.on('anchor-changed', this._syncAnchorPoint, this); + }, + + onDisable () { + this.node.off('anchor-changed', this._syncAnchorPoint, this); }, _applyFile () { @@ -459,6 +465,13 @@ let TiledMap = cc.Class({ this._buildWithMapInfo(mapInfo); } }, + + _syncAnchorPoint () { + let anchor = this.node.getAnchorPoint(); + for (let i = 0, l = this._layers.length; i < l; i++) { + this._layers[i].node.setAnchorPoint(anchor); + } + }, _buildWithMapInfo (mapInfo) { this._mapSize = mapInfo.getMapSize(); @@ -491,7 +504,6 @@ let TiledMap = cc.Class({ if (!child) { child = new cc.Node(); child.name = name; - child.setAnchorPoint(0.5, 0.5); node.addChild(child); } @@ -509,8 +521,8 @@ let TiledMap = cc.Class({ layerInfo.ownTiles = false; // update content size with the max size - this.width = Math.max(this.width, child.width); - this.height = Math.max(this.height, child.height); + this.node.width = Math.max(this.node.width, child.width); + this.node.height = Math.max(this.node.height, child.height); layers.push(layer); } @@ -525,17 +537,8 @@ let TiledMap = cc.Class({ } } } - }, - _parseLayer (layerInfo, mapInfo) { - let node = new cc.Node(); - let layer = node.addComponent(cc.TiledLayer); - let tileset = this._tilesetForLayer(layerInfo, mapInfo); - // tell the layerinfo to release the ownership of the tiles map. - layer.init(tileset, layerInfo, mapInfo); - layerInfo.ownTiles = false; - - return node; + this._syncAnchorPoint(); }, _tilesetForLayer (layerInfo, mapInfo) { From 681ac8ac623edff4fa8a1ddd782af970c77c762f Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Tue, 3 Apr 2018 10:19:42 +0800 Subject: [PATCH 13/35] fixed camera containsNode --- cocos2d/core/camera/CCCamera.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/camera/CCCamera.js b/cocos2d/core/camera/CCCamera.js index dc677b8045..e1498b9f2a 100644 --- a/cocos2d/core/camera/CCCamera.js +++ b/cocos2d/core/camera/CCCamera.js @@ -417,7 +417,7 @@ let Camera = cc.Class({ * @return {Boolean} */ containsNode (node) { - return node._cullingMask === this.cullingMask; + return node._cullingMask & this.cullingMask; }, /** From d0b676406cf698245fc098d3bb1d8b571f245a43 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Tue, 3 Apr 2018 11:40:28 +0800 Subject: [PATCH 14/35] fixed anchor point calc in tmx-layer-assembler --- cocos2d/tilemap/tmx-layer-assembler.js | 29 +++++++++++++------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/cocos2d/tilemap/tmx-layer-assembler.js b/cocos2d/tilemap/tmx-layer-assembler.js index 9f447e766d..3ab5727c31 100644 --- a/cocos2d/tilemap/tmx-layer-assembler.js +++ b/cocos2d/tilemap/tmx-layer-assembler.js @@ -41,6 +41,7 @@ const mat4 = math.mat4; const vec3 = math.vec3; let _mat4_temp = mat4.create(); +let _mat4_temp2 = mat4.create(); let _vec3_temp = vec3.create(); let tmxAssembler = js.addon({ @@ -105,15 +106,18 @@ let tmxAssembler = js.addon({ if (!tiles || !comp._tileset) { return; } - - node._updateWorldMatrix(); - let matrix = node._worldMatrix; - let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; - + let appx = node._anchorPoint.x * node._contentSize.width, appy = node._anchorPoint.y * node._contentSize.height; + node.getWorldMatrix(_mat4_temp2); + vec3.set(_vec3_temp, -appx, -appy, 0); + mat4.translate(_mat4_temp2, _mat4_temp2, _vec3_temp); + + let matrix = _mat4_temp2; + let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, + tx = matrix.m12, ty = matrix.m13; + let maptw = comp._mapTileSize.width, mapth = comp._mapTileSize.height, tilew = comp._tileset._tileSize.width, @@ -155,7 +159,7 @@ let tmxAssembler = js.addon({ } if (layerOrientation === Orientation.ORTHO) { - cc.vmath.mat4.invert(_mat4_temp, matrix); + cc.vmath.mat4.invert(_mat4_temp, _mat4_temp); let rect = cc.visibleRect; let a = _mat4_temp.m00, b = _mat4_temp.m01, c = _mat4_temp.m04, d = _mat4_temp.m05, @@ -249,16 +253,13 @@ let tmxAssembler = js.addon({ // transform a2 = a; b2 = b; c2 = c; d2 = d; tx2 = tx; ty2 = ty; tiledNode._updateLocalMatrix(); - cc.vmath.mat4.copy(_mat4_temp, tiledNode._mat4_temp); - _vec3_temp.x = -left; _vec3_temp.y = -bottom; _vec3_temp.z = 0; - cc.vmath.mat4.translate(_mat4_temp, _mat4_temp, _vec3_temp); - cc.vmath.mat4.multiply(_mat4_temp, matrix, _mat4_temp); + mat4.copy(_mat4_temp, tiledNode._mat4_temp); + vec3.set(_vec3_temp, -left, -bottom, 0); + mat4.translate(_mat4_temp, _mat4_temp, _vec3_temp); + mat4.multiply(_mat4_temp, matrix, _mat4_temp); a = _mat4_temp.m00; b = _mat4_temp.m01; c = _mat4_temp.m04; d = _mat4_temp.m05; tx = _mat4_temp.m12; ty = _mat4_temp.m13; } - - left -= appx; - bottom -= appy; right = left + tilew; top = bottom + tileh; From 3254de091f17dbf60f2c4144d2af1423a8bff65f Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Tue, 3 Apr 2018 16:01:15 +0800 Subject: [PATCH 15/35] fixed tmx-layer-assembler --- cocos2d/tilemap/tmx-layer-assembler.js | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/cocos2d/tilemap/tmx-layer-assembler.js b/cocos2d/tilemap/tmx-layer-assembler.js index 3ab5727c31..83af5812c4 100644 --- a/cocos2d/tilemap/tmx-layer-assembler.js +++ b/cocos2d/tilemap/tmx-layer-assembler.js @@ -110,13 +110,12 @@ let tmxAssembler = js.addon({ let appx = node._anchorPoint.x * node._contentSize.width, appy = node._anchorPoint.y * node._contentSize.height; - node.getWorldMatrix(_mat4_temp2); + node.getWorldMatrix(_mat4_temp); vec3.set(_vec3_temp, -appx, -appy, 0); - mat4.translate(_mat4_temp2, _mat4_temp2, _vec3_temp); + mat4.translate(_mat4_temp, _mat4_temp, _vec3_temp); - let matrix = _mat4_temp2; - let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; + let a = _mat4_temp.m00, b = _mat4_temp.m01, c = _mat4_temp.m04, d = _mat4_temp.m05, + tx = _mat4_temp.m12, ty = _mat4_temp.m13; let maptw = comp._mapTileSize.width, mapth = comp._mapTileSize.height, @@ -148,8 +147,8 @@ let tmxAssembler = js.addon({ if (enabledCulling) { let camera = cc.Camera.findCamera(comp.node); if (camera) { - camera.getWorldToCameraMatrix(_mat4_temp); - mat4.mul(_mat4_temp, matrix, _mat4_temp); + camera.getWorldToCameraMatrix(_mat4_temp2); + mat4.mul(_mat4_temp, _mat4_temp, _mat4_temp2); cullingA = _mat4_temp.m00; cullingD = _mat4_temp.m05; cullingMapx = ox * cullingA + oy * _mat4_temp.m04 + _mat4_temp.m12; @@ -159,7 +158,7 @@ let tmxAssembler = js.addon({ } if (layerOrientation === Orientation.ORTHO) { - cc.vmath.mat4.invert(_mat4_temp, _mat4_temp); + mat4.invert(_mat4_temp, _mat4_temp); let rect = cc.visibleRect; let a = _mat4_temp.m00, b = _mat4_temp.m01, c = _mat4_temp.m04, d = _mat4_temp.m05, @@ -256,7 +255,7 @@ let tmxAssembler = js.addon({ mat4.copy(_mat4_temp, tiledNode._mat4_temp); vec3.set(_vec3_temp, -left, -bottom, 0); mat4.translate(_mat4_temp, _mat4_temp, _vec3_temp); - mat4.multiply(_mat4_temp, matrix, _mat4_temp); + mat4.multiply(_mat4_temp, node._worldMatrix, _mat4_temp); a = _mat4_temp.m00; b = _mat4_temp.m01; c = _mat4_temp.m04; d = _mat4_temp.m05; tx = _mat4_temp.m12; ty = _mat4_temp.m13; } From ebef9795a035e7237ae8c02e328f634cf1ace2a5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 3 Apr 2018 20:55:02 +0800 Subject: [PATCH 16/35] Merge runtime builtin scripts. --- cocos2d/core/platform/instantiate-jit.js | 9 +- gulp/tasks/engine.js | 1 + jsb/builtin/.babelrc | 2 +- jsb/builtin/Blob.js | 229 +++++++++++++++++++ jsb/builtin/base64/base64.min.js | 1 + jsb/builtin/index.js | 10 +- jsb/builtin/jsb-adapter/Audio.js | 1 + jsb/builtin/jsb-adapter/DOMRect.js | 39 ++++ jsb/builtin/jsb-adapter/Element.js | 33 ++- jsb/builtin/jsb-adapter/FontFaceSet.js | 1 + jsb/builtin/jsb-adapter/HTMLAudioElement.js | 1 + jsb/builtin/jsb-adapter/HTMLCanvasElement.js | 18 ++ jsb/builtin/jsb-adapter/HTMLElement.js | 27 +-- jsb/builtin/jsb-adapter/HTMLImageElement.js | 13 ++ jsb/builtin/jsb-adapter/HTMLMediaElement.js | 1 + jsb/builtin/jsb-adapter/Image.js | 1 + jsb/builtin/jsb-adapter/ImageData.js | 1 + jsb/builtin/jsb-adapter/Node.js | 1 + jsb/builtin/jsb-adapter/document.js | 11 +- jsb/builtin/jsb-adapter/location.js | 2 + jsb/builtin/jsb-adapter/navigator.js | 5 +- jsb/builtin/jsb-adapter/window.js | 47 +++- jsb/builtin/jsb_opengl.js | 69 ++++-- jsb/builtin/jsb_opengl_constants.js | 2 + jsb/builtin/package.json | 8 + 25 files changed, 470 insertions(+), 63 deletions(-) create mode 100644 jsb/builtin/Blob.js create mode 100644 jsb/builtin/base64/base64.min.js create mode 100644 jsb/builtin/jsb-adapter/DOMRect.js create mode 100644 jsb/builtin/package.json diff --git a/cocos2d/core/platform/instantiate-jit.js b/cocos2d/core/platform/instantiate-jit.js index 744b5ebf59..4b1cdcf2ee 100644 --- a/cocos2d/core/platform/instantiate-jit.js +++ b/cocos2d/core/platform/instantiate-jit.js @@ -162,7 +162,14 @@ function equalsToDefault (def, value) { (def.constructor === Object && value.constructor === Object) ) { try { - return JSON.stringify(def) === JSON.stringify(value); + if (CC_JSB) { + //FIXME: JSON.stringify will take lots of time for compare object at runtime on JSB. + // We need to consider a new way for checking whether two objects are equal. + return false; + } + else { + return JSON.stringify(def) === JSON.stringify(value); + } } catch (e) { } diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index e93ad6f97b..d4f07876b7 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -41,6 +41,7 @@ const Optimizejs = require('gulp-optimize-js'); var jsbSkipModules = [ '../../cocos2d/audio/CCAudio', // '../../external/box2d/box2d.js', + // '../../external/chipmunk/chipmunk.js' ]; var aliasifyConfig = { replacements: { diff --git a/jsb/builtin/.babelrc b/jsb/builtin/.babelrc index 73348e7480..e4d79ac56c 100644 --- a/jsb/builtin/.babelrc +++ b/jsb/builtin/.babelrc @@ -1,3 +1,3 @@ { - "presets":["es2015"] + "presets":["env"] } \ No newline at end of file diff --git a/jsb/builtin/Blob.js b/jsb/builtin/Blob.js new file mode 100644 index 0000000000..d6d6a4a167 --- /dev/null +++ b/jsb/builtin/Blob.js @@ -0,0 +1,229 @@ +/* Blob.js + * A Blob implementation. + * 2017-11-15 + * + * By Eli Grey, http://eligrey.com + * By Devin Samarin, https://github.com/dsamarin + * License: MIT + * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md + */ + +/*global self, unescape */ +/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true, + plusplus: true */ + +/*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */ + +(function(global) { +(function (factory) { + if (typeof define === "function" && define.amd) { + // AMD. Register as an anonymous module. + define(["exports"], factory); + } else if (typeof exports === "object" && typeof exports.nodeName !== "string") { + // CommonJS + factory(exports); + } else { + // Browser globals + factory(global); + } +})(function (exports) { + "use strict"; + + exports.URL = global.URL || global.webkitURL; + + if (global.Blob && global.URL) { + try { + new Blob; + return; + } catch (e) {} + } + + // Internally we use a BlobBuilder implementation to base Blob off of + // in order to support older browsers that only have BlobBuilder + var BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MozBlobBuilder || (function() { + var + get_class = function(object) { + return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1]; + } + , FakeBlobBuilder = function BlobBuilder() { + this.data = []; + } + , FakeBlob = function Blob(data, type, encoding) { + this.data = data; + this.size = data.length; + this.type = type; + this.encoding = encoding; + } + , FBB_proto = FakeBlobBuilder.prototype + , FB_proto = FakeBlob.prototype + , FileReaderSync = global.FileReaderSync + , FileException = function(type) { + this.code = this[this.name = type]; + } + , file_ex_codes = ( + "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR " + + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR" + ).split(" ") + , file_ex_code = file_ex_codes.length + , real_URL = global.URL || global.webkitURL || exports + , real_create_object_URL = real_URL.createObjectURL + , real_revoke_object_URL = real_URL.revokeObjectURL + , URL = real_URL + , btoa = global.btoa + , atob = global.atob + + , ArrayBuffer = global.ArrayBuffer + , Uint8Array = global.Uint8Array + + , origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/ + ; + FakeBlob.fake = FB_proto.fake = true; + while (file_ex_code--) { + FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1; + } + // Polyfill URL + if (!real_URL.createObjectURL) { + URL = exports.URL = function(uri) { + var + uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a") + , uri_origin + ; + uri_info.href = uri; + if (!("origin" in uri_info)) { + if (uri_info.protocol.toLowerCase() === "data:") { + uri_info.origin = null; + } else { + uri_origin = uri.match(origin); + uri_info.origin = uri_origin && uri_origin[1]; + } + } + return uri_info; + }; + } + URL.createObjectURL = function(blob) { + var + type = blob.type + , data_URI_header + ; + if (type === null) { + type = "application/octet-stream"; + } + if (blob instanceof FakeBlob) { + data_URI_header = "data:" + type; + if (blob.encoding === "base64") { + return data_URI_header + ";base64," + blob.data; + } else if (blob.encoding === "URI") { + return data_URI_header + "," + decodeURIComponent(blob.data); + } if (btoa) { + return data_URI_header + ";base64," + btoa(blob.data); + } else { + return data_URI_header + "," + encodeURIComponent(blob.data); + } + } else if (real_create_object_URL) { + return real_create_object_URL.call(real_URL, blob); + } + }; + URL.revokeObjectURL = function(object_URL) { + if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) { + real_revoke_object_URL.call(real_URL, object_URL); + } + }; + FBB_proto.append = function(data/*, endings*/) { + var bb = this.data; + // decode data to a binary string + if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) { + var + str = "" + , buf = new Uint8Array(data) + , i = 0 + , buf_len = buf.length + ; + for (; i < buf_len; i++) { + str += String.fromCharCode(buf[i]); + } + bb.push(str); + } else if (get_class(data) === "Blob" || get_class(data) === "File") { + if (FileReaderSync) { + var fr = new FileReaderSync; + bb.push(fr.readAsBinaryString(data)); + } else { + // async FileReader won't work as BlobBuilder is sync + throw new FileException("NOT_READABLE_ERR"); + } + } else if (data instanceof FakeBlob) { + if (data.encoding === "base64" && atob) { + bb.push(atob(data.data)); + } else if (data.encoding === "URI") { + bb.push(decodeURIComponent(data.data)); + } else if (data.encoding === "raw") { + bb.push(data.data); + } + } else { + if (typeof data !== "string") { + data += ""; // convert unsupported types to strings + } + // decode UTF-16 to binary string + bb.push(unescape(encodeURIComponent(data))); + } + }; + FBB_proto.getBlob = function(type) { + if (!arguments.length) { + type = null; + } + return new FakeBlob(this.data.join(""), type, "raw"); + }; + FBB_proto.toString = function() { + return "[object BlobBuilder]"; + }; + FB_proto.slice = function(start, end, type) { + var args = arguments.length; + if (args < 3) { + type = null; + } + return new FakeBlob( + this.data.slice(start, args > 1 ? end : this.data.length) + , type + , this.encoding + ); + }; + FB_proto.toString = function() { + return "[object Blob]"; + }; + FB_proto.close = function() { + this.size = 0; + delete this.data; + }; + return FakeBlobBuilder; + }()); + + exports.Blob = function(blobParts, options) { + var type = options ? (options.type || "") : ""; + var builder = new BlobBuilder(); + if (blobParts) { + for (var i = 0, len = blobParts.length; i < len; i++) { + if (Uint8Array && blobParts[i] instanceof Uint8Array) { + builder.append(blobParts[i].buffer); + } + else { + builder.append(blobParts[i]); + } + } + } + var blob = builder.getBlob(type); + if (!blob.slice && blob.webkitSlice) { + blob.slice = blob.webkitSlice; + } + return blob; + }; + + var getPrototypeOf = Object.getPrototypeOf || function(object) { + return object.__proto__; + }; + exports.Blob.prototype = getPrototypeOf(new exports.Blob()); +}); +})( + typeof self !== "undefined" && self || + typeof window !== "undefined" && window || + typeof global !== "undefined" && global || + this.content || this +); diff --git a/jsb/builtin/base64/base64.min.js b/jsb/builtin/base64/base64.min.js new file mode 100644 index 0000000000..3b8a4c70a0 --- /dev/null +++ b/jsb/builtin/base64/base64.min.js @@ -0,0 +1 @@ +!function(){function e(e){this.message=e}var t="undefined"!=typeof exports?exports:"undefined"!=typeof self?self:$.global,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.prototype=new Error,e.prototype.name="InvalidCharacterError",t.btoa||(t.btoa=function(t){for(var o,n,a=String(t),i=0,f=r,c="";a.charAt(0|i)||(f="=",i%1);c+=f.charAt(63&o>>8-i%1*8)){if(n=a.charCodeAt(i+=.75),n>255)throw new e("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),t.atob||(t.atob=function(t){var o=String(t).replace(/[=]+$/,"");if(o.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,a,i=0,f=0,c="";a=o.charAt(f++);~a&&(n=i%4?64*n+a:a,i++%4)?c+=String.fromCharCode(255&n>>(-2*i&6)):0)a=r.indexOf(a);return c})}(); diff --git a/jsb/builtin/index.js b/jsb/builtin/index.js index a740fc19d4..b8da5248bc 100644 --- a/jsb/builtin/index.js +++ b/jsb/builtin/index.js @@ -22,10 +22,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - -// window.CC_JSB = true; + window.CC_JSB = true; -// console.log("CC_JSB:" + CC_JSB); window.CC_WECHATGAME = true; // Simulate wechat game API: @@ -168,6 +166,12 @@ jsb.urlRegExp = new RegExp("^(?:https?|ftp)://\\S*$", "i"); require('./jsb_prepare'); require('./jsb_opengl'); +const { btoa, atob } = require('./base64/base64.min'); +window.btoa = btoa; +window.atob = atob; +const { Blob, URL } = require('./Blob'); +window.Blob = Blob; +window.URL = URL; window.DOMParser = require('./xmldom/dom-parser').DOMParser; require('./jsb-adapter'); require('./jsb_audioengine'); diff --git a/jsb/builtin/jsb-adapter/Audio.js b/jsb/builtin/jsb-adapter/Audio.js index aef24ee545..99bc11dd30 100755 --- a/jsb/builtin/jsb-adapter/Audio.js +++ b/jsb/builtin/jsb-adapter/Audio.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + let HTMLAudioElement = require('./HTMLAudioElement'); const HAVE_NOTHING = 0 diff --git a/jsb/builtin/jsb-adapter/DOMRect.js b/jsb/builtin/jsb-adapter/DOMRect.js new file mode 100644 index 0000000000..b5720d2984 --- /dev/null +++ b/jsb/builtin/jsb-adapter/DOMRect.js @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +class DOMRect { + constructor(x, y, width, height) { + this.x = x ? x : 0; + this.y = y ? y : 0; + this.width = width ? width : 0; + this.height = height ? height : 0; + this.left = this.x; + this.top = this.y; + this.right = this.x + this.width; + this.bottom = this.y + this.height; + } +} + +module.exports = DOMRect; diff --git a/jsb/builtin/jsb-adapter/Element.js b/jsb/builtin/jsb-adapter/Element.js index 2b003c7179..794eb2fc9d 100755 --- a/jsb/builtin/jsb-adapter/Element.js +++ b/jsb/builtin/jsb-adapter/Element.js @@ -22,14 +22,35 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -let Node = require('./Node'); + +const Node = require('./Node'); +const DOMRect = require('./DOMRect'); class Element extends Node { - constructor() { - super() - this.className = '' - this.children = [] - } + constructor() { + super() + this.className = '' + this.children = [] + this.clientLeft = 0; + this.clientTop = 0; + } + + get clientWidth() { + return 0; + } + + get clientHeight() { + return 0; + } + + getBoundingClientRect() { + return new DOMRect(); + } + + // attrName is a string that names the attribute to be removed from element. + removeAttribute(attrName) { + + } } module.exports = Element; diff --git a/jsb/builtin/jsb-adapter/FontFaceSet.js b/jsb/builtin/jsb-adapter/FontFaceSet.js index 98eaf0d9ec..ae5bab8884 100644 --- a/jsb/builtin/jsb-adapter/FontFaceSet.js +++ b/jsb/builtin/jsb-adapter/FontFaceSet.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + let EventTarget = require('./EventTarget') let Event = require('./Event') diff --git a/jsb/builtin/jsb-adapter/HTMLAudioElement.js b/jsb/builtin/jsb-adapter/HTMLAudioElement.js index 90a5d5cb56..9d6b0a3542 100755 --- a/jsb/builtin/jsb-adapter/HTMLAudioElement.js +++ b/jsb/builtin/jsb-adapter/HTMLAudioElement.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + let HTMLMediaElement = require('./HTMLMediaElement'); class HTMLAudioElement extends HTMLMediaElement { diff --git a/jsb/builtin/jsb-adapter/HTMLCanvasElement.js b/jsb/builtin/jsb-adapter/HTMLCanvasElement.js index 459527b5d6..4d38c2b827 100644 --- a/jsb/builtin/jsb-adapter/HTMLCanvasElement.js +++ b/jsb/builtin/jsb-adapter/HTMLCanvasElement.js @@ -22,8 +22,10 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + const HTMLElement = require('./HTMLElement'); const ImageData = require('./ImageData'); +const DOMRect = require('./DOMRect'); class CanvasGradient { constructor() { @@ -276,6 +278,18 @@ class HTMLCanvasElement extends HTMLElement { return this._height; } + get clientWidth() { + return this._width; + } + + get clientHeight() { + return this._height; + } + + getBoundingClientRect() { + return new DOMRect(0, 0, this._width, this._height); + } + addEventListener(eventName, listener, options) { let ret = super.addEventListener(eventName, listener, options); if (ret) { @@ -317,6 +331,10 @@ ctx2DProto.drawImage = function(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, //TODO:cjh } +//TODO:cjh +ctx2DProto.bezierCurveTo = function() {} +ctx2DProto.fill = function() {} + function touchEventHandlerFactory(type) { return (touches) => { const touchEvent = new TouchEvent(type) diff --git a/jsb/builtin/jsb-adapter/HTMLElement.js b/jsb/builtin/jsb-adapter/HTMLElement.js index e721e76c6f..d6c8612e08 100755 --- a/jsb/builtin/jsb-adapter/HTMLElement.js +++ b/jsb/builtin/jsb-adapter/HTMLElement.js @@ -22,9 +22,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + const Element = require('./Element'); const { noop } = require('./util'); -const { innerWidth, innerHeight } = require('./WindowProperties'); class HTMLElement extends Element { @@ -35,8 +35,8 @@ class HTMLElement extends Element { this.className = '' this.children = [] this.style = { - width: `${innerWidth}px`, - height: `${innerHeight}px` + width: `${window.innerWidth}px`, + height: `${window.innerHeight}px` } this.insertBefore = noop @@ -53,27 +53,6 @@ class HTMLElement extends Element { return this[name] } - get clientWidth() { - const ret = parseInt(this.style.fontSize, 10) * this.innerHTML.length - - return Number.isNaN(ret) ? 0 : ret - } - - get clientHeight() { - const ret = parseInt(this.style.fontSize, 10) - - return Number.isNaN(ret) ? 0 : ret - } - - getBoundingClientRect() { - return { - top: 0, - left: 0, - width: innerWidth, - height: innerHeight - } - } - focus() { } diff --git a/jsb/builtin/jsb-adapter/HTMLImageElement.js b/jsb/builtin/jsb-adapter/HTMLImageElement.js index 35038d3d32..c04f3fb6e2 100755 --- a/jsb/builtin/jsb-adapter/HTMLImageElement.js +++ b/jsb/builtin/jsb-adapter/HTMLImageElement.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + const HTMLElement = require('./HTMLElement'); const Event = require('./Event'); @@ -77,6 +78,18 @@ class HTMLImageElement extends HTMLElement { get src() { return this._src; } + + get clientWidth() { + return this.width; + } + + get clientHeight() { + return this.height; + } + + getBoundingClientRect() { + return new DOMRect(0, 0, this.width, this.height); + } } module.exports = HTMLImageElement; diff --git a/jsb/builtin/jsb-adapter/HTMLMediaElement.js b/jsb/builtin/jsb-adapter/HTMLMediaElement.js index bb21ef4389..75f382da7d 100755 --- a/jsb/builtin/jsb-adapter/HTMLMediaElement.js +++ b/jsb/builtin/jsb-adapter/HTMLMediaElement.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + let HTMLElement = require('./HTMLElement'); class HTMLMediaElement extends HTMLElement { diff --git a/jsb/builtin/jsb-adapter/Image.js b/jsb/builtin/jsb-adapter/Image.js index 17fa029da0..366a9444e9 100755 --- a/jsb/builtin/jsb-adapter/Image.js +++ b/jsb/builtin/jsb-adapter/Image.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + let HTMLImageElement = require('./HTMLImageElement'); function Image (width, height) { diff --git a/jsb/builtin/jsb-adapter/ImageData.js b/jsb/builtin/jsb-adapter/ImageData.js index 969dac5299..7177370ba8 100644 --- a/jsb/builtin/jsb-adapter/ImageData.js +++ b/jsb/builtin/jsb-adapter/ImageData.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + class ImageData { // var imageData = new ImageData(array, width, height); diff --git a/jsb/builtin/jsb-adapter/Node.js b/jsb/builtin/jsb-adapter/Node.js index d170cf894d..dd10a99bd5 100755 --- a/jsb/builtin/jsb-adapter/Node.js +++ b/jsb/builtin/jsb-adapter/Node.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + let EventTarget = require('./EventTarget'); class Node extends EventTarget { diff --git a/jsb/builtin/jsb-adapter/document.js b/jsb/builtin/jsb-adapter/document.js index 1e490850e4..917907eaee 100755 --- a/jsb/builtin/jsb-adapter/document.js +++ b/jsb/builtin/jsb-adapter/document.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + let HTMLElement = require('./HTMLElement'); let Image = require('./Image'); let Audio = require('./Audio'); @@ -38,12 +39,18 @@ class Document extends Node { this.documentElement = window this.hidden = false this.style = {} - this.location = window.location + this.location = require('./location') this.head = new HTMLElement('head') this.body = new HTMLElement('body') this.fonts = new FontFaceSet() + + this.scripts = [] + } + + createElementNS(namespaceURI, qualifiedName, options) { + return this.createElement(qualifiedName); } createElement(tagName) { @@ -98,7 +105,7 @@ class Document extends Node { return document.head } else if (query === 'body') { return document.body - } else if (query === 'canvas' || query === 'GameCanvas') { + } else if (query === 'canvas') { return window.canvas } else if (query === `#${window.canvas.id}`) { return window.canvas diff --git a/jsb/builtin/jsb-adapter/location.js b/jsb/builtin/jsb-adapter/location.js index d55d2ff118..1c67c7c269 100755 --- a/jsb/builtin/jsb-adapter/location.js +++ b/jsb/builtin/jsb-adapter/location.js @@ -22,8 +22,10 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + const location = { href: 'game.js', + hash: '', reload() { } } diff --git a/jsb/builtin/jsb-adapter/navigator.js b/jsb/builtin/jsb-adapter/navigator.js index 985cd63eed..1179322c62 100755 --- a/jsb/builtin/jsb-adapter/navigator.js +++ b/jsb/builtin/jsb-adapter/navigator.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + let { noop } = require('./util'); // TODO 需要 wx.getSystemInfo 获取更详细信息 @@ -38,7 +39,9 @@ const navigator = { getCurrentPosition: noop, watchPosition: noop, clearWatch: noop - } + }, + + maxTouchPoints: 10 //FIXME: getting the number from OS. } module.exports = navigator; diff --git a/jsb/builtin/jsb-adapter/window.js b/jsb/builtin/jsb-adapter/window.js index 254ea5c20d..84e266c4e1 100755 --- a/jsb/builtin/jsb-adapter/window.js +++ b/jsb/builtin/jsb-adapter/window.js @@ -22,10 +22,20 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + function inject () { window.top = window.parent = window + window.ontouchstart = null; + window.ontouchmove = null; + window.ontouchend = null; + window.ontouchcancel = null; + + window.pageXOffset = window.pageYOffset = window.clientTop = window.clientLeft = 0; + + window.location = require('./location'); window.document = require('./document'); + window.Element = require('./Element'); window.HTMLElement = require('./HTMLElement'); window.HTMLCanvasElement = require('./HTMLCanvasElement'); window.HTMLImageElement = require('./HTMLImageElement'); @@ -38,17 +48,29 @@ function inject () { window.Image = require('./Image'); window.Audio = require('./Audio'); window.FileReader = require('./FileReader'); - window.location = require('./location'); window.FontFace = require('./FontFace'); window.FontFaceSet = require('./FontFaceSet'); window.EventTarget = require('./EventTarget'); window.Event = require('./Event'); window.TouchEvent = require('./TouchEvent'); - window.ontouchstart = null; - window.ontouchmove = null; - window.ontouchend = null; - window.ontouchcancel = null; + window.devicePixelRatio = 1.0; + window.screen = { + availTop: 0, + availLeft: 0, + availHeight: window.innerWidth, + availWidth: window.innerHeight, + colorDepth: 8, + pixelDepth: 8, + left: 0, + top: 0, + width: window.innerWidth, + height: window.innerHeight, + orientation: { //FIXME:cjh + type: 'portrait-primary' // portrait-primary, portrait-secondary, landscape-primary, landscape-secondary + }, + onorientationchange: function(event) {} + }; window.addEventListener = function(eventName, listener, options) { window.canvas.addEventListener(eventName, listener, options); @@ -62,6 +84,15 @@ function inject () { window.canvas.dispatchEvent(event); } + window.getComputedStyle = function(element) { + return { + position: 'absolute', + left: '0px', + top: '0px', + height: '0px' + }; + } + window._isInjected = true; } @@ -69,11 +100,5 @@ if (!window._isInjected) { inject(); } -window.canvas.getContext = function(name) { - if (name === 'webgl' || name === 'experimental-webgl') { - return window.gl; - } - return null; -}; window.localStorage = sys.localStorage; diff --git a/jsb/builtin/jsb_opengl.js b/jsb/builtin/jsb_opengl.js index ca9030084d..222cba9147 100644 --- a/jsb/builtin/jsb_opengl.js +++ b/jsb/builtin/jsb_opengl.js @@ -30,10 +30,8 @@ require('./jsb_opengl_constants'); window.gl = window.gl || {}; -gl.canvas = { - clientWidth: window.innerWidth, - clientHeight: window.innerHeight -}; +gl.drawingBufferWidth = window.innerWidth; +gl.drawingBufferHeight = window.innerHeight; // // Create functions @@ -52,7 +50,7 @@ gl.createBuffer = function() { gl.createRenderbuffer = function() { // Returns a "WebGLRenderBuffer" object - var ret = gl._createRenderuffer(); + var ret = gl._createRenderbuffer(); return { renderbuffer_id:ret}; }; @@ -164,7 +162,7 @@ gl.bindBuffer = function(target, buffer) { }; // void bindRenderbuffer(GLenum target, WebGLRenderbuffer? renderbuffer); -gl.bindRenderBuffer = function(target, buffer) { +gl.bindRenderbuffer = function(target, buffer) { var buffer_id; // Accept numbers too. eg: gl.bindRenderbuffer(0) @@ -173,7 +171,7 @@ gl.bindRenderBuffer = function(target, buffer) { else if (buffer === null) buffer_id = 0; else - buffer_id = buffer.buffer_id; + buffer_id = buffer.renderbuffer_id; gl._bindRenderbuffer(target, buffer_id); }; @@ -188,14 +186,53 @@ gl.bindFramebuffer = function(target, buffer) { else if( buffer === null ) buffer_id = null; else - buffer_id = buffer.buffer_id; + buffer_id = buffer.framebuffer_id; gl._bindFramebuffer(target, buffer_id); }; +gl.framebufferRenderbuffer = function(target, attachment, renderbuffertarget, renderbuffer) { + gl._framebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer.renderbuffer_id); +}; + gl.framebufferTexture2D = function(target, attachment, textarget, texture, level) { gl._framebufferTexture2D(target, attachment, textarget, texture.texture_id, level); -} +}; + +gl.isFramebuffer = function(buffer) { + if (buffer && buffer.framebuffer_id) { + return gl._isFramebuffer(buffer.framebuffer_id); + } + return false; +}; + +gl.isProgram = function(program) { + if (program && program.program_id) { + return gl._isProgram(program.program_id); + } + return false; +}; + +gl.isRenderbuffer = function(buffer) { + if (buffer && buffer.renderbuffer_id) { + return gl._isRenderbuffer(buffer.renderbuffer_id); + } + return false; +}; + +gl.isShader = function(shader) { + if (shader && shader.shader_id) { + return gl._isShader(shader.shader_id); + } + return false; +}; + +gl.isTexture = function(texture) { + if (texture && texture.texture_id) { + return gl._isTexture(texture.texture_id); + } + return false; +}; // // Uniform related @@ -415,17 +452,19 @@ gl.texImage2D = function(target, level, internalformat, width, height, border, f format = width; if (image instanceof HTMLImageElement) { - console.log(`==> texImage2D HTMLImageElement internalformat: ${image._glInternalFormat}, format: ${image._glFormat}, image: w:${image.width}, h:${image.height}, dataLen:${image._data.length}`); + // console.log(`==> texImage2D HTMLImageElement internalformat: ${image._glInternalFormat}, format: ${image._glFormat}, image: w:${image.width}, h:${image.height}, dataLen:${image._data.length}`); gl.pixelStorei(gl.UNPACK_ALIGNMENT, image._alignment); _glTexImage2D(target, level, image._glInternalFormat, image.width, image.height, 0, image._glFormat, image._glType, image._data); } else if (image instanceof HTMLCanvasElement) { - console.log(`==> texImage2D HTMLCanvasElement internalformat: ${internalformat}, format: ${format}, image: w:${image.width}, h:${image.height}`);//, dataLen:${image._data.length}`); - _glTexImage2D(target, level, internalformat, image.width, image.height, 0, format, type, image._data._data); + // console.log(`==> texImage2D HTMLCanvasElement internalformat: ${internalformat}, format: ${format}, image: w:${image.width}, h:${image.height}`);//, dataLen:${image._data.length}`); + if (image._data) { + _glTexImage2D(target, level, internalformat, image.width, image.height, 0, format, type, image._data._data); + } } else if (image instanceof ImageData) { - console.log(`==> texImage2D ImageData internalformat: ${internalformat}, format: ${format}, image: w:${image.width}, h:${image.height}`); + // console.log(`==> texImage2D ImageData internalformat: ${internalformat}, format: ${format}, image: w:${image.width}, h:${image.height}`); _glTexImage2D(target, level, internalformat, image.width, image.height, 0, format, type, image._data); } else { @@ -463,7 +502,9 @@ gl.texSubImage2D = function(target, level, xoffset, yoffset, width, height, form _glTexSubImage2D(target, level, xoffset, yoffset, image.width, image.height, image._glFormat, image._glType, image._data); } else if (image instanceof HTMLCanvasElement) { - _glTexSubImage2D(target, level, xoffset, yoffset, image.width, image.height, format, type, image._data._data); + if (image._data) { + _glTexSubImage2D(target, level, xoffset, yoffset, image.width, image.height, format, type, image._data._data); + } } else if (image instanceof ImageData) { _glTexSubImage2D(target, level, xoffset, yoffset, image.width, image.height, format, type, image._data); diff --git a/jsb/builtin/jsb_opengl_constants.js b/jsb/builtin/jsb_opengl_constants.js index 7fd5dc3d1e..b0675ddc16 100644 --- a/jsb/builtin/jsb_opengl_constants.js +++ b/jsb/builtin/jsb_opengl_constants.js @@ -245,6 +245,7 @@ gl.DECR_WRAP = 0x8508; gl.DELETE_STATUS = 0x8b80; gl.DEPTH24_STENCIL8_OES = 0x88f0; gl.DEPTH_ATTACHMENT = 0x8d00; +gl.DEPTH_STENCIL_ATTACHMENT = 0x821a; gl.DEPTH_BITS = 0xd56; gl.DEPTH_BUFFER_BIT = 0x100; gl.DEPTH_BUFFER_BIT0_QCOM = 0x100; @@ -856,6 +857,7 @@ gl.WRITE_ONLY_OES = 0x88b9; gl.Z400_BINARY_AMD = 0x8740; gl.ZERO = 0x0; +gl.RASTERIZER_DISCARD = 0x8C89; gl.UNPACK_FLIP_Y_WEBGL = 0x9240; gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241; gl.CONTEXT_LOST_WEBGL = 0x9242; diff --git a/jsb/builtin/package.json b/jsb/builtin/package.json new file mode 100644 index 0000000000..4173d9ed6d --- /dev/null +++ b/jsb/builtin/package.json @@ -0,0 +1,8 @@ +{ + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-core": "^6.26.0", + "babel-preset-env": "^1.6.1", + "babel-register": "^6.26.0" + } +} From 896d9121cefaf7af1846214fd0868cf855bfe5f6 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 4 Apr 2018 11:05:32 +0800 Subject: [PATCH 17/35] Fix issues --- cocos2d/actions/CCActionInstant.js | 6 +++--- cocos2d/deprecated.js | 4 ++++ modules.json | 20 +++++++------------- 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/cocos2d/actions/CCActionInstant.js b/cocos2d/actions/CCActionInstant.js index b00849a8d5..1ff2aa5c85 100644 --- a/cocos2d/actions/CCActionInstant.js +++ b/cocos2d/actions/CCActionInstant.js @@ -80,7 +80,7 @@ cc.Show = cc.Class({ extends: cc.ActionInstant, update:function (dt) { - var _renderComps = this.target.getComponentsInChildren(cc._SGComponent); + var _renderComps = this.target.getComponentsInChildren(cc.RenderComponent); for (var i = 0; i < _renderComps.length; ++i) { var render = _renderComps[i]; render.enabled = true; @@ -119,7 +119,7 @@ cc.Hide = cc.Class({ extends: cc.ActionInstant, update:function (dt) { - var _renderComps = this.target.getComponentsInChildren(cc._SGComponent); + var _renderComps = this.target.getComponentsInChildren(cc.RenderComponent); for (var i = 0; i < _renderComps.length; ++i) { var render = _renderComps[i]; render.enabled = false; @@ -158,7 +158,7 @@ cc.ToggleVisibility = cc.Class({ extends: cc.ActionInstant, update:function (dt) { - var _renderComps = this.target.getComponentsInChildren(cc._SGComponent); + var _renderComps = this.target.getComponentsInChildren(cc.RenderComponent); for (var i = 0; i < _renderComps.length; ++i) { var render = _renderComps[i]; render.enabled = !render.enabled; diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index 7593cc4914..baa75bd3ae 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -466,6 +466,10 @@ if (CC_DEV) { rand: 'Math.random() * 0xffffff', randomMinus1To1: '(Math.random() - 0.5) * 2', + + container: 'cc.game.container', + _canvas: 'cc.game.canvas', + _renderType: 'cc.game.renderType', }, 'cc'); markAsRemovedInObject(cc, [ 'BlendFunc', diff --git a/modules.json b/modules.json index 71082176f0..7daa45cd12 100644 --- a/modules.json +++ b/modules.json @@ -62,8 +62,7 @@ { "name": "Spine Skeleton", "entries": [ - "./extensions/spine/index.js", - "./jsb/jsb-spine.js" + "./extensions/spine/index.js" ] }, { @@ -131,22 +130,19 @@ { "name": "EditBox", "entries": [ - "./cocos2d/core/components/CCEditBox.js", - "./jsb/jsb-editbox.js" + "./cocos2d/core/components/CCEditBox.js" ] }, { "name": "VideoPlayer", "entries": [ - "./cocos2d/videoplayer/CCVideoPlayer.js", - "./jsb/jsb-videoplayer.js" + "./cocos2d/videoplayer/CCVideoPlayer.js" ] }, { "name": "WebView", "entries": [ - "./cocos2d/webview/CCWebView.js", - "./jsb/jsb-webview.js" + "./cocos2d/webview/CCWebView.js" ] }, { @@ -172,7 +168,7 @@ { "name": "MotionStreak", "entries": [ - "./cocos2d/core/components/motion-streak/CCMotionStreak.js", + "./cocos2d/core/components/CCMotionStreak.js", "./cocos2d/core/renderer/assemblers/motion-streak.js" ] }, @@ -203,15 +199,13 @@ { "name": "DragonBones", "entries": [ - "./extensions/dragonbones/index.js", - "./jsb/jsb-dragonbones.js" + "./extensions/dragonbones/index.js" ] }, { "name": "Physics", "entries": [ - "./cocos2d/core/physics/index.js", - "./jsb/jsb-box2d.js" + "./cocos2d/core/physics/index.js" ], "dependencies": ["Collider"] }, From 645ccc5b5e69b58fa67cbf48008bc2431e01166c Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Wed, 4 Apr 2018 11:54:31 +0800 Subject: [PATCH 18/35] add upgrade code in both _onBatchCreated and _onBatchRestored --- cocos2d/core/CCNode.js | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 56b6495852..819d355a6c 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1009,10 +1009,7 @@ var Node = cc.Class({ // INTERNAL - /* - * The initializer for Node which will be called before all components onLoad - */ - _onBatchCreated () { + _upgrade_1x_to_2x () { // Upgrade scaleX, scaleY from v1.x // TODO: remove in future version, 3.0 ? if (this._scaleX !== undefined) { @@ -1051,6 +1048,13 @@ var Node = cc.Class({ if (this._opacity !== 255 && this._opacity !== undefined) { this._color.a = this._opacity; } + }, + + /* + * The initializer for Node which will be called before all components onLoad + */ + _onBatchCreated () { + this._upgrade_1x_to_2x(); this._updateOrderOfArrival(); @@ -1079,6 +1083,8 @@ var Node = cc.Class({ // the same as _onBatchCreated but untouch prefab _onBatchRestored () { + this._upgrade_1x_to_2x(); + if (!this._activeInHierarchy) { // deactivate ActionManager and EventManager by default if (ActionManagerExist) { From ee3afd4403d318536ab8fe4d147a1784d9afeb10 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Apr 2018 17:32:29 +0800 Subject: [PATCH 19/35] bugfix in equalsToDefault. --- cocos2d/core/platform/instantiate-jit.js | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/cocos2d/core/platform/instantiate-jit.js b/cocos2d/core/platform/instantiate-jit.js index 4b1cdcf2ee..f891f5af1a 100644 --- a/cocos2d/core/platform/instantiate-jit.js +++ b/cocos2d/core/platform/instantiate-jit.js @@ -162,14 +162,7 @@ function equalsToDefault (def, value) { (def.constructor === Object && value.constructor === Object) ) { try { - if (CC_JSB) { - //FIXME: JSON.stringify will take lots of time for compare object at runtime on JSB. - // We need to consider a new way for checking whether two objects are equal. - return false; - } - else { - return JSON.stringify(def) === JSON.stringify(value); - } + return Array.isArray(def) && Array.isArray(value) && def.length === 0 && value.length === 0; } catch (e) { } From 564f3677fc11a1999ef5029619b31f0d1b0bfb3d Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Apr 2018 17:27:48 +0800 Subject: [PATCH 20/35] cc definition fix. --- index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.js b/index.js index d78b1b3b4e..12f2f0a141 100644 --- a/index.js +++ b/index.js @@ -34,7 +34,7 @@ * @module cc * @main cc */ -cc = {}; +cc = cc || {}; require('./predefine'); require('./CCDebugger'); From cec6dc4ce1ee7d4e7d49b04f22989eff08301e39 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Apr 2018 17:53:02 +0800 Subject: [PATCH 21/35] cc.SpriteFrame undefined on JSB fix. --- cocos2d/core/assets/CCSpriteFrame.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/cocos2d/core/assets/CCSpriteFrame.js b/cocos2d/core/assets/CCSpriteFrame.js index de6441f01e..da911febfa 100644 --- a/cocos2d/core/assets/CCSpriteFrame.js +++ b/cocos2d/core/assets/CCSpriteFrame.js @@ -536,8 +536,6 @@ proto.copyWithZone = proto.clone; proto.copy = proto.clone; proto.initWithTexture = proto.setTexture; -if (!CC_JSB) { - cc.SpriteFrame = SpriteFrame; -} +cc.SpriteFrame = SpriteFrame; module.exports = SpriteFrame; From fd245aef1fc023e10246e43902fe5640002005d8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Apr 2018 17:53:48 +0800 Subject: [PATCH 22/35] CCProfiler supports all platform now since it's implemented by label atlas. --- cocos2d/core/utils/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/utils/index.js b/cocos2d/core/utils/index.js index 9f2686ae22..e97dc29341 100644 --- a/cocos2d/core/utils/index.js +++ b/cocos2d/core/utils/index.js @@ -25,7 +25,7 @@ ****************************************************************************/ require('./CCPath'); -if (!CC_EDITOR && !CC_JSB && !CC_WECHATGAME && !CC_QQPLAY) { +if (!CC_EDITOR) { require('./profiler/CCProfiler'); } require('./find'); From 801dc9c5dcc308b2c6bf1eb9369b92a3eb99fc28 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Apr 2018 17:55:01 +0800 Subject: [PATCH 23/35] XMLDOM isn't devloped by cocos, so remove the licence since the original source files also don't include a license information. but it's MIT in fact. --- jsb/builtin/xmldom/dom-parser.js | 24 ------------------------ jsb/builtin/xmldom/dom.js | 25 ------------------------- jsb/builtin/xmldom/entities.js | 24 ------------------------ jsb/builtin/xmldom/sax.js | 25 ------------------------- 4 files changed, 98 deletions(-) diff --git a/jsb/builtin/xmldom/dom-parser.js b/jsb/builtin/xmldom/dom-parser.js index b8dc100965..e45dd476f1 100644 --- a/jsb/builtin/xmldom/dom-parser.js +++ b/jsb/builtin/xmldom/dom-parser.js @@ -1,27 +1,3 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ function DOMParser(options){ this.options = options ||{locator:{}}; diff --git a/jsb/builtin/xmldom/dom.js b/jsb/builtin/xmldom/dom.js index a44f8d7e2e..b13b3719d7 100644 --- a/jsb/builtin/xmldom/dom.js +++ b/jsb/builtin/xmldom/dom.js @@ -1,28 +1,3 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - /* * DOM Level 2 * Object DOMException diff --git a/jsb/builtin/xmldom/entities.js b/jsb/builtin/xmldom/entities.js index 038a5c32c0..1f7d605fbf 100644 --- a/jsb/builtin/xmldom/entities.js +++ b/jsb/builtin/xmldom/entities.js @@ -1,27 +1,3 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ exports.entityMap = { lt: '<', gt: '>', diff --git a/jsb/builtin/xmldom/sax.js b/jsb/builtin/xmldom/sax.js index 933b26681f..f8b494e097 100644 --- a/jsb/builtin/xmldom/sax.js +++ b/jsb/builtin/xmldom/sax.js @@ -1,28 +1,3 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] //[5] Name ::= NameStartChar (NameChar)* From 0ec2b387d0b5a87e4aba1b19b69ac08fc99cde77 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Apr 2018 17:55:17 +0800 Subject: [PATCH 24/35] FileReader API fix. --- jsb/builtin/jsb-adapter/FileReader.js | 32 ++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/jsb/builtin/jsb-adapter/FileReader.js b/jsb/builtin/jsb-adapter/FileReader.js index 6f49201fc6..dabc8b7f44 100755 --- a/jsb/builtin/jsb-adapter/FileReader.js +++ b/jsb/builtin/jsb-adapter/FileReader.js @@ -23,12 +23,32 @@ THE SOFTWARE. ****************************************************************************/ -/* - * TODO 使用 wx.readFile 来封装 FileReader - */ -class FileReader { - construct() { - } +const EventTarget = require('./EventTarget') + +class FileReader extends EventTarget { + construct() { + this.result = null + + } + + // Aborts the read operation. Upon return, the readyState will be DONE. + abort() {} + + // Starts reading the contents of the specified Blob, once finished, the result attribute contains an ArrayBuffer representing the file's data. + readAsArrayBuffer() { + + } + + // Starts reading the contents of the specified Blob, once finished, the result attribute contains a data: URL representing the file's data. + readAsDataURL(blob) { + this.result = 'data:image/png;base64,' + window.btoa(blob); + this.onload(); + } + + // Starts reading the contents of the specified Blob, once finished, the result attribute contains the contents of the file as a text string. + readAsText() { + + } } module.exports = FileReader; From 50dcb0e8fd75e2ee705c4aebca86ecc17af66d06 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Apr 2018 17:55:31 +0800 Subject: [PATCH 25/35] No audio deprecated any more. --- jsb/jsb-audio.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/jsb/jsb-audio.js b/jsb/jsb-audio.js index 94f94ebc1a..a59846a41e 100644 --- a/jsb/jsb-audio.js +++ b/jsb/jsb-audio.js @@ -48,10 +48,6 @@ cc.Audio.Type = { cc.audioEngine = audioEngine; audioEngine.play = audioEngine.play2d; audioEngine.setMaxWebAudioSize = function () {}; - // deprecated - // var Module = require('../cocos2d/audio/deprecated'); - // Module.removed(audioEngine); - // Module.deprecated(audioEngine); proto.State = audioEngine.AudioState; From 707bc6c5fcd94b75262925602d4172d1cbc53324 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Apr 2018 17:55:58 +0800 Subject: [PATCH 26/35] Removes WindowProperties.js file. --- jsb/builtin/jsb-adapter/WindowProperties.js | 47 --------------------- 1 file changed, 47 deletions(-) delete mode 100755 jsb/builtin/jsb-adapter/WindowProperties.js diff --git a/jsb/builtin/jsb-adapter/WindowProperties.js b/jsb/builtin/jsb-adapter/WindowProperties.js deleted file mode 100755 index 58e9466855..0000000000 --- a/jsb/builtin/jsb-adapter/WindowProperties.js +++ /dev/null @@ -1,47 +0,0 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -const { screenWidth, screenHeight, devicePixelRatio } = {screenWidth: window.innerWidth, screenHeight: window.innerHeight, devicePixelRatio: 1};//cjh wx.getSystemInfoSync() - -const innerWidth = screenWidth -const innerHeight = screenHeight -const screen = { - availWidth: innerWidth, - availHeight: innerHeight -} -const performance = null//cjh wx.getPerformance() -const ontouchstart = null -const ontouchmove = null -const ontouchend = null - -module.exports = { - innerWidth: innerWidth, - innerHeight: innerHeight, - devicePixelRatio: devicePixelRatio, - screen: screen, - performance: performance, - ontouchstart: ontouchstart, - ontouchmove: ontouchmove, - ontouchend: ontouchend -}; From ed16c5736c3ad75652c40f70c28614c35827f7e8 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Wed, 4 Apr 2018 18:05:44 +0800 Subject: [PATCH 27/35] add dragonbones canvas support --- extensions/dragonbones/canvas-assembler.js | 79 +++++++++++++++++++ extensions/dragonbones/index.js | 9 ++- ...nbones-assembler.js => webgl-assembler.js} | 0 3 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 extensions/dragonbones/canvas-assembler.js rename extensions/dragonbones/{dragonbones-assembler.js => webgl-assembler.js} (100%) diff --git a/extensions/dragonbones/canvas-assembler.js b/extensions/dragonbones/canvas-assembler.js new file mode 100644 index 0000000000..eaa686712a --- /dev/null +++ b/extensions/dragonbones/canvas-assembler.js @@ -0,0 +1,79 @@ +const Armature = require('./ArmatureDisplay'); +const renderEngine = require('../../cocos2d/core/renderer/render-engine'); +const math = renderEngine.math; + +const utils = require('../../cocos2d/core/renderer/canvas/renderers/utils'); + +let _color = cc.color(); + +let _matrix = math.mat4.create(); +let _matrix2 = math.mat4.create(); + +let armatureAssembler = { + draw (ctx, comp) { + let armature = comp._armature; + if (!armature || comp._isChildArmature) return 0; + + ctx.save(); + + let node = comp.node; + node._updateWorldMatrix(); + let matrix = node._worldMatrix; + + let texture = comp.dragonAtlasAsset.texture; + this.drawArmature(ctx, armature, texture, matrix); + + ctx.restore(); + + return 1; + }, + + drawArmature (ctx, armature, texture, matrix) { + let slots = armature._slots; + + for (let i = 0, l = slots.length; i < l; i++) { + let slot = slots[i]; + if (!slot._visible || !slot._displayData) continue; + + if (slot.childArmature) { + math.mat4.mul(_matrix, matrix, slot._matrix); + this.drawArmature(ctx, slot.childArmature, texture, _matrix); + continue; + } + + let localVertices = slot._localVertices; + + if (localVertices.length !== 4) { + continue; + } + + ctx.save(); + + math.mat4.mul(_matrix2, matrix, slot._matrix); + + let m = _matrix2; + ctx.transform(m.m00, -m.m01, -m.m04, m.m05, m.m12, -m.m13); + + let vertices = slot._vertices; + let sx = vertices[0].u * texture.width; + let sy = vertices[3].v * texture.height; + let sw = vertices[3].u * texture.width - sx; + let sh = vertices[0].v * texture.height - sy; + + let x = localVertices[0].x; + let y = localVertices[0].y; + let w = localVertices[3].x - x; + let h = localVertices[3].y - y; + y = -y-h; + + _color._val = slot._color; + let image = utils.getFrameCache(texture, _color, sx, sy, sw, sh); + + ctx.drawImage(image, x, y, w, h); + + ctx.restore(); + } + } +}; + +module.exports = Armature._assembler = armatureAssembler; diff --git a/extensions/dragonbones/index.js b/extensions/dragonbones/index.js index 5afef7f1bb..e0ec4597ce 100644 --- a/extensions/dragonbones/index.js +++ b/extensions/dragonbones/index.js @@ -132,7 +132,14 @@ if (!CC_EDITOR || !Editor.isMainProcess) { require('./DragonBonesAtlasAsset'); require('./ArmatureDisplay') - require('./dragonbones-assembler'); + cc.game.once(cc.game.EVENT_RENDERER_INITED, () => { + if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { + require('./canvas-assembler'); + } + else { + require('./webgl-assembler'); + } + }) } else { require('./DragonBonesAsset'); require('./DragonBonesAtlasAsset'); diff --git a/extensions/dragonbones/dragonbones-assembler.js b/extensions/dragonbones/webgl-assembler.js similarity index 100% rename from extensions/dragonbones/dragonbones-assembler.js rename to extensions/dragonbones/webgl-assembler.js From 8f7e5618af43f91dc7995d82c45f49546a5f1375 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sat, 7 Apr 2018 18:54:49 +0800 Subject: [PATCH 28/35] Add Mask canvas renderer --- .../core/renderer/canvas/renderers/index.js | 6 +- .../core/renderer/canvas/renderers/mask.js | 96 +++++++++++++++++++ 2 files changed, 100 insertions(+), 2 deletions(-) create mode 100644 cocos2d/core/renderer/canvas/renderers/mask.js diff --git a/cocos2d/core/renderer/canvas/renderers/index.js b/cocos2d/core/renderer/canvas/renderers/index.js index ec75cc9b5c..87275cf824 100644 --- a/cocos2d/core/renderer/canvas/renderers/index.js +++ b/cocos2d/core/renderer/canvas/renderers/index.js @@ -29,8 +29,9 @@ let Sprite = require('../../../components/CCSprite'); let Label = require('../../../components/CCLabel'); let Mask = require('../../../components/CCMask'); let RichText = require('../../../components/CCRichText'); -// the following should be placed into their own module folder let Graphics = require('../../../graphics/graphics'); + +// the following should be placed into their own module folder // let ParticleSystem = require('../../../../particle/CCParticleSystem'); // let TiledLayer = require('../../../../tilemap/CCTiledLayer'); // let Skeleton = require('../../../../../extensions/spine/Skeleton'); @@ -39,6 +40,7 @@ let Graphics = require('../../../graphics/graphics'); let spriteRenderer = require('./sprite'); let labelRenderer = require('./label'); let graphicsRenderer = require('./graphics'); +let maskRenderer = require('./mask'); let map = {}; let postMap = {}; @@ -55,7 +57,7 @@ function addRenderer (Component, handler, postHandler) { addRenderer(Sprite, spriteRenderer); addRenderer(Label, labelRenderer); -addRenderer(Mask, null); +addRenderer(Mask, maskRenderer.beforeHandler, maskRenderer.afterHandler); addRenderer(RichText, null); addRenderer(Graphics, graphicsRenderer); diff --git a/cocos2d/core/renderer/canvas/renderers/mask.js b/cocos2d/core/renderer/canvas/renderers/mask.js new file mode 100644 index 0000000000..eeccef1c2b --- /dev/null +++ b/cocos2d/core/renderer/canvas/renderers/mask.js @@ -0,0 +1,96 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +const Node = require('../../../CCNode'); +const Mask = require('../../../components/CCMask'); +const Graphics = require('../../../graphics/graphics'); +const graphicsHandler = require('./graphics'); + +// for nested mask, we might need multiple graphics component to avoid data conflict +let _graphicsPool = []; + +function getGraphics () { + let graphics = _graphicsPool.pop(); + + if (!graphics) { + let graphicsNode = new Node(); + graphics = graphicsNode.addComponent(Graphics); + graphics.lineWidth = 0; + } + return graphics; +} + +let beforeHandler = { + updateGraphics (mask) { + let node = mask.node; + let graphics = mask._graphics; + // Share render data with graphics content + graphics.clear(false); + let width = node.width; + let height = node.height; + let x = -width * node.anchorX; + let y = -height * node.anchorY; + if (mask._type === Mask.Type.RECT) { + graphics.rect(x, y, width, height); + } + else if (mask._type === Mask.Type.ELLIPSE) { + let cx = x + width / 2, + cy = y + height / 2, + rx = width / 2, + ry = height / 2; + graphics.ellipse(cx, cy, rx, ry); + } + graphics.stroke(); + }, + + draw (ctx, mask) { + let node = mask.node; + // Transform + let matrix = node._worldMatrix; + let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, + tx = matrix.m12, ty = matrix.m13; + + ctx.save(); + ctx.transform(a, b, c, d, tx, -ty); + + // draw stencil + mask._graphics = getGraphics(); + this.updateGraphics(mask); + graphicsHandler.draw(ctx, mask._graphics); + + ctx.clip(); + } +}; + +let afterHandler = { + draw (ctx, mask) { + ctx.restore(); + } +}; + +module.exports = { + beforeHandler, + afterHandler +}; \ No newline at end of file From a553d080e75b465f18b5ab724d0467c0199e12ad Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sat, 7 Apr 2018 18:55:04 +0800 Subject: [PATCH 29/35] Fix webgl mask assembler --- cocos2d/core/renderer/assemblers/mask-assembler.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/renderer/assemblers/mask-assembler.js b/cocos2d/core/renderer/assemblers/mask-assembler.js index c9251e19b5..e2584a0544 100644 --- a/cocos2d/core/renderer/assemblers/mask-assembler.js +++ b/cocos2d/core/renderer/assemblers/mask-assembler.js @@ -94,7 +94,7 @@ let maskFrontAssembler = js.addon({ if (mask.spriteFrame) { datas = mask._renderDatas; datas.length = 0; - renderData.dataLength = 4; + renderData.dataLength = 8; spriteAssembler.update(mask); renderData.material = mask.getMaterial(); datas.push(renderData); @@ -169,8 +169,7 @@ let maskEndAssembler = js.addon({ // vertex buffer if (mask._type === Mask.Type.IMAGE_STENCIL) { - spriteAssembler.fillVertexBuffer(mask, batchData.byteOffset / 4, vbuf, uintbuf); - spriteAssembler.fillIndexBuffer(mask, batchData.indiceOffset, vertexId, ibuf); + spriteAssembler.fillBuffers(mask, batchData, vertexId, vbuf, uintbuf, ibuf); } else { // Share node for correct global matrix From c01a31e00ac599860459bde6fc97a3ab32a696ed Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sat, 7 Apr 2018 18:55:19 +0800 Subject: [PATCH 30/35] Fix license --- .../canvas/renderers/graphics/impl.js | 24 ++++++++++++++++++ .../canvas/renderers/graphics/index.js | 25 +++++++++++++++++++ .../renderer/canvas/renderers/label/bmfont.js | 25 +++++++++++++++++++ .../renderer/canvas/renderers/label/ttf.js | 25 +++++++++++++++++++ 4 files changed, 99 insertions(+) diff --git a/cocos2d/core/renderer/canvas/renderers/graphics/impl.js b/cocos2d/core/renderer/canvas/renderers/graphics/impl.js index 4e45b6e648..9ecc8255e6 100644 --- a/cocos2d/core/renderer/canvas/renderers/graphics/impl.js +++ b/cocos2d/core/renderer/canvas/renderers/graphics/impl.js @@ -1,3 +1,27 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ const Helper = require('../../../../graphics/helper'); const Types = require('../../../../graphics/types'); diff --git a/cocos2d/core/renderer/canvas/renderers/graphics/index.js b/cocos2d/core/renderer/canvas/renderers/graphics/index.js index 5899989b94..1d5fbf6146 100644 --- a/cocos2d/core/renderer/canvas/renderers/graphics/index.js +++ b/cocos2d/core/renderer/canvas/renderers/graphics/index.js @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + const Impl = require('./impl'); module.exports = { diff --git a/cocos2d/core/renderer/canvas/renderers/label/bmfont.js b/cocos2d/core/renderer/canvas/renderers/label/bmfont.js index 5dd09388e5..0000f0199b 100644 --- a/cocos2d/core/renderer/canvas/renderers/label/bmfont.js +++ b/cocos2d/core/renderer/canvas/renderers/label/bmfont.js @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + const bmfontUtils = require('../../../utils/label/bmfont') const js = require('../../../../platform/js'); const utils = require('../utils'); diff --git a/cocos2d/core/renderer/canvas/renderers/label/ttf.js b/cocos2d/core/renderer/canvas/renderers/label/ttf.js index 9926781a72..4d245068a1 100644 --- a/cocos2d/core/renderer/canvas/renderers/label/ttf.js +++ b/cocos2d/core/renderer/canvas/renderers/label/ttf.js @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + const ttfUtils = require('../../../utils/label/ttf') const js = require('../../../../platform/js'); const utils = require('../utils'); From 6f77054b3d0cce557eeb3908516127969d22442c Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 8 Apr 2018 00:39:16 +0800 Subject: [PATCH 31/35] Fix rich text object testing --- cocos2d/core/components/CCRichText.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index afe28f67e5..8093f3ad8e 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -65,8 +65,7 @@ var pool = new js.Pool(function (node) { if (CC_DEV) { cc.assert(!node._parent, 'Recycling node\'s parent should be null!'); } - let Flags = cc.Object.Flags; - if (node._objFlags & Flags.Destroyed || node._objFlags & Flags.Destroying) { + if (!cc.isValid(node)) { return false; } if (node.getComponent(cc.LabelOutline)) { From c89ee01a5604a0faa5b15834488c542b3b06e854 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 8 Apr 2018 00:39:39 +0800 Subject: [PATCH 32/35] Fix JSB build issues --- cocos2d/core/renderer/render-engine.jsb.js | 5000 ++++++++++---------- gulp/tasks/engine.js | 2 +- index.js | 5 +- 3 files changed, 2465 insertions(+), 2542 deletions(-) diff --git a/cocos2d/core/renderer/render-engine.jsb.js b/cocos2d/core/renderer/render-engine.jsb.js index 06416dcbc0..236a71331e 100644 --- a/cocos2d/core/renderer/render-engine.jsb.js +++ b/cocos2d/core/renderer/render-engine.jsb.js @@ -26,9 +26,2465 @@ ****************************************************************************/ -var renderEngine = (function () { 'use strict'; +var ForwardRenderer = window.renderer.ForwardRenderer; + +var chunks = { +}; + +var templates = [ + { + name: 'gray_sprite', + vert: '\n \nuniform mat4 viewProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\nattribute vec2 a_uv0;\nvarying vec2 uv0;\nvoid main () {\n vec4 pos = viewProj * vec4(a_position, 1);\n v_fragmentColor = a_color;\n uv0 = a_uv0;\n gl_Position = pos;\n}', + frag: '\n \nuniform sampler2D texture;\nvarying vec2 uv0;\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 c = v_fragmentColor * texture2D(texture, uv0);\n float gray = 0.2126*c.r + 0.7152*c.g + 0.0722*c.b;\n gl_FragColor = vec4(gray, gray, gray, c.a);\n}', + defines: [ + ], + }, + { + name: 'sprite', + vert: '\n \nuniform mat4 viewProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\n#ifdef useModel\n uniform mat4 model;\n#endif\n#ifdef useTexture\n attribute vec2 a_uv0;\n varying vec2 uv0;\n#endif\nvoid main () {\n mat4 mvp;\n #ifdef useModel\n mvp = viewProj * model;\n #else\n mvp = viewProj;\n #endif\n vec4 pos = mvp * vec4(a_position, 1);\n v_fragmentColor = a_color;\n \n #ifdef useTexture\n uv0 = a_uv0;\n #endif\n gl_Position = pos;\n}', + frag: '\n \n#ifdef useTexture\n uniform sampler2D texture;\n varying vec2 uv0;\n#endif\n#ifdef alphaTest\n uniform float alphaThreshold;\n#endif\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 o = v_fragmentColor;\n #ifdef useTexture\n o *= texture2D(texture, uv0);\n #endif\n #ifdef alphaTest\n if (o.a <= alphaThreshold)\n discard;\n #endif\n gl_FragColor = o;\n}', + defines: [ + { name: 'useTexture', }, + { name: 'useModel', }, + { name: 'alphaTest', } ], + }, + { + name: 'vfx_emitter', + vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', + frag: '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D noise;\nuniform sampler2D state;\nuniform vec2 statesize;\nuniform vec2 noisesize;\nuniform bool stopped;\nuniform float dt;\nuniform float mode;\nuniform float noiseId;\nuniform float emitVar;\nuniform float life;\nuniform float lifeVar;\nuniform vec2 pos;\nuniform vec2 posVar;\nuniform vec4 color;\nuniform vec4 colorVar;\n \nuniform vec4 endColor;\nuniform vec4 endColorVar;\nuniform float size;\nuniform float sizeVar;\nuniform float endSize;\nuniform float endSizeVar;\nuniform float rot;\nuniform float rotVar;\nuniform float endRot;\nuniform float endRotVar;\nuniform float angle;\nuniform float angleVar;\nuniform float speed;\nuniform float speedVar;\nuniform float radial;\nuniform float radialVar;\nuniform float tangent;\nuniform float tangentVar;\nuniform float radius;\nuniform float radiusVar;\nuniform float endRadius;\nuniform float endRadiusVar;\nuniform float rotatePS;\nuniform float rotatePSVar;\nuniform float sizeScale;\nuniform float accelScale;\nuniform float radiusScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float NOISE_SCALE = 10000.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nconst float COLOR_SCALE = 1.0;\nconst float LIFE_SCALE = 100.0;\nconst float START_SIZE_EQUAL_TO_END_SIZE = -1.0;\nconst float START_RADIUS_EQUAL_TO_END_RADIUS = -1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nfloat randomMinus1To1(vec2 randomD) {\n float random = decode(randomD, NOISE_SCALE);\n return (random - 0.5) * 2.0;\n}\nbool doEmit (vec4 randomD) {\n float random1 = decode(randomD.rg, NOISE_SCALE);\n if (!stopped && (life + lifeVar) * random1 < life) {\n return true;\n }\n else {\n return false;\n }\n}\nvec4 initLife (vec4 data, vec4 randomD) {\n \n if (doEmit(randomD)) {\n float random2 = decode(randomD.ba, NOISE_SCALE);\n float plife = life + lifeVar * random2;\n vec2 l = encode(plife, LIFE_SCALE);\n return vec4(l, l);\n }\n else {\n return data;\n }\n}\nvec4 initColor (float randr, float randg, float randb, float randa) {\n vec4 random = vec4(randr, randg, randb, randa);\n vec4 result = clamp(color + colorVar * random, 0.0, 255.0);\n return result / 255.0;\n}\nvec4 initDeltaRG (vec2 startR, vec2 random) {\n vec2 start = clamp(color.rg + colorVar.rg * startR, 0.0, 255.0);\n vec2 end = clamp(endColor.rg + endColorVar.rg * random, 0.0, 255.0);\n vec2 delta = end - start;\n return vec4(encode(delta.x, COLOR_SCALE), encode(delta.y, COLOR_SCALE));\n}\nvec4 initDeltaBA (vec2 startR, vec2 random) {\n vec2 start = clamp(color.ba + colorVar.ba * startR, 0.0, 255.0);\n vec2 end = clamp(endColor.ba + endColorVar.ba * random, 0.0, 255.0);\n vec2 delta = end - start;\n return vec4(encode(delta.x, COLOR_SCALE), encode(delta.y, COLOR_SCALE));\n}\nvec4 initSize (float rand1, float rand2) {\n float start = max(0.0, size + sizeVar * rand1);\n if (endSize == START_SIZE_EQUAL_TO_END_SIZE) {\n float delta = 0.0;\n return vec4(encode(start, sizeScale), encode(delta, sizeScale));\n }\n else {\n float end = max(0.0, endSize + endSizeVar * rand2);\n float delta = end - start;\n return vec4(encode(start, sizeScale), encode(delta, sizeScale));\n }\n}\nvec4 initRotation (float rand1, float rand2) {\n float start = rot + rotVar * rand1;\n float end = endRot + endRotVar * rand2;\n float delta = end - start;\n return vec4(encode(start, ROTATION_SCALE), encode(delta, ROTATION_SCALE));\n}\nvec4 initControl1 (float rand1, float rand2) {\n \n if (mode == 0.0) {\n float pAngle = angle + angleVar * rand1;\n float dirX = cos(pAngle);\n float dirY = sin(pAngle);\n float pSpeed = speed + speedVar * rand2;\n return vec4(encode(dirX * pSpeed, POSITION_SCALE), encode(dirY * pSpeed, POSITION_SCALE));\n }\n \n else {\n float pAngle = angle + angleVar * rand1;\n float pRadius = radius + radiusVar * rand2;\n return vec4(encode(pAngle, ROTATION_SCALE), encode(pRadius, radiusScale));\n }\n}\nvec4 initControl2 (float startR1, float rand1, float rand2) {\n \n if (mode == 0.0) {\n float pRadial = radial + radialVar * rand1;\n float pTangent = tangent + tangentVar * rand2;\n return vec4(encode(pRadial, accelScale), encode(pTangent, accelScale));\n }\n \n else {\n float degreesPerSecond = rotatePS + rotatePSVar * rand1;\n float pDeltaRadius;\n if (endRadius == START_RADIUS_EQUAL_TO_END_RADIUS) {\n pDeltaRadius = 0.0;\n }\n else {\n float pRadius = radius + radiusVar * startR1;\n pDeltaRadius = (endRadius + endRadiusVar * rand2 - pRadius);\n }\n return vec4(encode(degreesPerSecond, ROTATION_SCALE), encode(pDeltaRadius, radiusScale));\n }\n}\nvec4 initPos (float rand1, float rand2) {\n vec2 result = pos + posVar * vec2(rand1, rand2);\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n}\nvoid main() {\n vec2 pixel = floor(index * statesize);\n vec2 pindex = floor(pixel / 3.0);\n vec2 temp = mod(pixel, vec2(3.0, 3.0));\n float id = floor(temp.y * 3.0 + temp.x);\n vec2 noffset = vec2(floor(noiseId / 4.0), mod(noiseId, 4.0));\n vec2 nid = pixel + noffset;\n vec4 randomD = texture2D(noise, nid / noisesize);\n \n vec4 lifeData = texture2D(state, pindex * 3.0 / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n float life = decode(lifeData.ba, LIFE_SCALE);\n \n if (id == 0.0) {\n vec4 data = texture2D(state, index);\n if (rest <= 0.0) {\n gl_FragColor = initLife(data, randomD);\n }\n else {\n gl_FragColor = data;\n }\n return;\n }\n \n if (rest > 0.0) {\n vec4 data = texture2D(state, index);\n gl_FragColor = data;\n return;\n }\n vec2 lifeNid = pindex * 3.0 + noffset;\n vec4 lifeRandomD = texture2D(noise, lifeNid / noisesize);\n bool emitting = doEmit(lifeRandomD);\n if (!emitting) {\n vec4 data = texture2D(state, index);\n gl_FragColor = data;\n return;\n }\n \n float random1 = randomMinus1To1(randomD.rg);\n float random2 = randomMinus1To1(randomD.ba);\n \n if (id == 1.0) {\n vec4 randomD3 = texture2D(noise, vec2(nid.x - 1.0, nid.y + 1.0) / noisesize);\n float random3 = randomMinus1To1(randomD3.rg);\n float random4 = randomMinus1To1(randomD3.ba);\n gl_FragColor = initColor(random1, random2, random3, random4);\n return;\n }\n \n if (id == 2.0) {\n vec4 randomD1 = texture2D(noise, vec2(nid.x - 1.0, nid.y) / noisesize);\n float startR1 = randomMinus1To1(randomD1.rg);\n float startR2 = randomMinus1To1(randomD1.ba);\n vec2 startR = vec2(startR1, startR2);\n gl_FragColor = initDeltaRG(startR, vec2(random1, random2));\n return;\n }\n \n if (id == 3.0) {\n vec2 startR = vec2(random1, random2);\n gl_FragColor = initDeltaBA(startR, vec2(random1, random2));\n return;\n }\n \n if (id == 4.0) {\n gl_FragColor = initSize(random1, random2);\n return;\n }\n \n if (id == 5.0) {\n gl_FragColor = initRotation(random1, random2);\n return;\n }\n \n if (id == 6.0) {\n gl_FragColor = initControl1(random1, random2);\n return;\n }\n \n if (id == 7.0) {\n vec4 randomD6 = texture2D(noise, vec2(nid.x - 1.0, nid.y) / noisesize);\n float startR1 = randomMinus1To1(randomD6.rg);\n gl_FragColor = initControl2(startR1, random1, random2);\n return;\n }\n \n if (id == 8.0) {\n gl_FragColor = initPos(random1, random2);\n return;\n }\n}', + defines: [ + ], + }, + { + name: 'vfx_particle', + vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nuniform mat4 model;\nuniform mat4 viewProj;\nuniform sampler2D state;\nuniform sampler2D quad;\nuniform vec2 statesize;\nuniform vec2 quadsize;\nuniform float z;\nuniform vec2 lb;\nuniform vec2 rt;\nvarying lowp vec4 v_fragmentColor;\nvarying vec2 uv0;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvoid main() {\n vec2 sIndex = floor(a_quad / 2.0) * 3.0;\n vec4 lifeData = texture2D(state, sIndex / statesize);\n float life = decode(lifeData.rg, LIFE_SCALE);\n if (life <= 0.0) {\n v_fragmentColor = vec4(0.0, 0.0, 0.0, 0.0);\n uv0 = vec2(0.0, 0.0);\n gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n }\n else {\n vec2 posIndex = a_quad / quadsize;\n vec4 posData = texture2D(quad, posIndex);\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n vec2 cIndex = vec2(sIndex.x + 1.0, sIndex.y) / statesize;\n vec4 color = texture2D(state, cIndex);\n v_fragmentColor = color;\n float u, v;\n vec2 uvId = mod(a_quad, vec2(2.0));\n if (uvId.x == 0.0) {\n u = lb.x;\n }\n else {\n u = rt.x;\n }\n if (uvId.y == 0.0) {\n v = lb.y;\n }\n else {\n v = rt.y;\n }\n uv0 = vec2(u, v);\n gl_Position = viewProj * model * vec4(pos, z, 1.0);\n } \n}\n', + frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D texture;\nvarying vec2 uv0;\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 o = v_fragmentColor;\n o *= texture2D(texture, uv0);\n gl_FragColor = o;\n}', + defines: [ + ], + }, + { + name: 'vfx_quad', + vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', + frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D state;\nuniform vec2 quadsize;\nuniform vec2 statesize;\nuniform float sizeScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nvoid main() {\n vec2 pixel = floor(index * quadsize);\n vec2 pIndex = floor(pixel / 2.0) * 3.0;\n vec4 lifeData = texture2D(state, pIndex / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n if (rest <= 0.0) {\n gl_FragColor = vec4(encode(0.0, POSITION_SCALE), encode(0.0, POSITION_SCALE));\n return;\n }\n vec2 dataIndex = (pIndex + 2.0) / statesize;\n vec4 posData = texture2D(state, dataIndex);\n float x = decode(posData.rg, POSITION_SCALE);\n float y = decode(posData.ba, POSITION_SCALE);\n vec2 pos = vec2(x, y);\n dataIndex = (pIndex + 1.0) / statesize;\n vec4 sizeData = texture2D(state, dataIndex);\n float size = decode(sizeData.rg, sizeScale);\n dataIndex.x = (pIndex.x + 2.0) / statesize.x;\n dataIndex.y = (pIndex.y + 1.0) / statesize.y;\n vec4 rotData = texture2D(state, dataIndex);\n float rot = radians(mod(decode(rotData.rg, ROTATION_SCALE), 180.0));\n float a = cos(rot);\n float b = -sin(rot);\n float c = -b;\n float d = a;\n vec2 vert = (mod(pixel, vec2(2.0)) - 0.5) * size;\n x = vert.x * a + vert.y * c + pos.x;\n y = vert.x * b + vert.y * d + pos.y;\n gl_FragColor = vec4(encode(x, POSITION_SCALE), encode(y, POSITION_SCALE));\n}\n', + defines: [ + ], + }, + { + name: 'vfx_update', + vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', + frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D state;\nuniform vec2 statesize;\nuniform float dt;\nuniform float mode;\nuniform vec2 gravity;\nuniform float sizeScale;\nuniform float accelScale;\nuniform float radiusScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float MAX_VALUE = BASE * BASE;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nconst float COLOR_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nvec4 updateLife (vec4 data) {\n float rest = decode(data.rg, LIFE_SCALE);\n rest -= dt;\n return vec4(encode(rest, LIFE_SCALE), data.ba);\n}\nvec4 updateColor (vec4 color, vec4 deltaRG, vec4 deltaBA, float life) {\n float r = decode(deltaRG.rg, COLOR_SCALE);\n float g = decode(deltaRG.ba, COLOR_SCALE);\n float b = decode(deltaBA.rg, COLOR_SCALE);\n float a = decode(deltaBA.ba, COLOR_SCALE);\n vec4 deltaColor = vec4(r, g, b, a) / 255.0;\n \n color = clamp(color + deltaColor * dt / life, 0.0, 1.0);\n return color;\n}\nvec4 updateSize (vec4 data, float life) {\n float size = decode(data.rg, sizeScale);\n float deltaSize = decode(data.ba, sizeScale);\n size = clamp(size + deltaSize * dt / life, 0.0, MAX_VALUE);\n return vec4(encode(size, sizeScale), data.ba);\n}\nvec4 updateRotation (vec4 data, float life) {\n float rotation = decode(data.rg, ROTATION_SCALE);\n float deltaRotation = decode(data.ba, ROTATION_SCALE);\n rotation = mod(rotation + deltaRotation * dt / life, 180.0);\n return vec4(encode(rotation, ROTATION_SCALE), data.ba);\n}\nvec4 updateControl (vec4 control1, vec4 control2, vec4 posData, float life) {\n \n if (mode == 0.0) {\n vec2 dir = vec2(decode(control1.rg, POSITION_SCALE), decode(control1.ba, POSITION_SCALE));\n float radialAccel = decode(control2.rg, accelScale);\n float tangentialAccel = decode(control2.ba, accelScale);\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n vec2 radial = normalize(pos);\n vec2 tangential = vec2(-radial.y, radial.x);\n radial = radial * radialAccel;\n tangential = tangential * tangentialAccel;\n vec2 result = dir + (radial + tangentialAccel + gravity) * dt;\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n }\n \n else {\n float angle = mod(decode(control1.rg, ROTATION_SCALE), 180.0);\n float radius = decode(control1.ba, radiusScale);\n float degreesPerSecond = decode(control2.rg, ROTATION_SCALE);\n float deltaRadius = decode(control2.ba, radiusScale);\n angle += degreesPerSecond * dt;\n radius += deltaRadius * dt / life;\n return vec4(encode(angle, ROTATION_SCALE), encode(radius, radiusScale));\n }\n}\nvec4 updatePos (vec4 posData, vec4 control) {\n vec2 result;\n \n if (mode == 0.0) {\n vec2 dir = vec2(decode(control.rg, POSITION_SCALE), decode(control.ba, POSITION_SCALE));\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n result = pos + dir * dt;\n }\n \n else {\n float angle = radians(mod(decode(control.rg, ROTATION_SCALE), 180.0));\n float radius = decode(control.ba, radiusScale);\n result.x = -cos(angle) * radius;\n result.y = -sin(angle) * radius;\n }\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n}\nvoid main() {\n vec2 pixel = floor(index * statesize);\n vec2 pindex = floor(pixel / 3.0);\n vec2 temp = mod(pixel, vec2(3.0));\n float id = floor(temp.y * 3.0 + temp.x);\n \n vec4 data = texture2D(state, index);\n vec4 lifeData = texture2D(state, pindex * 3.0 / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n if (rest <= 0.0) {\n gl_FragColor = data;\n return;\n }\n \n if (id == 2.0 || id == 3.0 || id == 7.0) {\n gl_FragColor = data;\n return;\n }\n float life = decode(lifeData.ba, LIFE_SCALE);\n \n if (id == 0.0) {\n gl_FragColor = updateLife(data);\n return;\n }\n \n if (id == 1.0) {\n vec2 rgIndex = vec2(pixel.x + 1.0, pixel.y) / statesize;\n vec4 deltaRG = texture2D(state, rgIndex);\n vec2 baIndex = vec2(pixel.x - 1.0, pixel.y + 1.0) / statesize;\n vec4 deltaBA = texture2D(state, baIndex);\n gl_FragColor = updateColor(data, deltaRG, deltaBA, life);\n return;\n }\n \n if (id == 4.0) {\n gl_FragColor = updateSize(data, life);\n return;\n }\n \n if (id == 5.0) {\n gl_FragColor = updateRotation(data, life);\n return;\n }\n \n if (id == 6.0) {\n vec2 ctrlIndex = vec2(pixel.x + 1.0, pixel.y) / statesize;\n vec4 control2 = texture2D(state, ctrlIndex);\n vec2 posIndex = vec2(pixel.x + 2.0, pixel.y) / statesize;\n vec4 pos = texture2D(state, posIndex);\n gl_FragColor = updateControl(data, control2, pos, life);\n return;\n }\n \n if (id == 8.0) {\n vec2 ctrlIndex = vec2(pixel.x - 2.0, pixel.y) / statesize;\n vec4 control1 = texture2D(state, ctrlIndex);\n gl_FragColor = updatePos(data, control1);\n return;\n }\n}\n', + defines: [ + ], + } ]; + +var shaders = { + chunks: chunks, + templates: templates +}; + +// reference: https://github.com/mziccard/node-timsort + +/** + * Default minimum size of a run. + */ +var DEFAULT_MIN_MERGE = 32; + +/** + * Minimum ordered subsequece required to do galloping. + */ +var DEFAULT_MIN_GALLOPING = 7; + +/** + * Default tmp storage length. Can increase depending on the size of the + * smallest run to merge. + */ +var DEFAULT_TMP_STORAGE_LENGTH = 256; + +/** + * Pre-computed powers of 10 for efficient lexicographic comparison of + * small integers. + */ +var POWERS_OF_TEN = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]; + +/** + * Estimate the logarithm base 10 of a small integer. + * + * @param {number} x - The integer to estimate the logarithm of. + * @return {number} - The estimated logarithm of the integer. + */ +function log10(x) { + if (x < 1e5) { + if (x < 1e2) { + return x < 1e1 ? 0 : 1; + } + + if (x < 1e4) { + return x < 1e3 ? 2 : 3; + } + + return 4; + } + + if (x < 1e7) { + return x < 1e6 ? 5 : 6; + } + + if (x < 1e9) { + return x < 1e8 ? 7 : 8; + } + + return 9; +} + +/** + * Default alphabetical comparison of items. + * + * @param {string|object|number} a - First element to compare. + * @param {string|object|number} b - Second element to compare. + * @return {number} - A positive number if a.toString() > b.toString(), a + * negative number if .toString() < b.toString(), 0 otherwise. + */ +function alphabeticalCompare(a, b) { + if (a === b) { + return 0; + } + + if (~~a === a && ~~b === b) { + if (a === 0 || b === 0) { + return a < b ? -1 : 1; + } + + if (a < 0 || b < 0) { + if (b >= 0) { + return -1; + } + + if (a >= 0) { + return 1; + } + + a = -a; + b = -b; + } + + var al = log10(a); + var bl = log10(b); + + var t = 0; + + if (al < bl) { + a *= POWERS_OF_TEN[bl - al - 1]; + b /= 10; + t = -1; + } else if (al > bl) { + b *= POWERS_OF_TEN[al - bl - 1]; + a /= 10; + t = 1; + } + + if (a === b) { + return t; + } + + return a < b ? -1 : 1; + } + + var aStr = String(a); + var bStr = String(b); + + if (aStr === bStr) { + return 0; + } + + return aStr < bStr ? -1 : 1; +} + +/** + * Compute minimum run length for TimSort + * + * @param {number} n - The size of the array to sort. + */ +function minRunLength(n) { + var r = 0; + + while (n >= DEFAULT_MIN_MERGE) { + r |= (n & 1); + n >>= 1; + } + + return n + r; +} + +/** + * Counts the length of a monotonically ascending or strictly monotonically + * descending sequence (run) starting at array[lo] in the range [lo, hi). If + * the run is descending it is made ascending. + * + * @param {array} array - The array to reverse. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + * @param {function} compare - Item comparison function. + * @return {number} - The length of the run. + */ +function makeAscendingRun(array, lo, hi, compare) { + var runHi = lo + 1; + + if (runHi === hi) { + return 1; + } + + // Descending + if (compare(array[runHi++], array[lo]) < 0) { + while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) { + runHi++; + } + + reverseRun(array, lo, runHi); + // Ascending + } else { + while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) { + runHi++; + } + } + + return runHi - lo; +} + +/** + * Reverse an array in the range [lo, hi). + * + * @param {array} array - The array to reverse. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + */ +function reverseRun(array, lo, hi) { + hi--; + + while (lo < hi) { + var t = array[lo]; + array[lo++] = array[hi]; + array[hi--] = t; + } +} + +/** + * Perform the binary sort of the array in the range [lo, hi) where start is + * the first element possibly out of order. + * + * @param {array} array - The array to sort. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + * @param {number} start - First element possibly out of order. + * @param {function} compare - Item comparison function. + */ +function binaryInsertionSort(array, lo, hi, start, compare) { + if (start === lo) { + start++; + } + + for (; start < hi; start++) { + var pivot = array[start]; + + // Ranges of the array where pivot belongs + var left = lo; + var right = start; + + /* + * pivot >= array[i] for i in [lo, left) + * pivot < array[i] for i in in [right, start) + */ + while (left < right) { + var mid = (left + right) >>> 1; + + if (compare(pivot, array[mid]) < 0) { + right = mid; + } else { + left = mid + 1; + } + } + + /* + * Move elements right to make room for the pivot. If there are elements + * equal to pivot, left points to the first slot after them: this is also + * a reason for which TimSort is stable + */ + var n = start - left; + // Switch is just an optimization for small arrays + switch (n) { + case 3: + array[left + 3] = array[left + 2]; + /* falls through */ + case 2: + array[left + 2] = array[left + 1]; + /* falls through */ + case 1: + array[left + 1] = array[left]; + break; + default: + while (n > 0) { + array[left + n] = array[left + n - 1]; + n--; + } + } + + array[left] = pivot; + } +} + +/** + * Find the position at which to insert a value in a sorted range. If the range + * contains elements equal to the value the leftmost element index is returned + * (for stability). + * + * @param {number} value - Value to insert. + * @param {array} array - The array in which to insert value. + * @param {number} start - First element in the range. + * @param {number} length - Length of the range. + * @param {number} hint - The index at which to begin the search. + * @param {function} compare - Item comparison function. + * @return {number} - The index where to insert value. + */ +function gallopLeft(value, array, start, length, hint, compare) { + var lastOffset = 0; + var maxOffset = 0; + var offset = 1; + + if (compare(value, array[start + hint]) > 0) { + maxOffset = length - hint; + + while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + lastOffset += hint; + offset += hint; + + // value <= array[start + hint] + } else { + maxOffset = hint + 1; + while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + var tmp = lastOffset; + lastOffset = hint - offset; + offset = hint - tmp; + } + + /* + * Now array[start+lastOffset] < value <= array[start+offset], so value + * belongs somewhere in the range (start + lastOffset, start + offset]. Do a + * binary search, with invariant array[start + lastOffset - 1] < value <= + * array[start + offset]. + */ + lastOffset++; + while (lastOffset < offset) { + var m = lastOffset + ((offset - lastOffset) >>> 1); + + if (compare(value, array[start + m]) > 0) { + lastOffset = m + 1; + + } else { + offset = m; + } + } + return offset; +} + +/** + * Find the position at which to insert a value in a sorted range. If the range + * contains elements equal to the value the rightmost element index is returned + * (for stability). + * + * @param {number} value - Value to insert. + * @param {array} array - The array in which to insert value. + * @param {number} start - First element in the range. + * @param {number} length - Length of the range. + * @param {number} hint - The index at which to begin the search. + * @param {function} compare - Item comparison function. + * @return {number} - The index where to insert value. + */ +function gallopRight(value, array, start, length, hint, compare) { + var lastOffset = 0; + var maxOffset = 0; + var offset = 1; + + if (compare(value, array[start + hint]) < 0) { + maxOffset = hint + 1; + + while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + var tmp = lastOffset; + lastOffset = hint - offset; + offset = hint - tmp; + + // value >= array[start + hint] + } else { + maxOffset = length - hint; + + while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + lastOffset += hint; + offset += hint; + } + + /* + * Now array[start+lastOffset] < value <= array[start+offset], so value + * belongs somewhere in the range (start + lastOffset, start + offset]. Do a + * binary search, with invariant array[start + lastOffset - 1] < value <= + * array[start + offset]. + */ + lastOffset++; + + while (lastOffset < offset) { + var m = lastOffset + ((offset - lastOffset) >>> 1); + + if (compare(value, array[start + m]) < 0) { + offset = m; + + } else { + lastOffset = m + 1; + } + } + + return offset; +} + +var TimSort = function TimSort(array, compare) { + this.array = array; + this.compare = compare; + this.minGallop = DEFAULT_MIN_GALLOPING; + this.length = array.length; + + this.tmpStorageLength = DEFAULT_TMP_STORAGE_LENGTH; + if (this.length < 2 * DEFAULT_TMP_STORAGE_LENGTH) { + this.tmpStorageLength = this.length >>> 1; + } + + this.tmp = new Array(this.tmpStorageLength); + + this.stackLength = + (this.length < 120 ? 5 : + this.length < 1542 ? 10 : + this.length < 119151 ? 19 : 40); + + this.runStart = new Array(this.stackLength); + this.runLength = new Array(this.stackLength); + this.stackSize = 0; +}; + +/** + * Push a new run on TimSort's stack. + * + * @param {number} runStart - Start index of the run in the original array. + * @param {number} runLength - Length of the run; + */ +TimSort.prototype.pushRun = function pushRun (runStart, runLength) { + this.runStart[this.stackSize] = runStart; + this.runLength[this.stackSize] = runLength; + this.stackSize += 1; +}; + +/** + * Merge runs on TimSort's stack so that the following holds for all i: + * 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1] + * 2) runLength[i - 2] > runLength[i - 1] + */ +TimSort.prototype.mergeRuns = function mergeRuns () { + var this$1 = this; + + while (this.stackSize > 1) { + var n = this$1.stackSize - 2; + + if ((n >= 1 && + this$1.runLength[n - 1] <= this$1.runLength[n] + this$1.runLength[n + 1]) || + (n >= 2 && + this$1.runLength[n - 2] <= this$1.runLength[n] + this$1.runLength[n - 1])) { + + if (this$1.runLength[n - 1] < this$1.runLength[n + 1]) { + n--; + } + + } else if (this$1.runLength[n] > this$1.runLength[n + 1]) { + break; + } + this$1.mergeAt(n); + } +}; + +/** + * Merge all runs on TimSort's stack until only one remains. + */ +TimSort.prototype.forceMergeRuns = function forceMergeRuns () { + var this$1 = this; + + while (this.stackSize > 1) { + var n = this$1.stackSize - 2; + + if (n > 0 && this$1.runLength[n - 1] < this$1.runLength[n + 1]) { + n--; + } + + this$1.mergeAt(n); + } +}; + +/** + * Merge the runs on the stack at positions i and i+1. Must be always be called + * with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack). + * + * @param {number} i - Index of the run to merge in TimSort's stack. + */ +TimSort.prototype.mergeAt = function mergeAt (i) { + var compare = this.compare; + var array = this.array; + + var start1 = this.runStart[i]; + var length1 = this.runLength[i]; + var start2 = this.runStart[i + 1]; + var length2 = this.runLength[i + 1]; + + this.runLength[i] = length1 + length2; + + if (i === this.stackSize - 3) { + this.runStart[i + 1] = this.runStart[i + 2]; + this.runLength[i + 1] = this.runLength[i + 2]; + } + + this.stackSize--; + + /* + * Find where the first element in the second run goes in run1. Previous + * elements in run1 are already in place + */ + var k = gallopRight(array[start2], array, start1, length1, 0, compare); + start1 += k; + length1 -= k; + + if (length1 === 0) { + return; + } + + /* + * Find where the last element in the first run goes in run2. Next elements + * in run2 are already in place + */ + length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare); + + if (length2 === 0) { + return; + } + + /* + * Merge remaining runs. A tmp array with length = min(length1, length2) is + * used + */ + if (length1 <= length2) { + this.mergeLow(start1, length1, start2, length2); + + } else { + this.mergeHigh(start1, length1, start2, length2); + } +}; + +/** + * Merge two adjacent runs in a stable way. The runs must be such that the + * first element of run1 is bigger than the first element in run2 and the + * last element of run1 is greater than all the elements in run2. + * The method should be called when run1.length <= run2.length as it uses + * TimSort temporary array to store run1. Use mergeHigh if run1.length > + * run2.length. + * + * @param {number} start1 - First element in run1. + * @param {number} length1 - Length of run1. + * @param {number} start2 - First element in run2. + * @param {number} length2 - Length of run2. + */ +TimSort.prototype.mergeLow = function mergeLow (start1, length1, start2, length2) { + + var compare = this.compare; + var array = this.array; + var tmp = this.tmp; + var i = 0; + + for (i = 0; i < length1; i++) { + tmp[i] = array[start1 + i]; + } + + var cursor1 = 0; + var cursor2 = start2; + var dest = start1; + + array[dest++] = array[cursor2++]; + + if (--length2 === 0) { + for (i = 0; i < length1; i++) { + array[dest + i] = tmp[cursor1 + i]; + } + return; + } + + if (length1 === 1) { + for (i = 0; i < length2; i++) { + array[dest + i] = array[cursor2 + i]; + } + array[dest + length2] = tmp[cursor1]; + return; + } + + var minGallop = this.minGallop; + + while (true) { + var count1 = 0; + var count2 = 0; + var exit = false; + + do { + if (compare(array[cursor2], tmp[cursor1]) < 0) { + array[dest++] = array[cursor2++]; + count2++; + count1 = 0; + + if (--length2 === 0) { + exit = true; + break; + } + + } else { + array[dest++] = tmp[cursor1++]; + count1++; + count2 = 0; + if (--length1 === 1) { + exit = true; + break; + } + } + } while ((count1 | count2) < minGallop); + + if (exit) { + break; + } + + do { + count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare); + + if (count1 !== 0) { + for (i = 0; i < count1; i++) { + array[dest + i] = tmp[cursor1 + i]; + } + + dest += count1; + cursor1 += count1; + length1 -= count1; + if (length1 <= 1) { + exit = true; + break; + } + } + + array[dest++] = array[cursor2++]; + + if (--length2 === 0) { + exit = true; + break; + } + + count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare); + + if (count2 !== 0) { + for (i = 0; i < count2; i++) { + array[dest + i] = array[cursor2 + i]; + } + + dest += count2; + cursor2 += count2; + length2 -= count2; + + if (length2 === 0) { + exit = true; + break; + } + } + array[dest++] = tmp[cursor1++]; + + if (--length1 === 1) { + exit = true; + break; + } + + minGallop--; + + } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); + + if (exit) { + break; + } + + if (minGallop < 0) { + minGallop = 0; + } + + minGallop += 2; + } + + this.minGallop = minGallop; + + if (minGallop < 1) { + this.minGallop = 1; + } + + if (length1 === 1) { + for (i = 0; i < length2; i++) { + array[dest + i] = array[cursor2 + i]; + } + array[dest + length2] = tmp[cursor1]; + + } else if (length1 === 0) { + throw new Error('mergeLow preconditions were not respected'); + + } else { + for (i = 0; i < length1; i++) { + array[dest + i] = tmp[cursor1 + i]; + } + } +}; + +/** + * Merge two adjacent runs in a stable way. The runs must be such that the + * first element of run1 is bigger than the first element in run2 and the + * last element of run1 is greater than all the elements in run2. + * The method should be called when run1.length > run2.length as it uses + * TimSort temporary array to store run2. Use mergeLow if run1.length <= + * run2.length. + * + * @param {number} start1 - First element in run1. + * @param {number} length1 - Length of run1. + * @param {number} start2 - First element in run2. + * @param {number} length2 - Length of run2. + */ +TimSort.prototype.mergeHigh = function mergeHigh (start1, length1, start2, length2) { + var compare = this.compare; + var array = this.array; + var tmp = this.tmp; + var i = 0; + + for (i = 0; i < length2; i++) { + tmp[i] = array[start2 + i]; + } + + var cursor1 = start1 + length1 - 1; + var cursor2 = length2 - 1; + var dest = start2 + length2 - 1; + var customCursor = 0; + var customDest = 0; + + array[dest--] = array[cursor1--]; + + if (--length1 === 0) { + customCursor = dest - (length2 - 1); + + for (i = 0; i < length2; i++) { + array[customCursor + i] = tmp[i]; + } + + return; + } + + if (length2 === 1) { + dest -= length1; + cursor1 -= length1; + customDest = dest + 1; + customCursor = cursor1 + 1; + + for (i = length1 - 1; i >= 0; i--) { + array[customDest + i] = array[customCursor + i]; + } + + array[dest] = tmp[cursor2]; + return; + } + + var minGallop = this.minGallop; + + while (true) { + var count1 = 0; + var count2 = 0; + var exit = false; + + do { + if (compare(tmp[cursor2], array[cursor1]) < 0) { + array[dest--] = array[cursor1--]; + count1++; + count2 = 0; + if (--length1 === 0) { + exit = true; + break; + } + + } else { + array[dest--] = tmp[cursor2--]; + count2++; + count1 = 0; + if (--length2 === 1) { + exit = true; + break; + } + } + + } while ((count1 | count2) < minGallop); + + if (exit) { + break; + } + + do { + count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare); + + if (count1 !== 0) { + dest -= count1; + cursor1 -= count1; + length1 -= count1; + customDest = dest + 1; + customCursor = cursor1 + 1; + + for (i = count1 - 1; i >= 0; i--) { + array[customDest + i] = array[customCursor + i]; + } + + if (length1 === 0) { + exit = true; + break; + } + } + + array[dest--] = tmp[cursor2--]; + + if (--length2 === 1) { + exit = true; + break; + } + + count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare); + + if (count2 !== 0) { + dest -= count2; + cursor2 -= count2; + length2 -= count2; + customDest = dest + 1; + customCursor = cursor2 + 1; + + for (i = 0; i < count2; i++) { + array[customDest + i] = tmp[customCursor + i]; + } + + if (length2 <= 1) { + exit = true; + break; + } + } + + array[dest--] = array[cursor1--]; + + if (--length1 === 0) { + exit = true; + break; + } + + minGallop--; + + } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); + + if (exit) { + break; + } + + if (minGallop < 0) { + minGallop = 0; + } + + minGallop += 2; + } + + this.minGallop = minGallop; + + if (minGallop < 1) { + this.minGallop = 1; + } + + if (length2 === 1) { + dest -= length1; + cursor1 -= length1; + customDest = dest + 1; + customCursor = cursor1 + 1; + + for (i = length1 - 1; i >= 0; i--) { + array[customDest + i] = array[customCursor + i]; + } + + array[dest] = tmp[cursor2]; + + } else if (length2 === 0) { + throw new Error('mergeHigh preconditions were not respected'); + + } else { + customCursor = dest - (length2 - 1); + for (i = 0; i < length2; i++) { + array[customCursor + i] = tmp[i]; + } + } +}; + +/** + * Sort an array in the range [lo, hi) using TimSort. + * + * @param {array} array - The array to sort. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + * @param {function=} compare - Item comparison function. Default is alphabetical. + */ +function sort (array, lo, hi, compare) { + if (!Array.isArray(array)) { + throw new TypeError('Can only sort arrays'); + } + + /* + * Handle the case where a comparison function is not provided. We do + * lexicographic sorting + */ + + if (lo === undefined) { + lo = 0; + } + + if (hi === undefined) { + hi = array.length; + } + + if (compare === undefined) { + compare = alphabeticalCompare; + } + + var remaining = hi - lo; + + // The array is already sorted + if (remaining < 2) { + return; + } + + var runLength = 0; + // On small arrays binary sort can be used directly + if (remaining < DEFAULT_MIN_MERGE) { + runLength = makeAscendingRun(array, lo, hi, compare); + binaryInsertionSort(array, lo, hi, lo + runLength, compare); + return; + } + + var ts = new TimSort(array, compare); + + var minRun = minRunLength(remaining); + + do { + runLength = makeAscendingRun(array, lo, hi, compare); + if (runLength < minRun) { + var force = remaining; + if (force > minRun) { + force = minRun; + } + + binaryInsertionSort(array, lo, lo + force, lo + runLength, compare); + runLength = force; + } + // Push new run and merge if necessary + ts.pushRun(lo, runLength); + ts.mergeRuns(); + + // Go find next run + remaining -= runLength; + lo += runLength; + + } while (remaining !== 0); + + // Force merging of remaining runs + ts.forceMergeRuns(); +} + +var FixedArray = function FixedArray(size) { + this._count = 0; + this._data = new Array(size); +}; + +var prototypeAccessors = { length: {},data: {} }; + +FixedArray.prototype._resize = function _resize (size) { + var this$1 = this; + + if (size > this._data.length) { + for (var i = this._data.length; i < size; ++i) { + this$1._data[i] = undefined; + } + } +}; + +prototypeAccessors.length.get = function () { + return this._count; +}; + +prototypeAccessors.data.get = function () { + return this._data; +}; + +FixedArray.prototype.reset = function reset () { + var this$1 = this; + + for (var i = 0; i < this._count; ++i) { + this$1._data[i] = undefined; + } + + this._count = 0; +}; + +FixedArray.prototype.push = function push (val) { + if (this._count >= this._data.length) { + this._resize(this._data.length * 2); + } + + this._data[this._count] = val; + ++this._count; +}; + +FixedArray.prototype.pop = function pop () { + --this._count; + + if (this._count < 0) { + this._count = 0; + } + + var ret = this._data[this._count]; + this._data[this._count] = undefined; + + return ret; +}; + +FixedArray.prototype.fastRemove = function fastRemove (idx) { + if (idx >= this._count) { + return; + } + + var last = this._count - 1; + this._data[idx] = this._data[last]; + this._data[last] = undefined; + this._count -= 1; +}; + +FixedArray.prototype.indexOf = function indexOf (val) { + var idx = this._data.indexOf(val); + if (idx >= this._count) { + return -1; + } + + return idx; +}; + +FixedArray.prototype.sort = function sort$1 (cmp) { + return sort(this._data, 0, this._count, cmp); +}; + +Object.defineProperties( FixedArray.prototype, prototypeAccessors ); + +var Pool = function Pool(fn, size) { + var this$1 = this; + + this._fn = fn; + this._idx = size - 1; + this._frees = new Array(size); + + for (var i = 0; i < size; ++i) { + this$1._frees[i] = fn(); + } +}; + +Pool.prototype._expand = function _expand (size) { + var this$1 = this; + + var old = this._frees; + this._frees = new Array(size); + + var len = size - old.length; + for (var i = 0; i < len; ++i) { + this$1._frees[i] = this$1._fn(); + } + + for (var i$1 = len, j = 0; i$1 < size; ++i$1, ++j) { + this$1._frees[i$1] = old[j]; + } + + this._idx += len; +}; + +Pool.prototype.alloc = function alloc () { + // create some more space (expand by 20%, minimum 1) + if (this._idx < 0) { + this._expand(Math.round(this._frees.length * 1.2) + 1); + } + + var ret = this._frees[this._idx]; + this._frees[this._idx] = null; + --this._idx; + + return ret; +}; + +Pool.prototype.free = function free (obj) { + ++this._idx; + this._frees[this._idx] = obj; +}; + +// NOTE: you must have `_prev` and `_next` field in the object returns by `fn` + +var LinkedArray = function LinkedArray(fn, size) { + this._fn = fn; + this._count = 0; + this._head = null; + this._tail = null; + + this._pool = new Pool(fn, size); +}; + +var prototypeAccessors$1 = { head: {},tail: {},length: {} }; + +prototypeAccessors$1.head.get = function () { + return this._head; +}; + +prototypeAccessors$1.tail.get = function () { + return this._tail; +}; + +prototypeAccessors$1.length.get = function () { + return this._count; +}; + +LinkedArray.prototype.add = function add () { + var node = this._pool.alloc(); + + if (!this._tail) { + this._head = node; + } else { + this._tail._next = node; + node._prev = this._tail; + } + this._tail = node; + this._count += 1; + + return node; +}; + +LinkedArray.prototype.remove = function remove (node) { + if (node._prev) { + node._prev._next = node._next; + } else { + this._head = node._next; + } + + if (node._next) { + node._next._prev = node._prev; + } else { + this._tail = node._prev; + } + + node._next = null; + node._prev = null; + this._pool.free(node); + this._count -= 1; +}; + +LinkedArray.prototype.forEach = function forEach (fn, binder) { + var this$1 = this; + + var cursor = this._head; + if (!cursor) { + return; + } + + if (binder) { + fn = fn.bind(binder); + } + + var idx = 0; + var next = cursor; + + while (cursor) { + next = cursor._next; + fn(cursor, idx, this$1); + + cursor = next; + ++idx; + } +}; + +Object.defineProperties( LinkedArray.prototype, prototypeAccessors$1 ); + +var RecyclePool = function RecyclePool(fn, size) { + var this$1 = this; + + this._fn = fn; + this._count = 0; + this._data = new Array(size); + + for (var i = 0; i < size; ++i) { + this$1._data[i] = fn(); + } +}; + +var prototypeAccessors$2 = { length: {},data: {} }; + +prototypeAccessors$2.length.get = function () { + return this._count; +}; + +prototypeAccessors$2.data.get = function () { + return this._data; +}; + +RecyclePool.prototype.reset = function reset () { + this._count = 0; +}; + +RecyclePool.prototype.resize = function resize (size) { + var this$1 = this; + + if (size > this._data.length) { + for (var i = this._data.length; i < size; ++i) { + this$1._data[i] = this$1._fn(); + } + } +}; + +RecyclePool.prototype.add = function add () { + if (this._count >= this._data.length) { + this.resize(this._data.length * 2); + } + + return this._data[this._count++]; +}; + +RecyclePool.prototype.remove = function remove (idx) { + if (idx >= this._count) { + return; + } + + var last = this._count - 1; + var tmp = this._data[idx]; + this._data[idx] = this._data[last]; + this._data[last] = tmp; + this._count -= 1; +}; + +RecyclePool.prototype.sort = function sort$1 (cmp) { + return sort(this._data, 0, this._count, cmp); +}; + +Object.defineProperties( RecyclePool.prototype, prototypeAccessors$2 ); + +var _bufferPools = Array(8); +for (var i = 0; i < 8; ++i) { + _bufferPools[i] = []; +} + +// Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + +/** + * BaseRenderData is a core data abstraction for renderer, this is a abstract class. + * An inherited render data type should define raw vertex datas. + * User should also define the effect, vertex count and index count. + */ +var BaseRenderData = function BaseRenderData () { + this.material = null; + this.vertexCount = 0; + this.indiceCount = 0; +}; + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var _pool; +var _dataPool = new Pool(function () { + return { + x: 0.0, + y: 0.0, + u: 0.0, + v: 0.0, + color: 0 + }; +}, 128); + +/** + * RenderData is most widely used render data type. + * It describes raw vertex data with a fixed data layout. + * Each vertex is described by five property: x, y, u, v, color. The data layout might be extended in the future. + * Vertex data objects are managed automatically by RenderData, user only need to set the dataLength property. + * User can also define rendering index orders for the vertex list. + */ +var RenderData = (function (BaseRenderData$$1) { + function RenderData () { + BaseRenderData$$1.call(this); + this._data = []; + this._indices = []; + + this._pivotX = 0; + this._pivotY = 0; + this._width = 0; + this._height = 0; + + this.uvDirty = true; + this.vertDirty = true; + } + + if ( BaseRenderData$$1 ) RenderData.__proto__ = BaseRenderData$$1; + RenderData.prototype = Object.create( BaseRenderData$$1 && BaseRenderData$$1.prototype ); + RenderData.prototype.constructor = RenderData; + + var prototypeAccessors = { type: {},dataLength: {} }; + + prototypeAccessors.type.get = function () { + return RenderData.type; + }; + + prototypeAccessors.dataLength.get = function () { + return this._data.length; + }; + + prototypeAccessors.dataLength.set = function (length) { + var data = this._data; + if (data.length !== length) { + // Free extra data + for (var i = length; i < data.length; i++) { + _dataPool.free(data[i]); + } + // Alloc needed data + for (var i$1 = data.length; i$1 < length; i$1++) { + data[i$1] = _dataPool.alloc(); + } + data.length = length; + } + }; + + RenderData.prototype.updateSizeNPivot = function updateSizeNPivot (width, height, pivotX, pivotY) { + if (width !== this._width || + height !== this._height || + pivotX !== this._pivotX || + pivotY !== this._pivotY) + { + this._width = width; + this._height = height; + this._pivotX = pivotX; + this._pivotY = pivotY; + this.vertDirty = true; + } + }; + + RenderData.alloc = function alloc () { + return _pool.alloc(); + }; + + RenderData.free = function free (data) { + if (data instanceof RenderData) { + for (var i = data.length-1; i > 0; i--) { + _dataPool.free(data._data[i]); + } + data._data.length = 0; + data._indices.length = 0; + data.material = null; + data.uvDirty = true; + data.vertDirty = true; + data.vertexCount = 0; + data.indiceCount = 0; + _pool.free(data); + } + }; + + Object.defineProperties( RenderData.prototype, prototypeAccessors ); + + return RenderData; +}(BaseRenderData)); + +RenderData.type = 'RenderData'; + +_pool = new Pool(function () { + return new RenderData(); +}, 32); + +// Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + +/** + * IARenderData is user customized render data type, user should provide the entier input assembler. + * IARenderData just defines a property `ia` for accessing the input assembler. + * It doesn't manage memory so users should manage the memory of input assembler by themselves. + */ +var IARenderData = (function (BaseRenderData$$1) { + function IARenderData () { + BaseRenderData$$1.call(this); + this.ia = null; + } + + if ( BaseRenderData$$1 ) IARenderData.__proto__ = BaseRenderData$$1; + IARenderData.prototype = Object.create( BaseRenderData$$1 && BaseRenderData$$1.prototype ); + IARenderData.prototype.constructor = IARenderData; + + var prototypeAccessors = { type: {} }; + + prototypeAccessors.type.get = function () { + return IARenderData.type; + }; + + Object.defineProperties( IARenderData.prototype, prototypeAccessors ); + + return IARenderData; +}(BaseRenderData)); + +IARenderData.type = 'IARenderData'; + +var gfx = window.gfx; + +var renderer = window.renderer; + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var BASE = 255; +var NOISE_SCALE = 10000; +var POS_SCALE = 1; +var LIFE_SCALE = 100; +var COLOR_SCALE = 1; +var ROTATION_SCALE = 1; +var MAX_SCALE = 500; +var _vertexFmt = new gfx.VertexFormat([ + { name: 'a_quad', type: gfx.ATTR_TYPE_FLOAT32, num: 2 } +]); + +var _dataOpts = { + width: 0, + height: 0, + minFilter: gfx.FILTER_NEAREST, + magFilter: gfx.FILTER_NEAREST, + wrapS: gfx.WRAP_CLAMP, + wrapT: gfx.WRAP_CLAMP, + format: gfx.TEXTURE_FMT_RGBA8, + images: [] +}; + +function encode (value, scale, outArr, offset) { + value = value * scale + BASE * BASE / 2; + outArr[offset] = Math.floor((value % BASE) / BASE * 255); + outArr[offset+1] = Math.floor(Math.floor(value / BASE) / BASE * 255); +} + +function decode (arr, offset, scale) { + return (((arr[offset] / 255) * BASE + + (arr[offset+1] / 255) * BASE * BASE) - BASE * BASE / 2) / scale; +} + +function clampf (value, min_inclusive, max_inclusive) { + return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive; +} + +var Particles = function Particles (device, renderer$$1, config) { + this._device = device; + this._config = config; + this._sizeScale = 1; + this._accelScale = 1; + this._radiusScale = 1; + + var opts = {}; + var programLib = renderer$$1._programLib; + this.programs = { + emitter: programLib.getProgram('vfx_emitter', opts), + update: programLib.getProgram('vfx_update', opts), + quad: programLib.getProgram('vfx_quad', opts), + }; + + this.textures = { + // need swap + state0: new gfx.Texture2D(device, opts), + state1: new gfx.Texture2D(device, opts), + // no swap needed + noise: new gfx.Texture2D(device, opts), + quads: new gfx.Texture2D(device, opts), + }; + + this.framebuffers = { + state0: new gfx.FrameBuffer(device, 0, 0, { + colors: [this.textures.state0] + }), + state1: new gfx.FrameBuffer(device, 0, 0, { + colors: [this.textures.state1] + }), + quads: new gfx.FrameBuffer(device, 0, 0, { + colors: [this.textures.quads] + }) + }; + + var verts = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]); + var indices = new Uint8Array([ 0, 1, 2, 1, 3, 2]); + this.buffers = { + updateVB: new gfx.VertexBuffer(device, _vertexFmt, gfx.USAGE_STATIC, verts, 4), + updateIB: new gfx.IndexBuffer(device, gfx.INDEX_FMT_UINT8, gfx.USAGE_STATIC, indices, 6), + indexes: null, + particleCache: null + }; + + this._elapsed = 0; + this._stopped = false; + + this.updateMaxParticle(config); + this.updateSizeScale(config); + this.updateRadiusScale(config); + this.updateAccelScale(config); + + // Vector uniforms + this._pos = new Float32Array([config.sourcePos.x, config.sourcePos.y]); + this._posVar = new Float32Array([config.posVar.x, config.posVar.y]); + this._gravity = new Float32Array([config.gravity.x, config.gravity.y]); + this._color = new Float32Array([config.startColor.r, config.startColor.g, config.startColor.b, config.startColor.a]); + this._colorVar = new Float32Array([config.startColorVar.r, config.startColorVar.g, config.startColorVar.b, config.startColorVar.a]); + this._endColor = new Float32Array([config.endColor.r, config.endColor.g, config.endColor.b, config.endColor.a]); + this._endColorVar = new Float32Array([config.endColorVar.r, config.endColorVar.g, config.endColorVar.b, config.endColorVar.a]); +}; + +var prototypeAccessors$3 = { vertexFormat: {},particleCount: {},stopped: {},pos: {},posVar: {},gravity: {},startColor: {},startColorVar: {},endColor: {},endColorVar: {} }; + +prototypeAccessors$3.vertexFormat.get = function () { + return _vertexFmt; +}; + +// TODO: it's too slow, need other approach to retrieve the real particle count +prototypeAccessors$3.particleCount.get = function () { + var particleCount = 0; + var device = this._device; + device.setFrameBuffer(this.framebuffers.state0); + var w = this.statesize[0], h = this.statesize[1], + tw = this._tw, th = this._th, + rgba = this.buffers.particleCache; + device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); + for (var y = 0; y < th; y++) { + for (var x = 0; x < tw; x++) { + var offset = y * 3 * tw * 12 + x * 12; + var rest = decode(rgba, offset, LIFE_SCALE); + if (rest > 0) { + particleCount++; + } + } + } + return particleCount; +}; + +prototypeAccessors$3.stopped.get = function () { + return this._stopped; +}; + +Particles.prototype.updateMaxParticle = function updateMaxParticle (config) { + var emissionMax = Math.floor(config.emissionRate * (config.life + config.lifeVar)); + var maxParticle; + if (config.totalParticles > emissionMax) { + maxParticle = emissionMax; + this._emitVar = config.lifeVar; + } + else { + maxParticle = config.totalParticles; + this._emitVar = 0; + } + if (maxParticle !== this._maxParticle) { + this._maxParticle = maxParticle; + this._tw = Math.ceil(Math.sqrt(maxParticle)); + this._th = Math.floor(Math.sqrt(maxParticle)); + this.initTextures(); + this.initBuffers(); + } +}; + +prototypeAccessors$3.pos.set = function (pos) { + this._pos[0] = pos.x; + this._pos[1] = pos.y; +}; + +prototypeAccessors$3.posVar.set = function (posVar) { + this._posVar[0] = posVar.x; + this._posVar[1] = posVar.y; +}; + +prototypeAccessors$3.gravity.set = function (gravity) { + this._gravity[0] = gravity.x; + this._gravity[1] = gravity.y; +}; + +prototypeAccessors$3.startColor.set = function (color) { + this._color[0] = color.r; + this._color[1] = color.g; + this._color[2] = color.b; + this._color[3] = color.a; +}; + +prototypeAccessors$3.startColorVar.set = function (color) { + this._colorVar[0] = color.r; + this._colorVar[1] = color.g; + this._colorVar[2] = color.b; + this._colorVar[3] = color.a; +}; + +prototypeAccessors$3.endColor.set = function (color) { + this._endColor[0] = color.r; + this._endColor[1] = color.g; + this._endColor[2] = color.b; + this._endColor[3] = color.a; +}; + +prototypeAccessors$3.endColorVar.set = function (color) { + this._endColorVar[0] = color.r; + this._endColorVar[1] = color.g; + this._endColorVar[2] = color.b; + this._endColorVar[3] = color.a; +}; + +Particles.prototype._updateTex = function _updateTex (tex, data, width, height) { + _dataOpts.images.length = 1; + _dataOpts.images[0] = data; + _dataOpts.width = width; + _dataOpts.height = height; + tex.update(_dataOpts); +}; + +Particles.prototype._initNoise = function _initNoise () { + var tw = this._tw, th = this._th; + var w = (tw + 1) * 3, h = (th + 1) * 3; + var data = new Uint8Array(w * h * 4); + var offset = 0; + for (var y = 0; y < h; y++) { + for (var x = 0; x < w; x++) { + encode(Math.random(), NOISE_SCALE, data, offset); + encode(Math.random(), NOISE_SCALE, data, offset + 2); + offset += 4; + } + } + this._noisesize = new Float32Array([w, h]); + this._updateTex(this.textures.noise, data, w, h); +}; + +Particles.prototype.initTextures = function initTextures () { + var tw = this._tw, th = this._th; + this.statesize = new Float32Array([tw * 3, th * 3]); + this.quadsize = new Float32Array([tw * 2, th * 2]); + var data = new Uint8Array(tw * 3 * th * 3 * 4); + // decode([97, 97], 0, LIFE_SCALE); equals to -128, just for initalize a negative value in life + data.fill(97); + this._updateTex(this.textures.state0, data, tw * 3, th * 3); + this._updateTex(this.textures.state1, data, tw * 3, th * 3); + this._updateTex(this.textures.quads, null, tw * 2, th * 2); + this._initNoise(); +}; + +Particles.prototype.initBuffers = function initBuffers () { + var w = this.quadsize[0], h = this.quadsize[1], + indexes = new Float32Array(w * h * 2), + i = 0; + for (var y = 0; y < h; y++) { + for (var x = 0; x < w; x++) { + indexes[i + 0] = x; + indexes[i + 1] = y; + i += 2; + } + } + this.buffers.indexes = indexes; + this.buffers.particleCache = new Uint8Array(this.statesize[0] * this.statesize[1] * 4); +}; + +Particles.prototype.updateSizeScale = function updateSizeScale (config) { + var size = config.startSize, + sizeVar = config.startSizeVar, + endSize = config.endSize, + endSizeVar = config.endSizeVar; + var scale = Math.floor(Math.pow(BASE, 2) / Math.max(size + sizeVar, endSize + endSizeVar)); + this._sizeScale = clampf(scale, 1, MAX_SCALE); +}; + +Particles.prototype.updateAccelScale = function updateAccelScale (config) { + var radial = config.radialAccel, + radialVar = config.radialAccelVar, + tangential = config.tangentialAccel, + tangentialVar = config.tangentialAccelVar; + var accelScale = Math.floor(Math.pow(BASE, 2) / Math.max(Math.abs(radial) + radialVar, Math.abs(tangential) + tangentialVar) / 2); + this._accelScale = clampf(accelScale, 1, MAX_SCALE); +}; + +Particles.prototype.updateRadiusScale = function updateRadiusScale (config) { + var radius = config.startRadius, + radiusVar = config.startRadiusVar, + endRadius = config.endRadius, + endRadiusVar = config.endRadiusVar; + var scale = Math.floor(Math.pow(BASE, 2) / Math.max(Math.abs(radius) + radiusVar, Math.abs(endRadius) + endRadiusVar)); + this._radiusScale = clampf(scale, 1, MAX_SCALE); +}; + +Particles.prototype.resetSystem = function resetSystem () { + this._stopped = false; +}; + +Particles.prototype.stopSystem = function stopSystem () { + this._stopped = true; +}; + +Particles.prototype.getState = function getState (framebuffer) { + var this$1 = this; + + var device = this._device; + device.setFrameBuffer(framebuffer); + var w = this.statesize[0], h = this.statesize[1], + tw = this._tw, th = this._th, + rgba = new Uint8Array(w * h * 4); + device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); + var particles = []; + for (var y = 0; y < th; y++) { + for (var x = 0; x < tw; x++) { + var offset = y * 3 * tw * 12 + x * 12; + var colorI = offset + 1 * 4; + var deltaRGI = offset + 2 * 4; + var deltaBAI = offset + tw * 12; + var sizeI = offset + tw * 12 + 1 * 4; + var rotI = offset + tw * 12 + 2 * 4; + var control1I = offset + 2 * tw * 12; + var control2I = offset + 2 * tw * 12 + 1 * 4; + var posI = offset + 2 * tw * 12 + 2 * 4; + + var rest = decode(rgba, offset, LIFE_SCALE); + var life = decode(rgba, offset + 2, LIFE_SCALE); + var color = { + r: rgba[colorI], + g: rgba[colorI+1], + b: rgba[colorI+2], + a: rgba[colorI+3] + }; + var deltaColor = { + r: decode(rgba, deltaRGI, COLOR_SCALE), + g: decode(rgba, deltaRGI + 2, COLOR_SCALE), + b: decode(rgba, deltaBAI, COLOR_SCALE), + a: decode(rgba, deltaBAI + 2, COLOR_SCALE) + }; + var size = decode(rgba, sizeI, this$1._sizeScale); + var deltaSize = decode(rgba, sizeI + 2, this$1._sizeScale); + var rot = decode(rgba, rotI, ROTATION_SCALE); + var deltaRot = decode(rgba, rotI + 2, ROTATION_SCALE); + var control = (void 0); + if (this$1._config.emitterMode === 0) { + control = [ + decode(rgba, control1I, POS_SCALE), + decode(rgba, control1I + 2, POS_SCALE), + decode(rgba, control2I, this$1._accelScale), + decode(rgba, control2I + 2, this$1._accelScale) + ]; + } + else { + control = [ + decode(rgba, control1I, ROTATION_SCALE), + decode(rgba, control1I + 2, this$1._radiusScale), + decode(rgba, control2I, ROTATION_SCALE), + decode(rgba, control2I + 2, this$1._radiusScale) + ]; + } + var pos = { + x: decode(rgba, posI, POS_SCALE), + y: decode(rgba, posI + 2, POS_SCALE) + }; + particles.push({ + rest: rest, + life: life, + color: color, + deltaColor: deltaColor, + size: size, + deltaSize: deltaSize, + rot: rot, + deltaRot: deltaRot, + control: control, + pos: pos + }); + } + } + return particles; +}; + +Particles.prototype.getNoise = function getNoise () { + var device = this._device; + var framebuffer = new gfx.FrameBuffer(device, 0, 0, { + colors: [this.textures.noise] + }); + device.setFrameBuffer(framebuffer); + var w = this._noisesize[0], h = this._noisesize[1], + rgba = new Uint8Array(w * h * 4); + device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); + var noises = []; + var offset = 0; + for (var y = 0; y < h; y++) { + for (var x = 0; x < w; x++) { + noises.push(decode(rgba, offset, 10000)); + noises.push(decode(rgba, offset+2, 10000)); + offset += 4; + } + } + return noises; +}; + +Particles.prototype.getQuads = function getQuads () { + var device = this._device; + var framebuffer = new gfx.FrameBuffer(device, 0, 0, { + colors: [this.textures.quads] + }); + device.setFrameBuffer(framebuffer); + var w = this.quadsize[0], h = this.quadsize[1], + rgba = new Uint8Array(w * h * 4); + device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); + var quads = []; + var off1 = 0, off2 = 0; + for (var y = 0; y < h; y += 2) { + for (var x = 0; x < w; x += 2) { + off1 = (y * w + x) * 4; + off2 = ((y + 1) * w + x) * 4; + quads.push([ + decode(rgba, off1, POS_SCALE), + decode(rgba, off1+2, POS_SCALE), + decode(rgba, off1+4, POS_SCALE), + decode(rgba, off1+6, POS_SCALE), + decode(rgba, off2, POS_SCALE), + decode(rgba, off2+2, POS_SCALE), + decode(rgba, off2+4, POS_SCALE), + decode(rgba, off2+6, POS_SCALE) + ]); + } + } + return quads; +}; + +Particles.prototype.step = function step (dt) { + var config = this._config; + var device = this._device; + + // setup + device.setViewport(0, 0, this.statesize[0], this.statesize[1]); + + // Emitter + device.setFrameBuffer(this.framebuffers.state1); + device.setTexture('noise', this.textures.noise, 0); + device.setTexture('state', this.textures.state0, 1); + device.setUniform('statesize', this.statesize); + device.setUniform('noisesize', this._noisesize); + device.setUniform('stopped', this._stopped); + device.setUniform('dt', dt); + device.setUniform('mode', config.emitterMode); + device.setUniform('noiseId', Math.floor(Math.random() * 16)); + device.setUniform('emitVar', this._emitVar); + device.setUniform('life', config.life); + device.setUniform('lifeVar', config.lifeVar); + device.setUniform('pos', this._pos); + device.setUniform('posVar', this._posVar); + device.setUniform('color', this._color); + device.setUniform('colorVar', this._colorVar); + device.setUniform('endColor', this._endColor); + device.setUniform('endColorVar', this._endColorVar); + device.setUniform('size', config.startSize); + device.setUniform('sizeVar', config.startSizeVar); + device.setUniform('endSize', config.endSize); + device.setUniform('endSizeVar', config.endSizeVar); + device.setUniform('rot', config.startSpin); + device.setUniform('rotVar', config.startSpinVar); + device.setUniform('endRot', config.endSpin); + device.setUniform('endRotVar', config.endSpinVar); + device.setUniform('angle', config.angle); + device.setUniform('angleVar', config.angleVar); + device.setUniform('speed', config.speed); + device.setUniform('speedVar', config.speedVar); + device.setUniform('radial', config.radialAccel); + device.setUniform('radialVar', config.radialAccelVar); + device.setUniform('tangent', config.tangentialAccel); + device.setUniform('tangentVar', config.tangentialAccelVar); + device.setUniform('radius', config.startRadius); + device.setUniform('radiusVar', config.startRadiusVar); + device.setUniform('endRadius', config.endRadius); + device.setUniform('endRadiusVar', config.endRadiusVar); + device.setUniform('rotatePS', config.rotatePerS); + device.setUniform('rotatePSVar', config.rotatePerSVar); + device.setUniform('sizeScale', this._sizeScale); + device.setUniform('accelScale', this._accelScale); + device.setUniform('radiusScale', this._radiusScale); + device.setVertexBuffer(0, this.buffers.updateVB); + device.setIndexBuffer(this.buffers.updateIB); + device.setProgram(this.programs.emitter); + device.draw(0, this.buffers.updateIB.count); + + // Update + device.setFrameBuffer(this.framebuffers.state0); + device.setTexture('state', this.textures.state1, 0); + device.setUniform('statesize', this.statesize); + device.setUniform('dt', dt); + device.setUniform('mode', config.emitterMode); + device.setUniform('gravity', this._gravity); + device.setUniform('sizeScale', this._sizeScale); + device.setUniform('accelScale', this._accelScale); + device.setUniform('radiusScale', this._radiusScale); + device.setVertexBuffer(0, this.buffers.updateVB); + device.setIndexBuffer(this.buffers.updateIB); + device.setProgram(this.programs.update); + device.draw(0, this.buffers.updateIB.count); + + // Draw quad + device.setViewport(0, 0, this._tw * 2, this._th * 2); + device.setFrameBuffer(this.framebuffers.quads); + device.setTexture('state', this.textures.state0, 0); + device.setUniform('quadsize', this.quadsize); + device.setUniform('statesize', this.statesize); + device.setUniform('sizeScale', this._sizeScale); + device.setVertexBuffer(0, this.buffers.updateVB); + device.setIndexBuffer(this.buffers.updateIB); + device.setProgram(this.programs.quad); + device.draw(0, this.buffers.updateIB.count); + + this._elapsed += dt; + if (config.duration !== -1 && config.duration < this._elapsed) { + this.stopSystem(); + } +}; + +Object.defineProperties( Particles.prototype, prototypeAccessors$3 ); + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var Asset = function Asset(persist) { + if ( persist === void 0 ) persist = true; + + this._loaded = false; + this._persist = persist; +}; + +Asset.prototype.unload = function unload () { + this._loaded = false; +}; + +Asset.prototype.reload = function reload () { + // TODO +}; + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var Texture = (function (Asset$$1) { + function Texture(persist) { + if ( persist === void 0 ) persist = true; + + Asset$$1.call(this, persist); + + this._texture = null; + } + + if ( Asset$$1 ) Texture.__proto__ = Asset$$1; + Texture.prototype = Object.create( Asset$$1 && Asset$$1.prototype ); + Texture.prototype.constructor = Texture; + + Texture.prototype.getImpl = function getImpl () { + return this._texture; + }; + + Texture.prototype.getId = function getId () {}; + + Texture.prototype.destroy = function destroy () { + this._texture && this._texture.destroy(); + }; + + return Texture; +}(Asset)); + +/** + * JS Implementation of MurmurHash2 + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} str ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ + +function murmurhash2_32_gc(str, seed) { + var + l = str.length, + h = seed ^ l, + i = 0, + k; + + while (l >= 4) { + k = + ((str.charCodeAt(i) & 0xff)) | + ((str.charCodeAt(++i) & 0xff) << 8) | + ((str.charCodeAt(++i) & 0xff) << 16) | + ((str.charCodeAt(++i) & 0xff) << 24); + + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k ^= k >>> 24; + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; + + l -= 4; + ++i; + } + + switch (l) { + case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; + case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; + case 1: h ^= (str.charCodeAt(i) & 0xff); + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + } + + h ^= h >>> 13; + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + h ^= h >>> 15; + + return h >>> 0; +} + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +// function genHashCode (str) { +// var hash = 0; +// if (str.length == 0) { +// return hash; +// } +// for (var i = 0; i < str.length; i++) { +// var char = str.charCodeAt(i); +// hash = ((hash<<5)-hash)+char; +// hash = hash & hash; // Convert to 32bit integer +// } +// return hash; +// } + +function serializeDefines (defines) { + var str = ''; + for (var i = 0; i < defines.length; i++) { + str += defines[i].name + defines[i].value; + } + return str; +} + +function serializePass (pass) { + var str = pass._programName + pass._cullMode; + if (pass._blend) { + str += pass._blendEq + pass._blendAlphaEq + pass._blendSrc + pass._blendDst + + pass._blendSrcAlpha + pass._blendDstAlpha + pass._blendColor; + } + if (pass._depthTest) { + str += pass._depthWrite + pass._depthFunc; + } + if (pass._stencilTest) { + str += pass._stencilFuncFront + pass._stencilRefFront + pass._stencilMaskFront + + pass._stencilFailOpFront + pass._stencilZFailOpFront + pass._stencilZPassOpFront + + pass._stencilWriteMaskFront + + pass._stencilFuncBack + pass._stencilRefBack + pass._stencilMaskBack + + pass._stencilFailOpBack + pass._stencilZFailOpBack + pass._stencilZPassOpBack + + pass._stencilWriteMaskBack; + } + return str; +} + +function computeHash(material) { + var effect = material._effect; + var hashData = ''; + if (effect) { + var i, j, techData, param, prop, propKey; + + // effect._defines + hashData += serializeDefines(effect._defines); + // effect._techniques + for (i = 0; i < effect._techniques.length; i++) { + techData = effect._techniques[i]; + // technique.stageIDs + hashData += techData.stageIDs; + // technique._layer + // hashData += + techData._layer + "_"; + // technique.passes + for (j = 0; j < techData.passes.length; j++) { + hashData += serializePass(techData.passes[j]); + } + //technique._parameters + for (j = 0; j < techData._parameters.length; j++) { + param = techData._parameters[j]; + propKey = param.name; + prop = effect._properties[propKey]; + if (!prop) { + continue; + } + switch(param.type) { + case renderer.PARAM_INT: + case renderer.PARAM_FLOAT: + hashData += prop + ';'; + break; + case renderer.PARAM_INT2: + case renderer.PARAM_FLOAT2: + hashData += prop.x + ',' + prop.y + ';'; + break; + case renderer.PARAM_INT4: + case renderer.PARAM_FLOAT4: + hashData += prop.x + ',' + prop.y + ',' + prop.z + ',' + prop.w + ';'; + break; + case renderer.PARAM_COLOR4: + hashData += prop.r + ',' + prop.g + ',' + prop.b + ',' + prop.a + ';'; + break; + case renderer.PARAM_MAT2: + hashData += prop.m00 + ',' + prop.m01 + ',' + prop.m02 + ',' + prop.m03 + ';'; + break; + case renderer.PARAM_TEXTURE_2D: + case renderer.PARAM_TEXTURE_CUBE: + hashData += material._texIds[propKey] + ';'; + break; + case renderer.PARAM_INT3: + case renderer.PARAM_FLOAT3: + case renderer.PARAM_COLOR3: + case renderer.PARAM_MAT3: + case renderer.PARAM_MAT4: + hashData += JSON.stringify(prop) + ';'; + break; + default: + break; + } + } + } + } + return hashData ? murmurhash2_32_gc(hashData, 666) : hashData; +} + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var Material = (function (Asset$$1) { + function Material(persist) { + if ( persist === void 0 ) persist = false; + + Asset$$1.call(this, persist); + + this._effect = null; // renderer.Effect + this._texIds = {}; // ids collected from texture defines + this._hash = ''; + } + + if ( Asset$$1 ) Material.__proto__ = Asset$$1; + Material.prototype = Object.create( Asset$$1 && Asset$$1.prototype ); + Material.prototype.constructor = Material; + + var prototypeAccessors = { hash: {} }; + + prototypeAccessors.hash.get = function () { + return this._hash; + }; + + Material.prototype.updateHash = function updateHash (value) { + this._hash = value || computeHash(this); + }; + + Object.defineProperties( Material.prototype, prototypeAccessors ); + + return Material; +}(Asset)); + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var SpriteMaterial = (function (Material$$1) { + function SpriteMaterial() { + Material$$1.call(this, false); + + var pass = new renderer.Pass('sprite'); + pass.setDepth(false, false); + pass.setCullMode(gfx.CULL_NONE); + pass.setBlend( + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA + ); + + var mainTech = new renderer.Technique( + ['transparent'], + [ + { name: 'texture', type: renderer.PARAM_TEXTURE_2D } ], + [ + pass + ] + ); + + this._effect = new renderer.Effect( + [ + mainTech ], + {}, + [ + { name: 'useTexture', value: true }, + { name: 'useModel', value: false }, + { name: 'alphaTest', value: false } ] + ); + + this._mainTech = mainTech; + this._texture = null; + } + + if ( Material$$1 ) SpriteMaterial.__proto__ = Material$$1; + SpriteMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); + SpriteMaterial.prototype.constructor = SpriteMaterial; + + var prototypeAccessors = { effect: {},useTexture: {},useModel: {},texture: {} }; + + prototypeAccessors.effect.get = function () { + return this._effect; + }; + + prototypeAccessors.useTexture.get = function () { + this._effect.getDefine('useTexture', val); + }; + + prototypeAccessors.useTexture.set = function (val) { + this._effect.define('useTexture', val); + }; + + prototypeAccessors.useModel.get = function () { + this._effect.getDefine('useModel', val); + }; + + prototypeAccessors.useModel.set = function (val) { + this._effect.define('useModel', val); + }; + + prototypeAccessors.texture.get = function () { + return this._texture; + }; + + prototypeAccessors.texture.set = function (val) { + if (this._texture !== val) { + this._texture = val; + this._effect.setProperty('texture', val.getImpl()); + this._texIds['texture'] = val.getId(); + } + }; + + SpriteMaterial.prototype.clone = function clone () { + var copy = new SpriteMaterial(); + copy.texture = this.texture; + copy.useTexture = this.useTexture; + copy.useModel = this.useModel; + copy.updateHash(); + return copy; + }; + + Object.defineProperties( SpriteMaterial.prototype, prototypeAccessors ); + + return SpriteMaterial; +}(Material)); + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var GraySpriteMaterial = (function (Material$$1) { + function GraySpriteMaterial() { + Material$$1.call(this, false); + + var pass = new renderer.Pass('gray_sprite'); + pass.setDepth(false, false); + pass.setCullMode(gfx.CULL_NONE); + pass.setBlend( + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA + ); + + var mainTech = new renderer.Technique( + ['transparent'], + [ + { name: 'texture', type: renderer.PARAM_TEXTURE_2D } ], + [ + pass + ] + ); + + this._effect = new renderer.Effect( + [ + mainTech ], + {}, + [] + ); + + this._mainTech = mainTech; + this._texture = null; + } + + if ( Material$$1 ) GraySpriteMaterial.__proto__ = Material$$1; + GraySpriteMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); + GraySpriteMaterial.prototype.constructor = GraySpriteMaterial; + + var prototypeAccessors = { effect: {},texture: {} }; + + prototypeAccessors.effect.get = function () { + return this._effect; + }; + + prototypeAccessors.texture.get = function () { + return this._texture; + }; + + prototypeAccessors.texture.set = function (val) { + if (this._texture !== val) { + this._texture = val; + this._effect.setProperty('texture', val.getImpl()); + this._texIds['texture'] = val.getId(); + } + }; + + GraySpriteMaterial.prototype.clone = function clone () { + var copy = new GraySpriteMaterial(); + copy.texture = this.texture; + copy.updateHash(); + return copy; + }; + + Object.defineProperties( GraySpriteMaterial.prototype, prototypeAccessors ); + + return GraySpriteMaterial; +}(Material)); + +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +var StencilMaterial = (function (Material$$1) { + function StencilMaterial() { + Material$$1.call(this, false); + + this._pass = new renderer.Pass('sprite'); + this._pass.setDepth(false, false); + this._pass.setCullMode(gfx.CULL_NONE); + this._pass.setBlend( + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, + gfx.BLEND_FUNC_ADD, + gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA + ); + + var mainTech = new renderer.Technique( + ['transparent'], + [ + { name: 'texture', type: renderer.PARAM_TEXTURE_2D }, + { name: 'alphaThreshold', type: renderer.PARAM_FLOAT } ], + [ + this._pass + ] + ); + + this._effect = new renderer.Effect( + [ + mainTech ], + {}, + [ + { name: 'useTexture', value: true }, + { name: 'useModel', value: false }, + { name: 'alphaTest', value: true } ] + ); + + this._mainTech = mainTech; + this._texture = null; + } + + if ( Material$$1 ) StencilMaterial.__proto__ = Material$$1; + StencilMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); + StencilMaterial.prototype.constructor = StencilMaterial; + + var prototypeAccessors = { effect: {},useTexture: {},texture: {},alphaThreshold: {} }; + + prototypeAccessors.effect.get = function () { + return this._effect; + }; + + prototypeAccessors.useTexture.get = function () { + this._effect.getDefine('useTexture', val); + }; + + prototypeAccessors.useTexture.set = function (val) { + this._effect.define('useTexture', val); + }; + + prototypeAccessors.texture.get = function () { + return this._texture; + }; + + prototypeAccessors.texture.set = function (val) { + if (this._texture !== val) { + this._texture = val; + this._effect.setProperty('texture', val.getImpl()); + this._texIds['texture'] = val.getId(); + } + }; + + prototypeAccessors.alphaThreshold.get = function () { + return this._effect.getProperty('alphaThreshold'); + }; + + prototypeAccessors.alphaThreshold.set = function (val) { + this._effect.setProperty('alphaThreshold', val); + }; + + StencilMaterial.prototype.clone = function clone () { + var copy = new StencilMaterial(); + copy.useTexture = this.useTexture; + copy.texture = this.texture; + copy.alphaThreshold = this.alphaThreshold; + copy.updateHash(); + return copy; + }; + + Object.defineProperties( StencilMaterial.prototype, prototypeAccessors ); + + return StencilMaterial; +}(Material)); + var _d2r = Math.PI / 180.0; var _r2d = 180.0 / Math.PI; @@ -252,7 +2708,7 @@ function log2(v) { * @param {number} v * @returns {number} */ -function log10(v) { +function log10$1(v) { return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; @@ -468,7 +2924,7 @@ var bits_ = Object.freeze({ max: max, isPow2: isPow2, log2: log2, - log10: log10, + log10: log10$1, popCount: popCount, countTrailingZeros: countTrailingZeros, nextPow2: nextPow2$1, @@ -7305,2540 +9761,6 @@ var math = Object.freeze({ nextPow2: nextPow2 }); -var renderer = window.renderer; - -var gfx = window.gfx; - -// reference: https://github.com/mziccard/node-timsort - -/** - * Default minimum size of a run. - */ -var DEFAULT_MIN_MERGE = 32; - -/** - * Minimum ordered subsequece required to do galloping. - */ -var DEFAULT_MIN_GALLOPING = 7; - -/** - * Default tmp storage length. Can increase depending on the size of the - * smallest run to merge. - */ -var DEFAULT_TMP_STORAGE_LENGTH = 256; - -/** - * Pre-computed powers of 10 for efficient lexicographic comparison of - * small integers. - */ -var POWERS_OF_TEN = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]; - -/** - * Estimate the logarithm base 10 of a small integer. - * - * @param {number} x - The integer to estimate the logarithm of. - * @return {number} - The estimated logarithm of the integer. - */ -function log10$1(x) { - if (x < 1e5) { - if (x < 1e2) { - return x < 1e1 ? 0 : 1; - } - - if (x < 1e4) { - return x < 1e3 ? 2 : 3; - } - - return 4; - } - - if (x < 1e7) { - return x < 1e6 ? 5 : 6; - } - - if (x < 1e9) { - return x < 1e8 ? 7 : 8; - } - - return 9; -} - -/** - * Default alphabetical comparison of items. - * - * @param {string|object|number} a - First element to compare. - * @param {string|object|number} b - Second element to compare. - * @return {number} - A positive number if a.toString() > b.toString(), a - * negative number if .toString() < b.toString(), 0 otherwise. - */ -function alphabeticalCompare(a, b) { - if (a === b) { - return 0; - } - - if (~~a === a && ~~b === b) { - if (a === 0 || b === 0) { - return a < b ? -1 : 1; - } - - if (a < 0 || b < 0) { - if (b >= 0) { - return -1; - } - - if (a >= 0) { - return 1; - } - - a = -a; - b = -b; - } - - var al = log10$1(a); - var bl = log10$1(b); - - var t = 0; - - if (al < bl) { - a *= POWERS_OF_TEN[bl - al - 1]; - b /= 10; - t = -1; - } else if (al > bl) { - b *= POWERS_OF_TEN[al - bl - 1]; - a /= 10; - t = 1; - } - - if (a === b) { - return t; - } - - return a < b ? -1 : 1; - } - - var aStr = String(a); - var bStr = String(b); - - if (aStr === bStr) { - return 0; - } - - return aStr < bStr ? -1 : 1; -} - -/** - * Compute minimum run length for TimSort - * - * @param {number} n - The size of the array to sort. - */ -function minRunLength(n) { - var r = 0; - - while (n >= DEFAULT_MIN_MERGE) { - r |= (n & 1); - n >>= 1; - } - - return n + r; -} - -/** - * Counts the length of a monotonically ascending or strictly monotonically - * descending sequence (run) starting at array[lo] in the range [lo, hi). If - * the run is descending it is made ascending. - * - * @param {array} array - The array to reverse. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - * @param {function} compare - Item comparison function. - * @return {number} - The length of the run. - */ -function makeAscendingRun(array, lo, hi, compare) { - var runHi = lo + 1; - - if (runHi === hi) { - return 1; - } - - // Descending - if (compare(array[runHi++], array[lo]) < 0) { - while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) { - runHi++; - } - - reverseRun(array, lo, runHi); - // Ascending - } else { - while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) { - runHi++; - } - } - - return runHi - lo; -} - -/** - * Reverse an array in the range [lo, hi). - * - * @param {array} array - The array to reverse. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - */ -function reverseRun(array, lo, hi) { - hi--; - - while (lo < hi) { - var t = array[lo]; - array[lo++] = array[hi]; - array[hi--] = t; - } -} - -/** - * Perform the binary sort of the array in the range [lo, hi) where start is - * the first element possibly out of order. - * - * @param {array} array - The array to sort. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - * @param {number} start - First element possibly out of order. - * @param {function} compare - Item comparison function. - */ -function binaryInsertionSort(array, lo, hi, start, compare) { - if (start === lo) { - start++; - } - - for (; start < hi; start++) { - var pivot = array[start]; - - // Ranges of the array where pivot belongs - var left = lo; - var right = start; - - /* - * pivot >= array[i] for i in [lo, left) - * pivot < array[i] for i in in [right, start) - */ - while (left < right) { - var mid = (left + right) >>> 1; - - if (compare(pivot, array[mid]) < 0) { - right = mid; - } else { - left = mid + 1; - } - } - - /* - * Move elements right to make room for the pivot. If there are elements - * equal to pivot, left points to the first slot after them: this is also - * a reason for which TimSort is stable - */ - var n = start - left; - // Switch is just an optimization for small arrays - switch (n) { - case 3: - array[left + 3] = array[left + 2]; - /* falls through */ - case 2: - array[left + 2] = array[left + 1]; - /* falls through */ - case 1: - array[left + 1] = array[left]; - break; - default: - while (n > 0) { - array[left + n] = array[left + n - 1]; - n--; - } - } - - array[left] = pivot; - } -} - -/** - * Find the position at which to insert a value in a sorted range. If the range - * contains elements equal to the value the leftmost element index is returned - * (for stability). - * - * @param {number} value - Value to insert. - * @param {array} array - The array in which to insert value. - * @param {number} start - First element in the range. - * @param {number} length - Length of the range. - * @param {number} hint - The index at which to begin the search. - * @param {function} compare - Item comparison function. - * @return {number} - The index where to insert value. - */ -function gallopLeft(value, array, start, length, hint, compare) { - var lastOffset = 0; - var maxOffset = 0; - var offset = 1; - - if (compare(value, array[start + hint]) > 0) { - maxOffset = length - hint; - - while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - lastOffset += hint; - offset += hint; - - // value <= array[start + hint] - } else { - maxOffset = hint + 1; - while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - var tmp = lastOffset; - lastOffset = hint - offset; - offset = hint - tmp; - } - - /* - * Now array[start+lastOffset] < value <= array[start+offset], so value - * belongs somewhere in the range (start + lastOffset, start + offset]. Do a - * binary search, with invariant array[start + lastOffset - 1] < value <= - * array[start + offset]. - */ - lastOffset++; - while (lastOffset < offset) { - var m = lastOffset + ((offset - lastOffset) >>> 1); - - if (compare(value, array[start + m]) > 0) { - lastOffset = m + 1; - - } else { - offset = m; - } - } - return offset; -} - -/** - * Find the position at which to insert a value in a sorted range. If the range - * contains elements equal to the value the rightmost element index is returned - * (for stability). - * - * @param {number} value - Value to insert. - * @param {array} array - The array in which to insert value. - * @param {number} start - First element in the range. - * @param {number} length - Length of the range. - * @param {number} hint - The index at which to begin the search. - * @param {function} compare - Item comparison function. - * @return {number} - The index where to insert value. - */ -function gallopRight(value, array, start, length, hint, compare) { - var lastOffset = 0; - var maxOffset = 0; - var offset = 1; - - if (compare(value, array[start + hint]) < 0) { - maxOffset = hint + 1; - - while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - var tmp = lastOffset; - lastOffset = hint - offset; - offset = hint - tmp; - - // value >= array[start + hint] - } else { - maxOffset = length - hint; - - while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - lastOffset += hint; - offset += hint; - } - - /* - * Now array[start+lastOffset] < value <= array[start+offset], so value - * belongs somewhere in the range (start + lastOffset, start + offset]. Do a - * binary search, with invariant array[start + lastOffset - 1] < value <= - * array[start + offset]. - */ - lastOffset++; - - while (lastOffset < offset) { - var m = lastOffset + ((offset - lastOffset) >>> 1); - - if (compare(value, array[start + m]) < 0) { - offset = m; - - } else { - lastOffset = m + 1; - } - } - - return offset; -} - -var TimSort = function TimSort(array, compare) { - this.array = array; - this.compare = compare; - this.minGallop = DEFAULT_MIN_GALLOPING; - this.length = array.length; - - this.tmpStorageLength = DEFAULT_TMP_STORAGE_LENGTH; - if (this.length < 2 * DEFAULT_TMP_STORAGE_LENGTH) { - this.tmpStorageLength = this.length >>> 1; - } - - this.tmp = new Array(this.tmpStorageLength); - - this.stackLength = - (this.length < 120 ? 5 : - this.length < 1542 ? 10 : - this.length < 119151 ? 19 : 40); - - this.runStart = new Array(this.stackLength); - this.runLength = new Array(this.stackLength); - this.stackSize = 0; -}; - -/** - * Push a new run on TimSort's stack. - * - * @param {number} runStart - Start index of the run in the original array. - * @param {number} runLength - Length of the run; - */ -TimSort.prototype.pushRun = function pushRun (runStart, runLength) { - this.runStart[this.stackSize] = runStart; - this.runLength[this.stackSize] = runLength; - this.stackSize += 1; -}; - -/** - * Merge runs on TimSort's stack so that the following holds for all i: - * 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1] - * 2) runLength[i - 2] > runLength[i - 1] - */ -TimSort.prototype.mergeRuns = function mergeRuns () { - var this$1 = this; - - while (this.stackSize > 1) { - var n = this$1.stackSize - 2; - - if ((n >= 1 && - this$1.runLength[n - 1] <= this$1.runLength[n] + this$1.runLength[n + 1]) || - (n >= 2 && - this$1.runLength[n - 2] <= this$1.runLength[n] + this$1.runLength[n - 1])) { - - if (this$1.runLength[n - 1] < this$1.runLength[n + 1]) { - n--; - } - - } else if (this$1.runLength[n] > this$1.runLength[n + 1]) { - break; - } - this$1.mergeAt(n); - } -}; - -/** - * Merge all runs on TimSort's stack until only one remains. - */ -TimSort.prototype.forceMergeRuns = function forceMergeRuns () { - var this$1 = this; - - while (this.stackSize > 1) { - var n = this$1.stackSize - 2; - - if (n > 0 && this$1.runLength[n - 1] < this$1.runLength[n + 1]) { - n--; - } - - this$1.mergeAt(n); - } -}; - -/** - * Merge the runs on the stack at positions i and i+1. Must be always be called - * with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack). - * - * @param {number} i - Index of the run to merge in TimSort's stack. - */ -TimSort.prototype.mergeAt = function mergeAt (i) { - var compare = this.compare; - var array = this.array; - - var start1 = this.runStart[i]; - var length1 = this.runLength[i]; - var start2 = this.runStart[i + 1]; - var length2 = this.runLength[i + 1]; - - this.runLength[i] = length1 + length2; - - if (i === this.stackSize - 3) { - this.runStart[i + 1] = this.runStart[i + 2]; - this.runLength[i + 1] = this.runLength[i + 2]; - } - - this.stackSize--; - - /* - * Find where the first element in the second run goes in run1. Previous - * elements in run1 are already in place - */ - var k = gallopRight(array[start2], array, start1, length1, 0, compare); - start1 += k; - length1 -= k; - - if (length1 === 0) { - return; - } - - /* - * Find where the last element in the first run goes in run2. Next elements - * in run2 are already in place - */ - length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare); - - if (length2 === 0) { - return; - } - - /* - * Merge remaining runs. A tmp array with length = min(length1, length2) is - * used - */ - if (length1 <= length2) { - this.mergeLow(start1, length1, start2, length2); - - } else { - this.mergeHigh(start1, length1, start2, length2); - } -}; - -/** - * Merge two adjacent runs in a stable way. The runs must be such that the - * first element of run1 is bigger than the first element in run2 and the - * last element of run1 is greater than all the elements in run2. - * The method should be called when run1.length <= run2.length as it uses - * TimSort temporary array to store run1. Use mergeHigh if run1.length > - * run2.length. - * - * @param {number} start1 - First element in run1. - * @param {number} length1 - Length of run1. - * @param {number} start2 - First element in run2. - * @param {number} length2 - Length of run2. - */ -TimSort.prototype.mergeLow = function mergeLow (start1, length1, start2, length2) { - - var compare = this.compare; - var array = this.array; - var tmp = this.tmp; - var i = 0; - - for (i = 0; i < length1; i++) { - tmp[i] = array[start1 + i]; - } - - var cursor1 = 0; - var cursor2 = start2; - var dest = start1; - - array[dest++] = array[cursor2++]; - - if (--length2 === 0) { - for (i = 0; i < length1; i++) { - array[dest + i] = tmp[cursor1 + i]; - } - return; - } - - if (length1 === 1) { - for (i = 0; i < length2; i++) { - array[dest + i] = array[cursor2 + i]; - } - array[dest + length2] = tmp[cursor1]; - return; - } - - var minGallop = this.minGallop; - - while (true) { - var count1 = 0; - var count2 = 0; - var exit = false; - - do { - if (compare(array[cursor2], tmp[cursor1]) < 0) { - array[dest++] = array[cursor2++]; - count2++; - count1 = 0; - - if (--length2 === 0) { - exit = true; - break; - } - - } else { - array[dest++] = tmp[cursor1++]; - count1++; - count2 = 0; - if (--length1 === 1) { - exit = true; - break; - } - } - } while ((count1 | count2) < minGallop); - - if (exit) { - break; - } - - do { - count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare); - - if (count1 !== 0) { - for (i = 0; i < count1; i++) { - array[dest + i] = tmp[cursor1 + i]; - } - - dest += count1; - cursor1 += count1; - length1 -= count1; - if (length1 <= 1) { - exit = true; - break; - } - } - - array[dest++] = array[cursor2++]; - - if (--length2 === 0) { - exit = true; - break; - } - - count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare); - - if (count2 !== 0) { - for (i = 0; i < count2; i++) { - array[dest + i] = array[cursor2 + i]; - } - - dest += count2; - cursor2 += count2; - length2 -= count2; - - if (length2 === 0) { - exit = true; - break; - } - } - array[dest++] = tmp[cursor1++]; - - if (--length1 === 1) { - exit = true; - break; - } - - minGallop--; - - } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); - - if (exit) { - break; - } - - if (minGallop < 0) { - minGallop = 0; - } - - minGallop += 2; - } - - this.minGallop = minGallop; - - if (minGallop < 1) { - this.minGallop = 1; - } - - if (length1 === 1) { - for (i = 0; i < length2; i++) { - array[dest + i] = array[cursor2 + i]; - } - array[dest + length2] = tmp[cursor1]; - - } else if (length1 === 0) { - throw new Error('mergeLow preconditions were not respected'); - - } else { - for (i = 0; i < length1; i++) { - array[dest + i] = tmp[cursor1 + i]; - } - } -}; - -/** - * Merge two adjacent runs in a stable way. The runs must be such that the - * first element of run1 is bigger than the first element in run2 and the - * last element of run1 is greater than all the elements in run2. - * The method should be called when run1.length > run2.length as it uses - * TimSort temporary array to store run2. Use mergeLow if run1.length <= - * run2.length. - * - * @param {number} start1 - First element in run1. - * @param {number} length1 - Length of run1. - * @param {number} start2 - First element in run2. - * @param {number} length2 - Length of run2. - */ -TimSort.prototype.mergeHigh = function mergeHigh (start1, length1, start2, length2) { - var compare = this.compare; - var array = this.array; - var tmp = this.tmp; - var i = 0; - - for (i = 0; i < length2; i++) { - tmp[i] = array[start2 + i]; - } - - var cursor1 = start1 + length1 - 1; - var cursor2 = length2 - 1; - var dest = start2 + length2 - 1; - var customCursor = 0; - var customDest = 0; - - array[dest--] = array[cursor1--]; - - if (--length1 === 0) { - customCursor = dest - (length2 - 1); - - for (i = 0; i < length2; i++) { - array[customCursor + i] = tmp[i]; - } - - return; - } - - if (length2 === 1) { - dest -= length1; - cursor1 -= length1; - customDest = dest + 1; - customCursor = cursor1 + 1; - - for (i = length1 - 1; i >= 0; i--) { - array[customDest + i] = array[customCursor + i]; - } - - array[dest] = tmp[cursor2]; - return; - } - - var minGallop = this.minGallop; - - while (true) { - var count1 = 0; - var count2 = 0; - var exit = false; - - do { - if (compare(tmp[cursor2], array[cursor1]) < 0) { - array[dest--] = array[cursor1--]; - count1++; - count2 = 0; - if (--length1 === 0) { - exit = true; - break; - } - - } else { - array[dest--] = tmp[cursor2--]; - count2++; - count1 = 0; - if (--length2 === 1) { - exit = true; - break; - } - } - - } while ((count1 | count2) < minGallop); - - if (exit) { - break; - } - - do { - count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare); - - if (count1 !== 0) { - dest -= count1; - cursor1 -= count1; - length1 -= count1; - customDest = dest + 1; - customCursor = cursor1 + 1; - - for (i = count1 - 1; i >= 0; i--) { - array[customDest + i] = array[customCursor + i]; - } - - if (length1 === 0) { - exit = true; - break; - } - } - - array[dest--] = tmp[cursor2--]; - - if (--length2 === 1) { - exit = true; - break; - } - - count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare); - - if (count2 !== 0) { - dest -= count2; - cursor2 -= count2; - length2 -= count2; - customDest = dest + 1; - customCursor = cursor2 + 1; - - for (i = 0; i < count2; i++) { - array[customDest + i] = tmp[customCursor + i]; - } - - if (length2 <= 1) { - exit = true; - break; - } - } - - array[dest--] = array[cursor1--]; - - if (--length1 === 0) { - exit = true; - break; - } - - minGallop--; - - } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); - - if (exit) { - break; - } - - if (minGallop < 0) { - minGallop = 0; - } - - minGallop += 2; - } - - this.minGallop = minGallop; - - if (minGallop < 1) { - this.minGallop = 1; - } - - if (length2 === 1) { - dest -= length1; - cursor1 -= length1; - customDest = dest + 1; - customCursor = cursor1 + 1; - - for (i = length1 - 1; i >= 0; i--) { - array[customDest + i] = array[customCursor + i]; - } - - array[dest] = tmp[cursor2]; - - } else if (length2 === 0) { - throw new Error('mergeHigh preconditions were not respected'); - - } else { - customCursor = dest - (length2 - 1); - for (i = 0; i < length2; i++) { - array[customCursor + i] = tmp[i]; - } - } -}; - -/** - * Sort an array in the range [lo, hi) using TimSort. - * - * @param {array} array - The array to sort. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - * @param {function=} compare - Item comparison function. Default is alphabetical. - */ -function sort (array, lo, hi, compare) { - if (!Array.isArray(array)) { - throw new TypeError('Can only sort arrays'); - } - - /* - * Handle the case where a comparison function is not provided. We do - * lexicographic sorting - */ - - if (lo === undefined) { - lo = 0; - } - - if (hi === undefined) { - hi = array.length; - } - - if (compare === undefined) { - compare = alphabeticalCompare; - } - - var remaining = hi - lo; - - // The array is already sorted - if (remaining < 2) { - return; - } - - var runLength = 0; - // On small arrays binary sort can be used directly - if (remaining < DEFAULT_MIN_MERGE) { - runLength = makeAscendingRun(array, lo, hi, compare); - binaryInsertionSort(array, lo, hi, lo + runLength, compare); - return; - } - - var ts = new TimSort(array, compare); - - var minRun = minRunLength(remaining); - - do { - runLength = makeAscendingRun(array, lo, hi, compare); - if (runLength < minRun) { - var force = remaining; - if (force > minRun) { - force = minRun; - } - - binaryInsertionSort(array, lo, lo + force, lo + runLength, compare); - runLength = force; - } - // Push new run and merge if necessary - ts.pushRun(lo, runLength); - ts.mergeRuns(); - - // Go find next run - remaining -= runLength; - lo += runLength; - - } while (remaining !== 0); - - // Force merging of remaining runs - ts.forceMergeRuns(); -} - -var FixedArray = function FixedArray(size) { - this._count = 0; - this._data = new Array(size); -}; - -var prototypeAccessors = { length: {},data: {} }; - -FixedArray.prototype._resize = function _resize (size) { - var this$1 = this; - - if (size > this._data.length) { - for (var i = this._data.length; i < size; ++i) { - this$1._data[i] = undefined; - } - } -}; - -prototypeAccessors.length.get = function () { - return this._count; -}; - -prototypeAccessors.data.get = function () { - return this._data; -}; - -FixedArray.prototype.reset = function reset () { - var this$1 = this; - - for (var i = 0; i < this._count; ++i) { - this$1._data[i] = undefined; - } - - this._count = 0; -}; - -FixedArray.prototype.push = function push (val) { - if (this._count >= this._data.length) { - this._resize(this._data.length * 2); - } - - this._data[this._count] = val; - ++this._count; -}; - -FixedArray.prototype.pop = function pop () { - --this._count; - - if (this._count < 0) { - this._count = 0; - } - - var ret = this._data[this._count]; - this._data[this._count] = undefined; - - return ret; -}; - -FixedArray.prototype.fastRemove = function fastRemove (idx) { - if (idx >= this._count) { - return; - } - - var last = this._count - 1; - this._data[idx] = this._data[last]; - this._data[last] = undefined; - this._count -= 1; -}; - -FixedArray.prototype.indexOf = function indexOf (val) { - var idx = this._data.indexOf(val); - if (idx >= this._count) { - return -1; - } - - return idx; -}; - -FixedArray.prototype.sort = function sort$1 (cmp) { - return sort(this._data, 0, this._count, cmp); -}; - -Object.defineProperties( FixedArray.prototype, prototypeAccessors ); - -var Pool = function Pool(fn, size) { - var this$1 = this; - - this._fn = fn; - this._idx = size - 1; - this._frees = new Array(size); - - for (var i = 0; i < size; ++i) { - this$1._frees[i] = fn(); - } -}; - -Pool.prototype._expand = function _expand (size) { - var this$1 = this; - - var old = this._frees; - this._frees = new Array(size); - - var len = size - old.length; - for (var i = 0; i < len; ++i) { - this$1._frees[i] = this$1._fn(); - } - - for (var i$1 = len, j = 0; i$1 < size; ++i$1, ++j) { - this$1._frees[i$1] = old[j]; - } - - this._idx += len; -}; - -Pool.prototype.alloc = function alloc () { - // create some more space (expand by 20%, minimum 1) - if (this._idx < 0) { - this._expand(Math.round(this._frees.length * 1.2) + 1); - } - - var ret = this._frees[this._idx]; - this._frees[this._idx] = null; - --this._idx; - - return ret; -}; - -Pool.prototype.free = function free (obj) { - ++this._idx; - this._frees[this._idx] = obj; -}; - -// NOTE: you must have `_prev` and `_next` field in the object returns by `fn` - -var LinkedArray = function LinkedArray(fn, size) { - this._fn = fn; - this._count = 0; - this._head = null; - this._tail = null; - - this._pool = new Pool(fn, size); -}; - -var prototypeAccessors$1 = { head: {},tail: {},length: {} }; - -prototypeAccessors$1.head.get = function () { - return this._head; -}; - -prototypeAccessors$1.tail.get = function () { - return this._tail; -}; - -prototypeAccessors$1.length.get = function () { - return this._count; -}; - -LinkedArray.prototype.add = function add () { - var node = this._pool.alloc(); - - if (!this._tail) { - this._head = node; - } else { - this._tail._next = node; - node._prev = this._tail; - } - this._tail = node; - this._count += 1; - - return node; -}; - -LinkedArray.prototype.remove = function remove (node) { - if (node._prev) { - node._prev._next = node._next; - } else { - this._head = node._next; - } - - if (node._next) { - node._next._prev = node._prev; - } else { - this._tail = node._prev; - } - - node._next = null; - node._prev = null; - this._pool.free(node); - this._count -= 1; -}; - -LinkedArray.prototype.forEach = function forEach (fn, binder) { - var this$1 = this; - - var cursor = this._head; - if (!cursor) { - return; - } - - if (binder) { - fn = fn.bind(binder); - } - - var idx = 0; - var next = cursor; - - while (cursor) { - next = cursor._next; - fn(cursor, idx, this$1); - - cursor = next; - ++idx; - } -}; - -Object.defineProperties( LinkedArray.prototype, prototypeAccessors$1 ); - -var RecyclePool = function RecyclePool(fn, size) { - var this$1 = this; - - this._fn = fn; - this._count = 0; - this._data = new Array(size); - - for (var i = 0; i < size; ++i) { - this$1._data[i] = fn(); - } -}; - -var prototypeAccessors$2 = { length: {},data: {} }; - -prototypeAccessors$2.length.get = function () { - return this._count; -}; - -prototypeAccessors$2.data.get = function () { - return this._data; -}; - -RecyclePool.prototype.reset = function reset () { - this._count = 0; -}; - -RecyclePool.prototype.resize = function resize (size) { - var this$1 = this; - - if (size > this._data.length) { - for (var i = this._data.length; i < size; ++i) { - this$1._data[i] = this$1._fn(); - } - } -}; - -RecyclePool.prototype.add = function add () { - if (this._count >= this._data.length) { - this.resize(this._data.length * 2); - } - - return this._data[this._count++]; -}; - -RecyclePool.prototype.remove = function remove (idx) { - if (idx >= this._count) { - return; - } - - var last = this._count - 1; - var tmp = this._data[idx]; - this._data[idx] = this._data[last]; - this._data[last] = tmp; - this._count -= 1; -}; - -RecyclePool.prototype.sort = function sort$1 (cmp) { - return sort(this._data, 0, this._count, cmp); -}; - -Object.defineProperties( RecyclePool.prototype, prototypeAccessors$2 ); - -var _bufferPools = Array(8); -for (var i = 0; i < 8; ++i) { - _bufferPools[i] = []; -} - -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -var _a16_view = new Float32Array(16); -var _a16_proj = new Float32Array(16); -var _a16_viewProj = new Float32Array(16); - -// Add stage to renderer -renderer.addStage('transparent'); - -var ForwardRenderer = (function (superclass) { - function ForwardRenderer (device, builtin) { - superclass.call(this, device, builtin); - this._registerStage('transparent', this._transparentStage.bind(this)); - } - - if ( superclass ) ForwardRenderer.__proto__ = superclass; - ForwardRenderer.prototype = Object.create( superclass && superclass.prototype ); - ForwardRenderer.prototype.constructor = ForwardRenderer; - - ForwardRenderer.prototype.reset = function reset () { - this._reset(); - }; - - ForwardRenderer.prototype.render = function render (scene) { - var this$1 = this; - - this._reset(); - - scene._cameras.sort(function (a, b) { - if (a._depth > b._depth) { return 1; } - else if (a._depth < b._depth) { return -1; } - else { return 0; } - }); - - for (var i = 0; i < scene._cameras.length; ++i) { - var camera = scene._cameras.data[i]; - this$1.renderCamera(camera, scene); - } - }; - - ForwardRenderer.prototype.renderCamera = function renderCamera (camera, scene) { - var canvas = this._device._gl.canvas; - - var view = camera.view; - var dirty = camera.dirty; - if (!view) { - view = this._requestView(); - dirty = true; - } - if (dirty) { - var width = canvas.width; - var height = canvas.height; - if (camera._framebuffer) { - width = camera._framebuffer._width; - height = camera._framebuffer._height; - } - camera.extractView(view, width, height); - } - this._render(view, scene); - }; - - ForwardRenderer.prototype._transparentStage = function _transparentStage (view, items) { - var this$1 = this; - - // update uniforms - this._device.setUniform('view', mat4.array(_a16_view, view._matView)); - this._device.setUniform('proj', mat4.array(_a16_proj, view._matProj)); - this._device.setUniform('viewProj', mat4.array(_a16_viewProj, view._matViewProj)); - - // draw it - for (var i = 0; i < items.length; ++i) { - var item = items.data[i]; - this$1._draw(item); - } - }; - - return ForwardRenderer; -}(renderer.Base)); - -var chunks = { -}; - -var templates = [ - { - name: 'gray_sprite', - vert: '\n \nuniform mat4 viewProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\nattribute vec2 a_uv0;\nvarying vec2 uv0;\nvoid main () {\n vec4 pos = viewProj * vec4(a_position, 1);\n v_fragmentColor = a_color;\n uv0 = a_uv0;\n gl_Position = pos;\n}', - frag: '\n \nuniform sampler2D texture;\nvarying vec2 uv0;\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 c = v_fragmentColor * texture2D(texture, uv0);\n float gray = 0.2126*c.r + 0.7152*c.g + 0.0722*c.b;\n gl_FragColor = vec4(gray, gray, gray, c.a);\n}', - defines: [ - ], - }, - { - name: 'sprite', - vert: '\n \nuniform mat4 viewProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\n#ifdef useModel\n uniform mat4 model;\n#endif\n#ifdef useTexture\n attribute vec2 a_uv0;\n varying vec2 uv0;\n#endif\nvoid main () {\n mat4 mvp;\n #ifdef useModel\n mvp = viewProj * model;\n #else\n mvp = viewProj;\n #endif\n vec4 pos = mvp * vec4(a_position, 1);\n v_fragmentColor = a_color;\n \n #ifdef useTexture\n uv0 = a_uv0;\n #endif\n gl_Position = pos;\n}', - frag: '\n \n#ifdef useTexture\n uniform sampler2D texture;\n varying vec2 uv0;\n#endif\n#ifdef alphaTest\n uniform float alphaThreshold;\n#endif\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 o = v_fragmentColor;\n #ifdef useTexture\n o *= texture2D(texture, uv0);\n #endif\n #ifdef alphaTest\n if (o.a <= alphaThreshold)\n discard;\n #endif\n gl_FragColor = o;\n}', - defines: [ - { name: 'useTexture', }, - { name: 'useModel', }, - { name: 'alphaTest', } ], - }, - { - name: 'vfx_emitter', - vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', - frag: '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D noise;\nuniform sampler2D state;\nuniform vec2 statesize;\nuniform vec2 noisesize;\nuniform bool stopped;\nuniform float dt;\nuniform float mode;\nuniform float noiseId;\nuniform float emitVar;\nuniform float life;\nuniform float lifeVar;\nuniform vec2 pos;\nuniform vec2 posVar;\nuniform vec4 color;\nuniform vec4 colorVar;\n \nuniform vec4 endColor;\nuniform vec4 endColorVar;\nuniform float size;\nuniform float sizeVar;\nuniform float endSize;\nuniform float endSizeVar;\nuniform float rot;\nuniform float rotVar;\nuniform float endRot;\nuniform float endRotVar;\nuniform float angle;\nuniform float angleVar;\nuniform float speed;\nuniform float speedVar;\nuniform float radial;\nuniform float radialVar;\nuniform float tangent;\nuniform float tangentVar;\nuniform float radius;\nuniform float radiusVar;\nuniform float endRadius;\nuniform float endRadiusVar;\nuniform float rotatePS;\nuniform float rotatePSVar;\nuniform float sizeScale;\nuniform float accelScale;\nuniform float radiusScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float NOISE_SCALE = 10000.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nconst float COLOR_SCALE = 1.0;\nconst float LIFE_SCALE = 100.0;\nconst float START_SIZE_EQUAL_TO_END_SIZE = -1.0;\nconst float START_RADIUS_EQUAL_TO_END_RADIUS = -1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nfloat randomMinus1To1(vec2 randomD) {\n float random = decode(randomD, NOISE_SCALE);\n return (random - 0.5) * 2.0;\n}\nbool doEmit (vec4 randomD) {\n float random1 = decode(randomD.rg, NOISE_SCALE);\n if (!stopped && (life + lifeVar) * random1 < life) {\n return true;\n }\n else {\n return false;\n }\n}\nvec4 initLife (vec4 data, vec4 randomD) {\n \n if (doEmit(randomD)) {\n float random2 = decode(randomD.ba, NOISE_SCALE);\n float plife = life + lifeVar * random2;\n vec2 l = encode(plife, LIFE_SCALE);\n return vec4(l, l);\n }\n else {\n return data;\n }\n}\nvec4 initColor (float randr, float randg, float randb, float randa) {\n vec4 random = vec4(randr, randg, randb, randa);\n vec4 result = clamp(color + colorVar * random, 0.0, 255.0);\n return result / 255.0;\n}\nvec4 initDeltaRG (vec2 startR, vec2 random) {\n vec2 start = clamp(color.rg + colorVar.rg * startR, 0.0, 255.0);\n vec2 end = clamp(endColor.rg + endColorVar.rg * random, 0.0, 255.0);\n vec2 delta = end - start;\n return vec4(encode(delta.x, COLOR_SCALE), encode(delta.y, COLOR_SCALE));\n}\nvec4 initDeltaBA (vec2 startR, vec2 random) {\n vec2 start = clamp(color.ba + colorVar.ba * startR, 0.0, 255.0);\n vec2 end = clamp(endColor.ba + endColorVar.ba * random, 0.0, 255.0);\n vec2 delta = end - start;\n return vec4(encode(delta.x, COLOR_SCALE), encode(delta.y, COLOR_SCALE));\n}\nvec4 initSize (float rand1, float rand2) {\n float start = max(0.0, size + sizeVar * rand1);\n if (endSize == START_SIZE_EQUAL_TO_END_SIZE) {\n float delta = 0.0;\n return vec4(encode(start, sizeScale), encode(delta, sizeScale));\n }\n else {\n float end = max(0.0, endSize + endSizeVar * rand2);\n float delta = end - start;\n return vec4(encode(start, sizeScale), encode(delta, sizeScale));\n }\n}\nvec4 initRotation (float rand1, float rand2) {\n float start = rot + rotVar * rand1;\n float end = endRot + endRotVar * rand2;\n float delta = end - start;\n return vec4(encode(start, ROTATION_SCALE), encode(delta, ROTATION_SCALE));\n}\nvec4 initControl1 (float rand1, float rand2) {\n \n if (mode == 0.0) {\n float pAngle = angle + angleVar * rand1;\n float dirX = cos(pAngle);\n float dirY = sin(pAngle);\n float pSpeed = speed + speedVar * rand2;\n return vec4(encode(dirX * pSpeed, POSITION_SCALE), encode(dirY * pSpeed, POSITION_SCALE));\n }\n \n else {\n float pAngle = angle + angleVar * rand1;\n float pRadius = radius + radiusVar * rand2;\n return vec4(encode(pAngle, ROTATION_SCALE), encode(pRadius, radiusScale));\n }\n}\nvec4 initControl2 (float startR1, float rand1, float rand2) {\n \n if (mode == 0.0) {\n float pRadial = radial + radialVar * rand1;\n float pTangent = tangent + tangentVar * rand2;\n return vec4(encode(pRadial, accelScale), encode(pTangent, accelScale));\n }\n \n else {\n float degreesPerSecond = rotatePS + rotatePSVar * rand1;\n float pDeltaRadius;\n if (endRadius == START_RADIUS_EQUAL_TO_END_RADIUS) {\n pDeltaRadius = 0.0;\n }\n else {\n float pRadius = radius + radiusVar * startR1;\n pDeltaRadius = (endRadius + endRadiusVar * rand2 - pRadius);\n }\n return vec4(encode(degreesPerSecond, ROTATION_SCALE), encode(pDeltaRadius, radiusScale));\n }\n}\nvec4 initPos (float rand1, float rand2) {\n vec2 result = pos + posVar * vec2(rand1, rand2);\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n}\nvoid main() {\n vec2 pixel = floor(index * statesize);\n vec2 pindex = floor(pixel / 3.0);\n vec2 temp = mod(pixel, vec2(3.0, 3.0));\n float id = floor(temp.y * 3.0 + temp.x);\n vec2 noffset = vec2(floor(noiseId / 4.0), mod(noiseId, 4.0));\n vec2 nid = pixel + noffset;\n vec4 randomD = texture2D(noise, nid / noisesize);\n \n vec4 lifeData = texture2D(state, pindex * 3.0 / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n float life = decode(lifeData.ba, LIFE_SCALE);\n \n if (id == 0.0) {\n vec4 data = texture2D(state, index);\n if (rest <= 0.0) {\n gl_FragColor = initLife(data, randomD);\n }\n else {\n gl_FragColor = data;\n }\n return;\n }\n \n if (rest > 0.0) {\n vec4 data = texture2D(state, index);\n gl_FragColor = data;\n return;\n }\n vec2 lifeNid = pindex * 3.0 + noffset;\n vec4 lifeRandomD = texture2D(noise, lifeNid / noisesize);\n bool emitting = doEmit(lifeRandomD);\n if (!emitting) {\n vec4 data = texture2D(state, index);\n gl_FragColor = data;\n return;\n }\n \n float random1 = randomMinus1To1(randomD.rg);\n float random2 = randomMinus1To1(randomD.ba);\n \n if (id == 1.0) {\n vec4 randomD3 = texture2D(noise, vec2(nid.x - 1.0, nid.y + 1.0) / noisesize);\n float random3 = randomMinus1To1(randomD3.rg);\n float random4 = randomMinus1To1(randomD3.ba);\n gl_FragColor = initColor(random1, random2, random3, random4);\n return;\n }\n \n if (id == 2.0) {\n vec4 randomD1 = texture2D(noise, vec2(nid.x - 1.0, nid.y) / noisesize);\n float startR1 = randomMinus1To1(randomD1.rg);\n float startR2 = randomMinus1To1(randomD1.ba);\n vec2 startR = vec2(startR1, startR2);\n gl_FragColor = initDeltaRG(startR, vec2(random1, random2));\n return;\n }\n \n if (id == 3.0) {\n vec2 startR = vec2(random1, random2);\n gl_FragColor = initDeltaBA(startR, vec2(random1, random2));\n return;\n }\n \n if (id == 4.0) {\n gl_FragColor = initSize(random1, random2);\n return;\n }\n \n if (id == 5.0) {\n gl_FragColor = initRotation(random1, random2);\n return;\n }\n \n if (id == 6.0) {\n gl_FragColor = initControl1(random1, random2);\n return;\n }\n \n if (id == 7.0) {\n vec4 randomD6 = texture2D(noise, vec2(nid.x - 1.0, nid.y) / noisesize);\n float startR1 = randomMinus1To1(randomD6.rg);\n gl_FragColor = initControl2(startR1, random1, random2);\n return;\n }\n \n if (id == 8.0) {\n gl_FragColor = initPos(random1, random2);\n return;\n }\n}', - defines: [ - ], - }, - { - name: 'vfx_particle', - vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nuniform mat4 model;\nuniform mat4 viewProj;\nuniform sampler2D state;\nuniform sampler2D quad;\nuniform vec2 statesize;\nuniform vec2 quadsize;\nuniform float z;\nuniform vec2 lb;\nuniform vec2 rt;\nvarying lowp vec4 v_fragmentColor;\nvarying vec2 uv0;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvoid main() {\n vec2 sIndex = floor(a_quad / 2.0) * 3.0;\n vec4 lifeData = texture2D(state, sIndex / statesize);\n float life = decode(lifeData.rg, LIFE_SCALE);\n if (life <= 0.0) {\n v_fragmentColor = vec4(0.0, 0.0, 0.0, 0.0);\n uv0 = vec2(0.0, 0.0);\n gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n }\n else {\n vec2 posIndex = a_quad / quadsize;\n vec4 posData = texture2D(quad, posIndex);\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n vec2 cIndex = vec2(sIndex.x + 1.0, sIndex.y) / statesize;\n vec4 color = texture2D(state, cIndex);\n v_fragmentColor = color;\n float u, v;\n vec2 uvId = mod(a_quad, vec2(2.0));\n if (uvId.x == 0.0) {\n u = lb.x;\n }\n else {\n u = rt.x;\n }\n if (uvId.y == 0.0) {\n v = lb.y;\n }\n else {\n v = rt.y;\n }\n uv0 = vec2(u, v);\n gl_Position = viewProj * model * vec4(pos, z, 1.0);\n } \n}\n', - frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D texture;\nvarying vec2 uv0;\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 o = v_fragmentColor;\n o *= texture2D(texture, uv0);\n gl_FragColor = o;\n}', - defines: [ - ], - }, - { - name: 'vfx_quad', - vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', - frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D state;\nuniform vec2 quadsize;\nuniform vec2 statesize;\nuniform float sizeScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nvoid main() {\n vec2 pixel = floor(index * quadsize);\n vec2 pIndex = floor(pixel / 2.0) * 3.0;\n vec4 lifeData = texture2D(state, pIndex / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n if (rest <= 0.0) {\n gl_FragColor = vec4(encode(0.0, POSITION_SCALE), encode(0.0, POSITION_SCALE));\n return;\n }\n vec2 dataIndex = (pIndex + 2.0) / statesize;\n vec4 posData = texture2D(state, dataIndex);\n float x = decode(posData.rg, POSITION_SCALE);\n float y = decode(posData.ba, POSITION_SCALE);\n vec2 pos = vec2(x, y);\n dataIndex = (pIndex + 1.0) / statesize;\n vec4 sizeData = texture2D(state, dataIndex);\n float size = decode(sizeData.rg, sizeScale);\n dataIndex.x = (pIndex.x + 2.0) / statesize.x;\n dataIndex.y = (pIndex.y + 1.0) / statesize.y;\n vec4 rotData = texture2D(state, dataIndex);\n float rot = radians(mod(decode(rotData.rg, ROTATION_SCALE), 180.0));\n float a = cos(rot);\n float b = -sin(rot);\n float c = -b;\n float d = a;\n vec2 vert = (mod(pixel, vec2(2.0)) - 0.5) * size;\n x = vert.x * a + vert.y * c + pos.x;\n y = vert.x * b + vert.y * d + pos.y;\n gl_FragColor = vec4(encode(x, POSITION_SCALE), encode(y, POSITION_SCALE));\n}\n', - defines: [ - ], - }, - { - name: 'vfx_update', - vert: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nattribute vec2 a_quad;\nvarying vec2 index;\nvoid main() {\n index = (a_quad + 1.0) / 2.0;\n gl_Position = vec4(a_quad, 0, 1);\n}\n', - frag: '\n \n#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D state;\nuniform vec2 statesize;\nuniform float dt;\nuniform float mode;\nuniform vec2 gravity;\nuniform float sizeScale;\nuniform float accelScale;\nuniform float radiusScale;\nvarying vec2 index;\nconst float BASE = 255.0;\nconst float OFFSET = BASE * BASE / 2.0;\nconst float MAX_VALUE = BASE * BASE;\nconst float LIFE_SCALE = 100.0;\nconst float POSITION_SCALE = 1.0;\nconst float ROTATION_SCALE = 1.0;\nconst float COLOR_SCALE = 1.0;\nfloat decode(vec2 channels, float scale) {\n return (dot(channels, vec2(BASE, BASE * BASE)) - OFFSET) / scale;\n}\nvec2 encode(float value, float scale) {\n value = value * scale + OFFSET;\n float x = mod(value, BASE);\n float y = floor(value / BASE);\n return vec2(x, y) / BASE;\n}\nvec4 updateLife (vec4 data) {\n float rest = decode(data.rg, LIFE_SCALE);\n rest -= dt;\n return vec4(encode(rest, LIFE_SCALE), data.ba);\n}\nvec4 updateColor (vec4 color, vec4 deltaRG, vec4 deltaBA, float life) {\n float r = decode(deltaRG.rg, COLOR_SCALE);\n float g = decode(deltaRG.ba, COLOR_SCALE);\n float b = decode(deltaBA.rg, COLOR_SCALE);\n float a = decode(deltaBA.ba, COLOR_SCALE);\n vec4 deltaColor = vec4(r, g, b, a) / 255.0;\n \n color = clamp(color + deltaColor * dt / life, 0.0, 1.0);\n return color;\n}\nvec4 updateSize (vec4 data, float life) {\n float size = decode(data.rg, sizeScale);\n float deltaSize = decode(data.ba, sizeScale);\n size = clamp(size + deltaSize * dt / life, 0.0, MAX_VALUE);\n return vec4(encode(size, sizeScale), data.ba);\n}\nvec4 updateRotation (vec4 data, float life) {\n float rotation = decode(data.rg, ROTATION_SCALE);\n float deltaRotation = decode(data.ba, ROTATION_SCALE);\n rotation = mod(rotation + deltaRotation * dt / life, 180.0);\n return vec4(encode(rotation, ROTATION_SCALE), data.ba);\n}\nvec4 updateControl (vec4 control1, vec4 control2, vec4 posData, float life) {\n \n if (mode == 0.0) {\n vec2 dir = vec2(decode(control1.rg, POSITION_SCALE), decode(control1.ba, POSITION_SCALE));\n float radialAccel = decode(control2.rg, accelScale);\n float tangentialAccel = decode(control2.ba, accelScale);\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n vec2 radial = normalize(pos);\n vec2 tangential = vec2(-radial.y, radial.x);\n radial = radial * radialAccel;\n tangential = tangential * tangentialAccel;\n vec2 result = dir + (radial + tangentialAccel + gravity) * dt;\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n }\n \n else {\n float angle = mod(decode(control1.rg, ROTATION_SCALE), 180.0);\n float radius = decode(control1.ba, radiusScale);\n float degreesPerSecond = decode(control2.rg, ROTATION_SCALE);\n float deltaRadius = decode(control2.ba, radiusScale);\n angle += degreesPerSecond * dt;\n radius += deltaRadius * dt / life;\n return vec4(encode(angle, ROTATION_SCALE), encode(radius, radiusScale));\n }\n}\nvec4 updatePos (vec4 posData, vec4 control) {\n vec2 result;\n \n if (mode == 0.0) {\n vec2 dir = vec2(decode(control.rg, POSITION_SCALE), decode(control.ba, POSITION_SCALE));\n vec2 pos = vec2(decode(posData.rg, POSITION_SCALE), decode(posData.ba, POSITION_SCALE));\n result = pos + dir * dt;\n }\n \n else {\n float angle = radians(mod(decode(control.rg, ROTATION_SCALE), 180.0));\n float radius = decode(control.ba, radiusScale);\n result.x = -cos(angle) * radius;\n result.y = -sin(angle) * radius;\n }\n return vec4(encode(result.x, POSITION_SCALE), encode(result.y, POSITION_SCALE));\n}\nvoid main() {\n vec2 pixel = floor(index * statesize);\n vec2 pindex = floor(pixel / 3.0);\n vec2 temp = mod(pixel, vec2(3.0));\n float id = floor(temp.y * 3.0 + temp.x);\n \n vec4 data = texture2D(state, index);\n vec4 lifeData = texture2D(state, pindex * 3.0 / statesize);\n float rest = decode(lifeData.rg, LIFE_SCALE);\n if (rest <= 0.0) {\n gl_FragColor = data;\n return;\n }\n \n if (id == 2.0 || id == 3.0 || id == 7.0) {\n gl_FragColor = data;\n return;\n }\n float life = decode(lifeData.ba, LIFE_SCALE);\n \n if (id == 0.0) {\n gl_FragColor = updateLife(data);\n return;\n }\n \n if (id == 1.0) {\n vec2 rgIndex = vec2(pixel.x + 1.0, pixel.y) / statesize;\n vec4 deltaRG = texture2D(state, rgIndex);\n vec2 baIndex = vec2(pixel.x - 1.0, pixel.y + 1.0) / statesize;\n vec4 deltaBA = texture2D(state, baIndex);\n gl_FragColor = updateColor(data, deltaRG, deltaBA, life);\n return;\n }\n \n if (id == 4.0) {\n gl_FragColor = updateSize(data, life);\n return;\n }\n \n if (id == 5.0) {\n gl_FragColor = updateRotation(data, life);\n return;\n }\n \n if (id == 6.0) {\n vec2 ctrlIndex = vec2(pixel.x + 1.0, pixel.y) / statesize;\n vec4 control2 = texture2D(state, ctrlIndex);\n vec2 posIndex = vec2(pixel.x + 2.0, pixel.y) / statesize;\n vec4 pos = texture2D(state, posIndex);\n gl_FragColor = updateControl(data, control2, pos, life);\n return;\n }\n \n if (id == 8.0) {\n vec2 ctrlIndex = vec2(pixel.x - 2.0, pixel.y) / statesize;\n vec4 control1 = texture2D(state, ctrlIndex);\n gl_FragColor = updatePos(data, control1);\n return;\n }\n}\n', - defines: [ - ], - } ]; - -var shaders = { - chunks: chunks, - templates: templates -}; - -// Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - -/** - * BaseRenderData is a core data abstraction for renderer, this is a abstract class. - * An inherited render data type should define raw vertex datas. - * User should also define the effect, vertex count and index count. - */ -var BaseRenderData = function BaseRenderData () { - this.material = null; - this.vertexCount = 0; - this.indiceCount = 0; -}; - -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -var _pool; -var _dataPool = new Pool(function () { - return { - x: 0.0, - y: 0.0, - u: 0.0, - v: 0.0, - color: 0 - }; -}, 128); - -/** - * RenderData is most widely used render data type. - * It describes raw vertex data with a fixed data layout. - * Each vertex is described by five property: x, y, u, v, color. The data layout might be extended in the future. - * Vertex data objects are managed automatically by RenderData, user only need to set the dataLength property. - * User can also define rendering index orders for the vertex list. - */ -var RenderData = (function (BaseRenderData$$1) { - function RenderData () { - BaseRenderData$$1.call(this); - this._data = []; - this._indices = []; - - this._pivotX = 0; - this._pivotY = 0; - this._width = 0; - this._height = 0; - - this.uvDirty = true; - this.vertDirty = true; - } - - if ( BaseRenderData$$1 ) RenderData.__proto__ = BaseRenderData$$1; - RenderData.prototype = Object.create( BaseRenderData$$1 && BaseRenderData$$1.prototype ); - RenderData.prototype.constructor = RenderData; - - var prototypeAccessors = { type: {},dataLength: {} }; - - prototypeAccessors.type.get = function () { - return RenderData.type; - }; - - prototypeAccessors.dataLength.get = function () { - return this._data.length; - }; - - prototypeAccessors.dataLength.set = function (length) { - var data = this._data; - if (data.length !== length) { - // Free extra data - for (var i = length; i < data.length; i++) { - _dataPool.free(data[i]); - } - // Alloc needed data - for (var i$1 = data.length; i$1 < length; i$1++) { - data[i$1] = _dataPool.alloc(); - } - data.length = length; - } - }; - - RenderData.prototype.updateSizeNPivot = function updateSizeNPivot (width, height, pivotX, pivotY) { - if (width !== this._width || - height !== this._height || - pivotX !== this._pivotX || - pivotY !== this._pivotY) - { - this._width = width; - this._height = height; - this._pivotX = pivotX; - this._pivotY = pivotY; - this.vertDirty = true; - } - }; - - RenderData.alloc = function alloc () { - return _pool.alloc(); - }; - - RenderData.free = function free (data) { - if (data instanceof RenderData) { - for (var i = data.length-1; i > 0; i--) { - _dataPool.free(data._data[i]); - } - data._data.length = 0; - data._indices.length = 0; - data.material = null; - data.uvDirty = true; - data.vertDirty = true; - data.vertexCount = 0; - data.indiceCount = 0; - _pool.free(data); - } - }; - - Object.defineProperties( RenderData.prototype, prototypeAccessors ); - - return RenderData; -}(BaseRenderData)); - -RenderData.type = 'RenderData'; - -_pool = new Pool(function () { - return new RenderData(); -}, 32); - -// Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - -/** - * IARenderData is user customized render data type, user should provide the entier input assembler. - * IARenderData just defines a property `ia` for accessing the input assembler. - * It doesn't manage memory so users should manage the memory of input assembler by themselves. - */ -var IARenderData = (function (BaseRenderData$$1) { - function IARenderData () { - BaseRenderData$$1.call(this); - this.ia = null; - } - - if ( BaseRenderData$$1 ) IARenderData.__proto__ = BaseRenderData$$1; - IARenderData.prototype = Object.create( BaseRenderData$$1 && BaseRenderData$$1.prototype ); - IARenderData.prototype.constructor = IARenderData; - - var prototypeAccessors = { type: {} }; - - prototypeAccessors.type.get = function () { - return IARenderData.type; - }; - - Object.defineProperties( IARenderData.prototype, prototypeAccessors ); - - return IARenderData; -}(BaseRenderData)); - -IARenderData.type = 'IARenderData'; - -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -var BASE = 255; -var NOISE_SCALE = 10000; -var POS_SCALE = 1; -var LIFE_SCALE = 100; -var COLOR_SCALE = 1; -var ROTATION_SCALE = 1; -var MAX_SCALE = 500; -var _vertexFmt = new gfx.VertexFormat([ - { name: 'a_quad', type: gfx.ATTR_TYPE_FLOAT32, num: 2 } -]); - -var _dataOpts = { - width: 0, - height: 0, - minFilter: gfx.FILTER_NEAREST, - magFilter: gfx.FILTER_NEAREST, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - format: gfx.TEXTURE_FMT_RGBA8, - images: [] -}; - -function encode (value, scale, outArr, offset) { - value = value * scale + BASE * BASE / 2; - outArr[offset] = Math.floor((value % BASE) / BASE * 255); - outArr[offset+1] = Math.floor(Math.floor(value / BASE) / BASE * 255); -} - -function decode (arr, offset, scale) { - return (((arr[offset] / 255) * BASE + - (arr[offset+1] / 255) * BASE * BASE) - BASE * BASE / 2) / scale; -} - -function clampf (value, min_inclusive, max_inclusive) { - return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive; -} - -var Particles = function Particles (device, renderer$$1, config) { - this._device = device; - this._config = config; - this._sizeScale = 1; - this._accelScale = 1; - this._radiusScale = 1; - - var opts = {}; - var programLib = renderer$$1._programLib; - this.programs = { - emitter: programLib.getProgram('vfx_emitter', opts), - update: programLib.getProgram('vfx_update', opts), - quad: programLib.getProgram('vfx_quad', opts), - }; - - this.textures = { - // need swap - state0: new gfx.Texture2D(device, opts), - state1: new gfx.Texture2D(device, opts), - // no swap needed - noise: new gfx.Texture2D(device, opts), - quads: new gfx.Texture2D(device, opts), - }; - - this.framebuffers = { - state0: new gfx.FrameBuffer(device, 0, 0, { - colors: [this.textures.state0] - }), - state1: new gfx.FrameBuffer(device, 0, 0, { - colors: [this.textures.state1] - }), - quads: new gfx.FrameBuffer(device, 0, 0, { - colors: [this.textures.quads] - }) - }; - - var verts = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]); - var indices = new Uint8Array([ 0, 1, 2, 1, 3, 2]); - this.buffers = { - updateVB: new gfx.VertexBuffer(device, _vertexFmt, gfx.USAGE_STATIC, verts, 4), - updateIB: new gfx.IndexBuffer(device, gfx.INDEX_FMT_UINT8, gfx.USAGE_STATIC, indices, 6), - indexes: null, - particleCache: null - }; - - this._elapsed = 0; - this._stopped = false; - - this.updateMaxParticle(config); - this.updateSizeScale(config); - this.updateRadiusScale(config); - this.updateAccelScale(config); - - // Vector uniforms - this._pos = new Float32Array([config.sourcePos.x, config.sourcePos.y]); - this._posVar = new Float32Array([config.posVar.x, config.posVar.y]); - this._gravity = new Float32Array([config.gravity.x, config.gravity.y]); - this._color = new Float32Array([config.startColor.r, config.startColor.g, config.startColor.b, config.startColor.a]); - this._colorVar = new Float32Array([config.startColorVar.r, config.startColorVar.g, config.startColorVar.b, config.startColorVar.a]); - this._endColor = new Float32Array([config.endColor.r, config.endColor.g, config.endColor.b, config.endColor.a]); - this._endColorVar = new Float32Array([config.endColorVar.r, config.endColorVar.g, config.endColorVar.b, config.endColorVar.a]); -}; - -var prototypeAccessors$3 = { vertexFormat: {},particleCount: {},stopped: {},pos: {},posVar: {},gravity: {},startColor: {},startColorVar: {},endColor: {},endColorVar: {} }; - -prototypeAccessors$3.vertexFormat.get = function () { - return _vertexFmt; -}; - -// TODO: it's too slow, need other approach to retrieve the real particle count -prototypeAccessors$3.particleCount.get = function () { - var particleCount = 0; - var device = this._device; - device.setFrameBuffer(this.framebuffers.state0); - var w = this.statesize[0], h = this.statesize[1], - tw = this._tw, th = this._th, - rgba = this.buffers.particleCache; - device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); - for (var y = 0; y < th; y++) { - for (var x = 0; x < tw; x++) { - var offset = y * 3 * tw * 12 + x * 12; - var rest = decode(rgba, offset, LIFE_SCALE); - if (rest > 0) { - particleCount++; - } - } - } - return particleCount; -}; - -prototypeAccessors$3.stopped.get = function () { - return this._stopped; -}; - -Particles.prototype.updateMaxParticle = function updateMaxParticle (config) { - var emissionMax = Math.floor(config.emissionRate * (config.life + config.lifeVar)); - var maxParticle; - if (config.totalParticles > emissionMax) { - maxParticle = emissionMax; - this._emitVar = config.lifeVar; - } - else { - maxParticle = config.totalParticles; - this._emitVar = 0; - } - if (maxParticle !== this._maxParticle) { - this._maxParticle = maxParticle; - this._tw = Math.ceil(Math.sqrt(maxParticle)); - this._th = Math.floor(Math.sqrt(maxParticle)); - this.initTextures(); - this.initBuffers(); - } -}; - -prototypeAccessors$3.pos.set = function (pos) { - this._pos[0] = pos.x; - this._pos[1] = pos.y; -}; - -prototypeAccessors$3.posVar.set = function (posVar) { - this._posVar[0] = posVar.x; - this._posVar[1] = posVar.y; -}; - -prototypeAccessors$3.gravity.set = function (gravity) { - this._gravity[0] = gravity.x; - this._gravity[1] = gravity.y; -}; - -prototypeAccessors$3.startColor.set = function (color) { - this._color[0] = color.r; - this._color[1] = color.g; - this._color[2] = color.b; - this._color[3] = color.a; -}; - -prototypeAccessors$3.startColorVar.set = function (color) { - this._colorVar[0] = color.r; - this._colorVar[1] = color.g; - this._colorVar[2] = color.b; - this._colorVar[3] = color.a; -}; - -prototypeAccessors$3.endColor.set = function (color) { - this._endColor[0] = color.r; - this._endColor[1] = color.g; - this._endColor[2] = color.b; - this._endColor[3] = color.a; -}; - -prototypeAccessors$3.endColorVar.set = function (color) { - this._endColorVar[0] = color.r; - this._endColorVar[1] = color.g; - this._endColorVar[2] = color.b; - this._endColorVar[3] = color.a; -}; - -Particles.prototype._updateTex = function _updateTex (tex, data, width, height) { - _dataOpts.images.length = 1; - _dataOpts.images[0] = data; - _dataOpts.width = width; - _dataOpts.height = height; - tex.update(_dataOpts); -}; - -Particles.prototype._initNoise = function _initNoise () { - var tw = this._tw, th = this._th; - var w = (tw + 1) * 3, h = (th + 1) * 3; - var data = new Uint8Array(w * h * 4); - var offset = 0; - for (var y = 0; y < h; y++) { - for (var x = 0; x < w; x++) { - encode(Math.random(), NOISE_SCALE, data, offset); - encode(Math.random(), NOISE_SCALE, data, offset + 2); - offset += 4; - } - } - this._noisesize = new Float32Array([w, h]); - this._updateTex(this.textures.noise, data, w, h); -}; - -Particles.prototype.initTextures = function initTextures () { - var tw = this._tw, th = this._th; - this.statesize = new Float32Array([tw * 3, th * 3]); - this.quadsize = new Float32Array([tw * 2, th * 2]); - var data = new Uint8Array(tw * 3 * th * 3 * 4); - // decode([97, 97], 0, LIFE_SCALE); equals to -128, just for initalize a negative value in life - data.fill(97); - this._updateTex(this.textures.state0, data, tw * 3, th * 3); - this._updateTex(this.textures.state1, data, tw * 3, th * 3); - this._updateTex(this.textures.quads, null, tw * 2, th * 2); - this._initNoise(); -}; - -Particles.prototype.initBuffers = function initBuffers () { - var w = this.quadsize[0], h = this.quadsize[1], - indexes = new Float32Array(w * h * 2), - i = 0; - for (var y = 0; y < h; y++) { - for (var x = 0; x < w; x++) { - indexes[i + 0] = x; - indexes[i + 1] = y; - i += 2; - } - } - this.buffers.indexes = indexes; - this.buffers.particleCache = new Uint8Array(this.statesize[0] * this.statesize[1] * 4); -}; - -Particles.prototype.updateSizeScale = function updateSizeScale (config) { - var size = config.startSize, - sizeVar = config.startSizeVar, - endSize = config.endSize, - endSizeVar = config.endSizeVar; - var scale = Math.floor(Math.pow(BASE, 2) / Math.max(size + sizeVar, endSize + endSizeVar)); - this._sizeScale = clampf(scale, 1, MAX_SCALE); -}; - -Particles.prototype.updateAccelScale = function updateAccelScale (config) { - var radial = config.radialAccel, - radialVar = config.radialAccelVar, - tangential = config.tangentialAccel, - tangentialVar = config.tangentialAccelVar; - var accelScale = Math.floor(Math.pow(BASE, 2) / Math.max(Math.abs(radial) + radialVar, Math.abs(tangential) + tangentialVar) / 2); - this._accelScale = clampf(accelScale, 1, MAX_SCALE); -}; - -Particles.prototype.updateRadiusScale = function updateRadiusScale (config) { - var radius = config.startRadius, - radiusVar = config.startRadiusVar, - endRadius = config.endRadius, - endRadiusVar = config.endRadiusVar; - var scale = Math.floor(Math.pow(BASE, 2) / Math.max(Math.abs(radius) + radiusVar, Math.abs(endRadius) + endRadiusVar)); - this._radiusScale = clampf(scale, 1, MAX_SCALE); -}; - -Particles.prototype.resetSystem = function resetSystem () { - this._stopped = false; -}; - -Particles.prototype.stopSystem = function stopSystem () { - this._stopped = true; -}; - -Particles.prototype.getState = function getState (framebuffer) { - var this$1 = this; - - var device = this._device; - device.setFrameBuffer(framebuffer); - var w = this.statesize[0], h = this.statesize[1], - tw = this._tw, th = this._th, - rgba = new Uint8Array(w * h * 4); - device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); - var particles = []; - for (var y = 0; y < th; y++) { - for (var x = 0; x < tw; x++) { - var offset = y * 3 * tw * 12 + x * 12; - var colorI = offset + 1 * 4; - var deltaRGI = offset + 2 * 4; - var deltaBAI = offset + tw * 12; - var sizeI = offset + tw * 12 + 1 * 4; - var rotI = offset + tw * 12 + 2 * 4; - var control1I = offset + 2 * tw * 12; - var control2I = offset + 2 * tw * 12 + 1 * 4; - var posI = offset + 2 * tw * 12 + 2 * 4; - - var rest = decode(rgba, offset, LIFE_SCALE); - var life = decode(rgba, offset + 2, LIFE_SCALE); - var color = { - r: rgba[colorI], - g: rgba[colorI+1], - b: rgba[colorI+2], - a: rgba[colorI+3] - }; - var deltaColor = { - r: decode(rgba, deltaRGI, COLOR_SCALE), - g: decode(rgba, deltaRGI + 2, COLOR_SCALE), - b: decode(rgba, deltaBAI, COLOR_SCALE), - a: decode(rgba, deltaBAI + 2, COLOR_SCALE) - }; - var size = decode(rgba, sizeI, this$1._sizeScale); - var deltaSize = decode(rgba, sizeI + 2, this$1._sizeScale); - var rot = decode(rgba, rotI, ROTATION_SCALE); - var deltaRot = decode(rgba, rotI + 2, ROTATION_SCALE); - var control = (void 0); - if (this$1._config.emitterMode === 0) { - control = [ - decode(rgba, control1I, POS_SCALE), - decode(rgba, control1I + 2, POS_SCALE), - decode(rgba, control2I, this$1._accelScale), - decode(rgba, control2I + 2, this$1._accelScale) - ]; - } - else { - control = [ - decode(rgba, control1I, ROTATION_SCALE), - decode(rgba, control1I + 2, this$1._radiusScale), - decode(rgba, control2I, ROTATION_SCALE), - decode(rgba, control2I + 2, this$1._radiusScale) - ]; - } - var pos = { - x: decode(rgba, posI, POS_SCALE), - y: decode(rgba, posI + 2, POS_SCALE) - }; - particles.push({ - rest: rest, - life: life, - color: color, - deltaColor: deltaColor, - size: size, - deltaSize: deltaSize, - rot: rot, - deltaRot: deltaRot, - control: control, - pos: pos - }); - } - } - return particles; -}; - -Particles.prototype.getNoise = function getNoise () { - var device = this._device; - var framebuffer = new gfx.FrameBuffer(device, 0, 0, { - colors: [this.textures.noise] - }); - device.setFrameBuffer(framebuffer); - var w = this._noisesize[0], h = this._noisesize[1], - rgba = new Uint8Array(w * h * 4); - device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); - var noises = []; - var offset = 0; - for (var y = 0; y < h; y++) { - for (var x = 0; x < w; x++) { - noises.push(decode(rgba, offset, 10000)); - noises.push(decode(rgba, offset+2, 10000)); - offset += 4; - } - } - return noises; -}; - -Particles.prototype.getQuads = function getQuads () { - var device = this._device; - var framebuffer = new gfx.FrameBuffer(device, 0, 0, { - colors: [this.textures.quads] - }); - device.setFrameBuffer(framebuffer); - var w = this.quadsize[0], h = this.quadsize[1], - rgba = new Uint8Array(w * h * 4); - device._gl.readPixels(0, 0, w, h, device._gl.RGBA, device._gl.UNSIGNED_BYTE, rgba); - var quads = []; - var off1 = 0, off2 = 0; - for (var y = 0; y < h; y += 2) { - for (var x = 0; x < w; x += 2) { - off1 = (y * w + x) * 4; - off2 = ((y + 1) * w + x) * 4; - quads.push([ - decode(rgba, off1, POS_SCALE), - decode(rgba, off1+2, POS_SCALE), - decode(rgba, off1+4, POS_SCALE), - decode(rgba, off1+6, POS_SCALE), - decode(rgba, off2, POS_SCALE), - decode(rgba, off2+2, POS_SCALE), - decode(rgba, off2+4, POS_SCALE), - decode(rgba, off2+6, POS_SCALE) - ]); - } - } - return quads; -}; - -Particles.prototype.step = function step (dt) { - var config = this._config; - var device = this._device; - - // setup - device.setViewport(0, 0, this.statesize[0], this.statesize[1]); - - // Emitter - device.setFrameBuffer(this.framebuffers.state1); - device.setTexture('noise', this.textures.noise, 0); - device.setTexture('state', this.textures.state0, 1); - device.setUniform('statesize', this.statesize); - device.setUniform('noisesize', this._noisesize); - device.setUniform('stopped', this._stopped); - device.setUniform('dt', dt); - device.setUniform('mode', config.emitterMode); - device.setUniform('noiseId', Math.floor(Math.random() * 16)); - device.setUniform('emitVar', this._emitVar); - device.setUniform('life', config.life); - device.setUniform('lifeVar', config.lifeVar); - device.setUniform('pos', this._pos); - device.setUniform('posVar', this._posVar); - device.setUniform('color', this._color); - device.setUniform('colorVar', this._colorVar); - device.setUniform('endColor', this._endColor); - device.setUniform('endColorVar', this._endColorVar); - device.setUniform('size', config.startSize); - device.setUniform('sizeVar', config.startSizeVar); - device.setUniform('endSize', config.endSize); - device.setUniform('endSizeVar', config.endSizeVar); - device.setUniform('rot', config.startSpin); - device.setUniform('rotVar', config.startSpinVar); - device.setUniform('endRot', config.endSpin); - device.setUniform('endRotVar', config.endSpinVar); - device.setUniform('angle', config.angle); - device.setUniform('angleVar', config.angleVar); - device.setUniform('speed', config.speed); - device.setUniform('speedVar', config.speedVar); - device.setUniform('radial', config.radialAccel); - device.setUniform('radialVar', config.radialAccelVar); - device.setUniform('tangent', config.tangentialAccel); - device.setUniform('tangentVar', config.tangentialAccelVar); - device.setUniform('radius', config.startRadius); - device.setUniform('radiusVar', config.startRadiusVar); - device.setUniform('endRadius', config.endRadius); - device.setUniform('endRadiusVar', config.endRadiusVar); - device.setUniform('rotatePS', config.rotatePerS); - device.setUniform('rotatePSVar', config.rotatePerSVar); - device.setUniform('sizeScale', this._sizeScale); - device.setUniform('accelScale', this._accelScale); - device.setUniform('radiusScale', this._radiusScale); - device.setVertexBuffer(0, this.buffers.updateVB); - device.setIndexBuffer(this.buffers.updateIB); - device.setProgram(this.programs.emitter); - device.draw(0, this.buffers.updateIB.count); - - // Update - device.setFrameBuffer(this.framebuffers.state0); - device.setTexture('state', this.textures.state1, 0); - device.setUniform('statesize', this.statesize); - device.setUniform('dt', dt); - device.setUniform('mode', config.emitterMode); - device.setUniform('gravity', this._gravity); - device.setUniform('sizeScale', this._sizeScale); - device.setUniform('accelScale', this._accelScale); - device.setUniform('radiusScale', this._radiusScale); - device.setVertexBuffer(0, this.buffers.updateVB); - device.setIndexBuffer(this.buffers.updateIB); - device.setProgram(this.programs.update); - device.draw(0, this.buffers.updateIB.count); - - // Draw quad - device.setViewport(0, 0, this._tw * 2, this._th * 2); - device.setFrameBuffer(this.framebuffers.quads); - device.setTexture('state', this.textures.state0, 0); - device.setUniform('quadsize', this.quadsize); - device.setUniform('statesize', this.statesize); - device.setUniform('sizeScale', this._sizeScale); - device.setVertexBuffer(0, this.buffers.updateVB); - device.setIndexBuffer(this.buffers.updateIB); - device.setProgram(this.programs.quad); - device.draw(0, this.buffers.updateIB.count); - - this._elapsed += dt; - if (config.duration !== -1 && config.duration < this._elapsed) { - this.stopSystem(); - } -}; - -Object.defineProperties( Particles.prototype, prototypeAccessors$3 ); - -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -var Asset = function Asset(persist) { - if ( persist === void 0 ) persist = true; - - this._loaded = false; - this._persist = persist; -}; - -Asset.prototype.unload = function unload () { - this._loaded = false; -}; - -Asset.prototype.reload = function reload () { - // TODO -}; - -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -var Texture = (function (Asset$$1) { - function Texture(persist) { - if ( persist === void 0 ) persist = true; - - Asset$$1.call(this, persist); - - this._texture = null; - } - - if ( Asset$$1 ) Texture.__proto__ = Asset$$1; - Texture.prototype = Object.create( Asset$$1 && Asset$$1.prototype ); - Texture.prototype.constructor = Texture; - - Texture.prototype.getImpl = function getImpl () { - return this._texture; - }; - - Texture.prototype.getId = function getId () {}; - - Texture.prototype.destroy = function destroy () { - this._texture && this._texture.destroy(); - }; - - return Texture; -}(Asset)); - -/** - * JS Implementation of MurmurHash2 - * - * @author Gary Court - * @see http://github.com/garycourt/murmurhash-js - * @author Austin Appleby - * @see http://sites.google.com/site/murmurhash/ - * - * @param {string} str ASCII only - * @param {number} seed Positive integer only - * @return {number} 32-bit positive integer hash - */ - -function murmurhash2_32_gc(str, seed) { - var - l = str.length, - h = seed ^ l, - i = 0, - k; - - while (l >= 4) { - k = - ((str.charCodeAt(i) & 0xff)) | - ((str.charCodeAt(++i) & 0xff) << 8) | - ((str.charCodeAt(++i) & 0xff) << 16) | - ((str.charCodeAt(++i) & 0xff) << 24); - - k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); - k ^= k >>> 24; - k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); - - h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; - - l -= 4; - ++i; - } - - switch (l) { - case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; - case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; - case 1: h ^= (str.charCodeAt(i) & 0xff); - h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); - } - - h ^= h >>> 13; - h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); - h ^= h >>> 15; - - return h >>> 0; -} - -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -// function genHashCode (str) { -// var hash = 0; -// if (str.length == 0) { -// return hash; -// } -// for (var i = 0; i < str.length; i++) { -// var char = str.charCodeAt(i); -// hash = ((hash<<5)-hash)+char; -// hash = hash & hash; // Convert to 32bit integer -// } -// return hash; -// } - -function serializeDefines (defines) { - var str = ''; - for (var i = 0; i < defines.length; i++) { - str += defines[i].name + defines[i].value; - } - return str; -} - -function serializePass (pass) { - var str = pass._programName + pass._cullMode; - if (pass._blend) { - str += pass._blendEq + pass._blendAlphaEq + pass._blendSrc + pass._blendDst - + pass._blendSrcAlpha + pass._blendDstAlpha + pass._blendColor; - } - if (pass._depthTest) { - str += pass._depthWrite + pass._depthFunc; - } - if (pass._stencilTest) { - str += pass._stencilFuncFront + pass._stencilRefFront + pass._stencilMaskFront - + pass._stencilFailOpFront + pass._stencilZFailOpFront + pass._stencilZPassOpFront - + pass._stencilWriteMaskFront - + pass._stencilFuncBack + pass._stencilRefBack + pass._stencilMaskBack - + pass._stencilFailOpBack + pass._stencilZFailOpBack + pass._stencilZPassOpBack - + pass._stencilWriteMaskBack; - } - return str; -} - -function computeHash(material) { - var effect = material._effect; - var hashData = ''; - if (effect) { - var i, j, techData, param, prop, propKey; - - // effect._defines - hashData += serializeDefines(effect._defines); - // effect._techniques - for (i = 0; i < effect._techniques.length; i++) { - techData = effect._techniques[i]; - // technique.stageIDs - hashData += techData.stageIDs; - // technique._layer - // hashData += + techData._layer + "_"; - // technique.passes - for (j = 0; j < techData.passes.length; j++) { - hashData += serializePass(techData.passes[j]); - } - //technique._parameters - for (j = 0; j < techData._parameters.length; j++) { - param = techData._parameters[j]; - propKey = param.name; - prop = effect._properties[propKey]; - if (!prop) { - continue; - } - switch(param.type) { - case renderer.PARAM_INT: - case renderer.PARAM_FLOAT: - hashData += prop + ';'; - break; - case renderer.PARAM_INT2: - case renderer.PARAM_FLOAT2: - hashData += prop.x + ',' + prop.y + ';'; - break; - case renderer.PARAM_INT4: - case renderer.PARAM_FLOAT4: - hashData += prop.x + ',' + prop.y + ',' + prop.z + ',' + prop.w + ';'; - break; - case renderer.PARAM_COLOR4: - hashData += prop.r + ',' + prop.g + ',' + prop.b + ',' + prop.a + ';'; - break; - case renderer.PARAM_MAT2: - hashData += prop.m00 + ',' + prop.m01 + ',' + prop.m02 + ',' + prop.m03 + ';'; - break; - case renderer.PARAM_TEXTURE_2D: - case renderer.PARAM_TEXTURE_CUBE: - hashData += material._texIds[propKey] + ';'; - break; - case renderer.PARAM_INT3: - case renderer.PARAM_FLOAT3: - case renderer.PARAM_COLOR3: - case renderer.PARAM_MAT3: - case renderer.PARAM_MAT4: - hashData += JSON.stringify(prop) + ';'; - break; - default: - break; - } - } - } - } - return hashData ? murmurhash2_32_gc(hashData, 666) : hashData; -} - -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -var Material = (function (Asset$$1) { - function Material(persist) { - if ( persist === void 0 ) persist = false; - - Asset$$1.call(this, persist); - - this._effect = null; // renderer.Effect - this._texIds = {}; // ids collected from texture defines - this._hash = ''; - } - - if ( Asset$$1 ) Material.__proto__ = Asset$$1; - Material.prototype = Object.create( Asset$$1 && Asset$$1.prototype ); - Material.prototype.constructor = Material; - - var prototypeAccessors = { hash: {} }; - - prototypeAccessors.hash.get = function () { - return this._hash; - }; - - Material.prototype.updateHash = function updateHash (value) { - this._hash = value || computeHash(this); - }; - - Object.defineProperties( Material.prototype, prototypeAccessors ); - - return Material; -}(Asset)); - -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -var SpriteMaterial = (function (Material$$1) { - function SpriteMaterial() { - Material$$1.call(this, false); - - var pass = new renderer.Pass('sprite'); - pass.setDepth(false, false); - pass.setCullMode(gfx.CULL_NONE); - pass.setBlend( - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA - ); - - var mainTech = new renderer.Technique( - ['transparent'], - [ - { name: 'texture', type: renderer.PARAM_TEXTURE_2D } ], - [ - pass - ] - ); - - this._effect = new renderer.Effect( - [ - mainTech ], - {}, - [ - { name: 'useTexture', value: true }, - { name: 'useModel', value: false }, - { name: 'alphaTest', value: false } ] - ); - - this._mainTech = mainTech; - this._texture = null; - } - - if ( Material$$1 ) SpriteMaterial.__proto__ = Material$$1; - SpriteMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); - SpriteMaterial.prototype.constructor = SpriteMaterial; - - var prototypeAccessors = { effect: {},useTexture: {},useModel: {},texture: {} }; - - prototypeAccessors.effect.get = function () { - return this._effect; - }; - - prototypeAccessors.useTexture.get = function () { - this._effect.getDefine('useTexture', val); - }; - - prototypeAccessors.useTexture.set = function (val) { - this._effect.define('useTexture', val); - }; - - prototypeAccessors.useModel.get = function () { - this._effect.getDefine('useModel', val); - }; - - prototypeAccessors.useModel.set = function (val) { - this._effect.define('useModel', val); - }; - - prototypeAccessors.texture.get = function () { - return this._texture; - }; - - prototypeAccessors.texture.set = function (val) { - if (this._texture !== val) { - this._texture = val; - this._effect.setProperty('texture', val.getImpl()); - this._texIds['texture'] = val.getId(); - } - }; - - SpriteMaterial.prototype.clone = function clone () { - var copy = new SpriteMaterial(); - copy.texture = this.texture; - copy.useTexture = this.useTexture; - copy.useModel = this.useModel; - copy.updateHash(); - return copy; - }; - - Object.defineProperties( SpriteMaterial.prototype, prototypeAccessors ); - - return SpriteMaterial; -}(Material)); - -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -var GraySpriteMaterial = (function (Material$$1) { - function GraySpriteMaterial() { - Material$$1.call(this, false); - - var pass = new renderer.Pass('gray_sprite'); - pass.setDepth(false, false); - pass.setCullMode(gfx.CULL_NONE); - pass.setBlend( - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA - ); - - var mainTech = new renderer.Technique( - ['transparent'], - [ - { name: 'texture', type: renderer.PARAM_TEXTURE_2D } ], - [ - pass - ] - ); - - this._effect = new renderer.Effect( - [ - mainTech ], - {}, - [] - ); - - this._mainTech = mainTech; - this._texture = null; - } - - if ( Material$$1 ) GraySpriteMaterial.__proto__ = Material$$1; - GraySpriteMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); - GraySpriteMaterial.prototype.constructor = GraySpriteMaterial; - - var prototypeAccessors = { effect: {},texture: {} }; - - prototypeAccessors.effect.get = function () { - return this._effect; - }; - - prototypeAccessors.texture.get = function () { - return this._texture; - }; - - prototypeAccessors.texture.set = function (val) { - if (this._texture !== val) { - this._texture = val; - this._effect.setProperty('texture', val.getImpl()); - this._texIds['texture'] = val.getId(); - } - }; - - GraySpriteMaterial.prototype.clone = function clone () { - var copy = new GraySpriteMaterial(); - copy.texture = this.texture; - copy.updateHash(); - return copy; - }; - - Object.defineProperties( GraySpriteMaterial.prototype, prototypeAccessors ); - - return GraySpriteMaterial; -}(Material)); - -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -var StencilMaterial = (function (Material$$1) { - function StencilMaterial() { - Material$$1.call(this, false); - - this._pass = new renderer.Pass('sprite'); - this._pass.setDepth(false, false); - this._pass.setCullMode(gfx.CULL_NONE); - this._pass.setBlend( - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, - gfx.BLEND_FUNC_ADD, - gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA - ); - - var mainTech = new renderer.Technique( - ['transparent'], - [ - { name: 'texture', type: renderer.PARAM_TEXTURE_2D }, - { name: 'alphaThreshold', type: renderer.PARAM_FLOAT } ], - [ - this._pass - ] - ); - - this._effect = new renderer.Effect( - [ - mainTech ], - {}, - [ - { name: 'useTexture', value: true }, - { name: 'useModel', value: false }, - { name: 'alphaTest', value: true } ] - ); - - this._mainTech = mainTech; - this._texture = null; - } - - if ( Material$$1 ) StencilMaterial.__proto__ = Material$$1; - StencilMaterial.prototype = Object.create( Material$$1 && Material$$1.prototype ); - StencilMaterial.prototype.constructor = StencilMaterial; - - var prototypeAccessors = { effect: {},useTexture: {},texture: {},alphaThreshold: {} }; - - prototypeAccessors.effect.get = function () { - return this._effect; - }; - - prototypeAccessors.useTexture.get = function () { - this._effect.getDefine('useTexture', val); - }; - - prototypeAccessors.useTexture.set = function (val) { - this._effect.define('useTexture', val); - }; - - prototypeAccessors.texture.get = function () { - return this._texture; - }; - - prototypeAccessors.texture.set = function (val) { - if (this._texture !== val) { - this._texture = val; - this._effect.setProperty('texture', val.getImpl()); - this._texIds['texture'] = val.getId(); - } - }; - - prototypeAccessors.alphaThreshold.get = function () { - return this._effect.getProperty('alphaThreshold'); - }; - - prototypeAccessors.alphaThreshold.set = function (val) { - this._effect.setProperty('alphaThreshold', val); - }; - - StencilMaterial.prototype.clone = function clone () { - var copy = new StencilMaterial(); - copy.useTexture = this.useTexture; - copy.texture = this.texture; - copy.alphaThreshold = this.alphaThreshold; - copy.updateHash(); - return copy; - }; - - Object.defineProperties( StencilMaterial.prototype, prototypeAccessors ); - - return StencilMaterial; -}(Material)); - // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. var ParticleMaterial = (function (Material$$1) { @@ -10167,6 +10089,4 @@ var renderEngine = { gfx: gfx, }; -return renderEngine; - -}()); +module.exports = renderEngine; diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index d4f07876b7..dbf5345cbe 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -45,7 +45,7 @@ var jsbSkipModules = [ ]; var aliasifyConfig = { replacements: { - '(.*)render-engine(.js)?': './cocos2d/core/renderer/render-engine.jsb' + '(.*)render-engine(.js)?': require.resolve('../../cocos2d/core/renderer/render-engine.jsb') }, verbose: false }; diff --git a/index.js b/index.js index 12f2f0a141..24ab9e0b98 100644 --- a/index.js +++ b/index.js @@ -26,6 +26,9 @@ // PREDEFINE +// window may be undefined when first load engine from editor +var _global = typeof window === 'undefined' ? global : window; + /** * !#en * The main namespace of Cocos2d-JS, all engine core classes, functions, properties and constants are defined in this namespace. @@ -34,7 +37,7 @@ * @module cc * @main cc */ -cc = cc || {}; +cc = _global.cc || {}; require('./predefine'); require('./CCDebugger'); From 86585d6a01d211b47fa7f97e9dbfc84026ff45ab Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 8 Apr 2018 00:40:07 +0800 Subject: [PATCH 33/35] Explicitly destroy old gl texture before update --- cocos2d/core/assets/CCTexture2D.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cocos2d/core/assets/CCTexture2D.js b/cocos2d/core/assets/CCTexture2D.js index fb45d17a63..ab17030026 100644 --- a/cocos2d/core/assets/CCTexture2D.js +++ b/cocos2d/core/assets/CCTexture2D.js @@ -362,6 +362,9 @@ var Texture2D = cc.Class({ this._image = options.images[0]; } else if (options.image !== undefined) { + // Release previous gl texture if existed + this._texture.destroy(); + this._image = options.image; if (!options.images) { _images.length = 0; From f0cdd047f07aa63a759ad913238a1426235073a5 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 8 Apr 2018 16:05:58 +0800 Subject: [PATCH 34/35] Fix stage not added issue in JSB --- cocos2d/core/renderer/render-engine.js | 6 +++--- cocos2d/core/renderer/render-engine.jsb.js | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/renderer/render-engine.js b/cocos2d/core/renderer/render-engine.js index e13d544a30..bb9888eeab 100644 --- a/cocos2d/core/renderer/render-engine.js +++ b/cocos2d/core/renderer/render-engine.js @@ -13503,9 +13503,6 @@ var _a16_view = new Float32Array(16); var _a16_proj = new Float32Array(16); var _a16_viewProj = new Float32Array(16); -// Add stage to renderer -renderer.addStage('transparent'); - var ForwardRenderer = (function (superclass) { function ForwardRenderer (device, builtin) { superclass.call(this, device, builtin); @@ -15058,6 +15055,9 @@ var Device$4 = gfx.Device; var Model$2 = renderer.Model; var InputAssembler$2 = renderer.InputAssembler; +// Add stage to renderer +renderer.addStage('transparent'); + var renderEngine = { // core classes Device: Device$4, diff --git a/cocos2d/core/renderer/render-engine.jsb.js b/cocos2d/core/renderer/render-engine.jsb.js index 236a71331e..cb499b03fe 100644 --- a/cocos2d/core/renderer/render-engine.jsb.js +++ b/cocos2d/core/renderer/render-engine.jsb.js @@ -10044,6 +10044,9 @@ var Device$2 = gfx.Device; var Model = renderer.Model; var InputAssembler = renderer.InputAssembler; +// Add stage to renderer +renderer.addStage('transparent'); + var renderEngine = { // core classes Device: Device$2, From 4d8e97a4a991992e03935ccdc5b5bcb873b81039 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Tue, 10 Apr 2018 13:58:31 +0800 Subject: [PATCH 35/35] support mesh sprite --- cocos2d/core/assets/CCSpriteFrame.js | 34 +++- cocos2d/core/components/CCSprite.js | 20 ++- .../renderer/assemblers/sprite/bar-filled.js | 2 +- .../core/renderer/assemblers/sprite/index.js | 6 +- .../core/renderer/assemblers/sprite/mesh.js | 170 ++++++++++++++++++ .../assemblers/sprite/radial-filled.js | 1 - .../core/renderer/assemblers/sprite/simple.js | 76 ++++---- .../core/renderer/assemblers/sprite/sliced.js | 74 ++++---- .../core/renderer/assemblers/sprite/tiled.js | 3 - 9 files changed, 295 insertions(+), 91 deletions(-) create mode 100644 cocos2d/core/renderer/assemblers/sprite/mesh.js diff --git a/cocos2d/core/assets/CCSpriteFrame.js b/cocos2d/core/assets/CCSpriteFrame.js index da911febfa..55d44c41cb 100644 --- a/cocos2d/core/assets/CCSpriteFrame.js +++ b/cocos2d/core/assets/CCSpriteFrame.js @@ -153,6 +153,8 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ */ this.insetRight = 0; + this.vertices = null; + this._texture = null; this._textureFilename = ''; @@ -459,6 +461,18 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ } }, + _normalizeUV () { + let vertices = this.vertices; + let tw = this._texture.width; + let th = this._texture.height; + vertices.nu = []; + vertices.nv = []; + for (let i = 0; i < vertices.u.length; i++) { + vertices.nu[i] = vertices.u[i]/tw; + vertices.nv[i] = vertices.v[i]/th; + } + }, + // SERIALIZATION _serialize: CC_EDITOR && function (exporting) { @@ -486,6 +500,18 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ this.insetBottom !== 0) { capInsets = [this.insetLeft, this.insetTop, this.insetRight, this.insetBottom]; } + + let vertices; + if (this.vertices) { + vertices = { + triangles: this.vertices.triangles, + x: this.vertices.x, + y: this.vertices.y, + u: this.vertices.u, + v: this.vertices.v + }; + } + return { name: this._name, texture: uuid || undefined, @@ -494,7 +520,8 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ offset: offset ? [offset.x, offset.y] : undefined, originalSize: size ? [size.width, size.height] : undefined, rotated: this._rotated ? 1 : undefined, - capInsets: capInsets + capInsets: capInsets, + vertices: vertices }; }, @@ -522,6 +549,11 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ this._atlasUuid = data.atlas; } + if (data.vertices) { + this.vertices = data.vertices; + this.on('load', this._normalizeUV, this); + } + // load texture via _textureSetter var textureUuid = data.texture; if (textureUuid) { diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 1df91fd658..0b97ae1be5 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -370,8 +370,10 @@ var Sprite = cc.Class({ set: function (value) { if (this._isTrimmedMode !== value) { this._isTrimmedMode = value; - if (this._type === SpriteType.SIMPLE && this._renderData) { + if ((this._type === SpriteType.SIMPLE || this._type === SpriteType.MESH) && + this._renderData) { this._renderData.uvDirty = true; + this._renderData.vertDirty = true; } } }, @@ -519,6 +521,7 @@ var Sprite = cc.Class({ if (!this._renderData) { this._renderData = this._assembler.createData(this); this._renderData.worldMatDirty = true; + this._renderData.material = this._material; } }, @@ -651,13 +654,18 @@ var Sprite = cc.Class({ } var spriteFrame = this._spriteFrame; - if (spriteFrame && (!oldFrame || spriteFrame._texture !== oldFrame._texture)) { - if (spriteFrame.textureLoaded()) { - this._onTextureLoaded(null); + if (spriteFrame) { + if (!oldFrame || spriteFrame._texture !== oldFrame._texture) { + if (spriteFrame.textureLoaded()) { + this._onTextureLoaded(null); + } + else { + spriteFrame.once('load', this._onTextureLoaded, this); + spriteFrame.ensureLoadTexture(); + } } else { - spriteFrame.once('load', this._onTextureLoaded, this); - spriteFrame.ensureLoadTexture(); + this._applySpriteSize(); } } diff --git a/cocos2d/core/renderer/assemblers/sprite/bar-filled.js b/cocos2d/core/renderer/assemblers/sprite/bar-filled.js index 08648ac7d6..bd3f2ead10 100644 --- a/cocos2d/core/renderer/assemblers/sprite/bar-filled.js +++ b/cocos2d/core/renderer/assemblers/sprite/bar-filled.js @@ -63,7 +63,7 @@ module.exports = { if (vertDirty) { this.updateVerts(sprite, fillStart, fillEnd); } - if (renderData.worldMatDirty) { + if (vertDirty || renderData.worldMatDirty) { this.updateWorldVerts(sprite); } }, diff --git a/cocos2d/core/renderer/assemblers/sprite/index.js b/cocos2d/core/renderer/assemblers/sprite/index.js index b745844428..97aaafbe87 100644 --- a/cocos2d/core/renderer/assemblers/sprite/index.js +++ b/cocos2d/core/renderer/assemblers/sprite/index.js @@ -35,6 +35,7 @@ const slicedRenderUtil = require('./sliced'); const tiledRenderUtil = require('./tiled'); const radialFilledRenderUtil = require('./radial-filled'); const barFilledRenderUtil = require('./bar-filled'); +const meshRenderUtil = require('./mesh'); // Inline all type switch to avoid jit deoptimization during inlined function change let spriteAssembler = js.addon({ @@ -58,6 +59,9 @@ let spriteAssembler = js.addon({ util = barFilledRenderUtil; } break; + case SpriteType.MESH: + util = meshRenderUtil; + break; } return util; @@ -65,7 +69,7 @@ let spriteAssembler = js.addon({ updateRenderData (sprite) { let datas = sprite.__allocedDatas; - if (!sprite.spriteFrame) { + if (!sprite.spriteFrame || !sprite.getMaterial() || !sprite._renderData) { return datas; } diff --git a/cocos2d/core/renderer/assemblers/sprite/mesh.js b/cocos2d/core/renderer/assemblers/sprite/mesh.js new file mode 100644 index 0000000000..799da554a3 --- /dev/null +++ b/cocos2d/core/renderer/assemblers/sprite/mesh.js @@ -0,0 +1,170 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +module.exports = { + createData (sprite) { + return sprite.requestRenderData(); + }, + + update (sprite) { + let renderData = sprite._renderData; + let frame = sprite.spriteFrame; + + let vertices = frame.vertices; + if (!vertices) return; + + if (renderData.vertexCount !== vertices.x.length) { + renderData.vertexCount = vertices.x.length; + renderData.indiceCount = vertices.triangles.length; + + // 1 for world vertices, 2 for local vertices + renderData.dataLength = renderData.vertexCount * 2; + + renderData.uvDirty = renderData.vertDirty = true; + } + + if (renderData.uvDirty) { + this.updateUVs(sprite); + } + let vertDirty = renderData.vertDirty; + if (vertDirty) { + this.updateVerts(sprite); + } + if (vertDirty || renderData.worldMatDirty) { + this.updateWorldVerts(sprite); + } + }, + + updateUVs (sprite) { + let material = sprite.getMaterial(); + let texture = material.effect.getProperty('texture'); + let texw = texture._width, + texh = texture._height; + + let vertices = sprite.spriteFrame.vertices, + u = vertices.nu, + v = vertices.nv; + + let renderData = sprite._renderData; + let data = renderData._data; + for (let i = 0, l = u.length; i < l; i++) { + let vertice = data[i]; + vertice.u = u[i]; + vertice.v = v[i]; + } + + renderData.uvDirty = false; + }, + + updateVerts (sprite) { + let node = sprite.node, + contentWidth = Math.abs(node.width), + contentHeight = Math.abs(node.height), + appx = node.anchorX * contentWidth, + appy = node.anchorY * contentHeight; + + let frame = sprite.spriteFrame, + vertices = frame.vertices, + x = vertices.x, + y = vertices.y, + originalWidth = frame._originalSize.width, + originalHeight = frame._originalSize.height, + rectWidth = frame._rect.width, + rectHeight = frame._rect.height, + offsetX = frame._offset.x, + offsetY = frame._offset.y; + trimX = offsetX + (originalWidth - rectWidth) / 2, + trimY = offsetY + (originalHeight - rectHeight) / 2; + + let scaleX = contentWidth / (sprite.trim ? rectWidth : originalWidth), + scaleY = contentHeight / (sprite.trim ? rectHeight : originalHeight); + + let renderData = sprite._renderData; + let data = renderData._data; + + if (!sprite.trim) { + for (let i = 0, l = x.length; i < l; i++) { + let vertice = data[i+l]; + vertice.x = (x[i]) * scaleX - appx; + vertice.y = (originalHeight - y[i]) * scaleY - appy; + } + } + else { + for (let i = 0, l = x.length; i < l; i++) { + let vertice = data[i+l]; + vertice.x = (x[i] - trimX) * scaleX - appx; + vertice.y = (originalHeight - y[i] - trimY) * scaleY - appy; + } + } + + renderData.vertDirty = false; + }, + + updateWorldVerts (sprite) { + let node = sprite.node, + renderData = sprite._renderData, + data = renderData._data, + matrix = node._worldMatrix; + let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, + tx = matrix.m12, ty = matrix.m13; + + for (let i = 0, l = renderData.vertexCount; i < l; i++) { + let local = data[i+l]; + let world = data[i]; + world.x = local.x * a + local.y * c + tx; + world.y = local.x * b + local.y * d + ty; + } + + renderData.worldMatDirty = false; + }, + + fillBuffers (sprite, batchData, vertexId, vbuf, uintbuf, ibuf) { + let vertexOffset = batchData.byteOffset / 4, + indiceOffset = batchData.indiceOffset; + + // update verts + let node = sprite.node; + let renderData = sprite._renderData; + let data = renderData._data; + let z = node._position.z; + let color = node._color._val; + + for (let i = 0, l = renderData.vertexCount; i < l; i++) { + let vertice = data[i]; + vbuf[vertexOffset++] = vertice.x; + vbuf[vertexOffset++] = vertice.y; + vbuf[vertexOffset++] = z; + uintbuf[vertexOffset++] = color; + vbuf[vertexOffset++] = vertice.u; + vbuf[vertexOffset++] = vertice.v; + } + + let triangles = sprite.spriteFrame.vertices.triangles; + + for (let i = 0, l = triangles.length; i < l; i++) { + ibuf[indiceOffset++] = vertexId + triangles[i]; + } + } +}; \ No newline at end of file diff --git a/cocos2d/core/renderer/assemblers/sprite/radial-filled.js b/cocos2d/core/renderer/assemblers/sprite/radial-filled.js index 2e6a98e547..d0dcfb74bd 100644 --- a/cocos2d/core/renderer/assemblers/sprite/radial-filled.js +++ b/cocos2d/core/renderer/assemblers/sprite/radial-filled.js @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ -const Sprite = require('../../../components/CCSprite'); const simpleRenderUtil = require('./simple'); const PI_2 = Math.PI * 2; diff --git a/cocos2d/core/renderer/assemblers/sprite/simple.js b/cocos2d/core/renderer/assemblers/sprite/simple.js index 900dd079d0..71f2da53cd 100644 --- a/cocos2d/core/renderer/assemblers/sprite/simple.js +++ b/cocos2d/core/renderer/assemblers/sprite/simple.js @@ -23,8 +23,6 @@ THE SOFTWARE. ****************************************************************************/ -const Sprite = require('../../../components/CCSprite'); - const js = require('../../../platform/js'); const assembler = require('../assembler'); @@ -87,45 +85,43 @@ module.exports = js.addon({ updateUVs (sprite) { let material = sprite.getMaterial(); let renderData = sprite._renderData; - if (material && renderData) { - let data = renderData._data; - let texture = material.effect.getProperty('texture'); - let texw = texture._width, - texh = texture._height; - let frame = sprite.spriteFrame; - let rect = frame._rect; - - if (frame._rotated) { - let l = texw === 0 ? 0 : rect.x / texw; - let r = texw === 0 ? 0 : (rect.x + rect.height) / texw; - let b = texh === 0 ? 0 : (rect.y + rect.width) / texh; - let t = texh === 0 ? 0 : rect.y / texh; - data[0].u = l; - data[0].v = t; - data[1].u = l; - data[1].v = b; - data[2].u = r; - data[2].v = t; - data[3].u = r; - data[3].v = b; - } - else { - let l = texw === 0 ? 0 : rect.x / texw; - let r = texw === 0 ? 0 : (rect.x + rect.width) / texw; - let b = texh === 0 ? 0 : (rect.y + rect.height) / texh; - let t = texh === 0 ? 0 : rect.y / texh; - data[0].u = l; - data[0].v = b; - data[1].u = r; - data[1].v = b; - data[2].u = l; - data[2].v = t; - data[3].u = r; - data[3].v = t; - } - - renderData.uvDirty = false; + let data = renderData._data; + let texture = material.effect.getProperty('texture'); + let texw = texture._width, + texh = texture._height; + let frame = sprite.spriteFrame; + let rect = frame._rect; + + if (frame._rotated) { + let l = texw === 0 ? 0 : rect.x / texw; + let r = texw === 0 ? 0 : (rect.x + rect.height) / texw; + let b = texh === 0 ? 0 : (rect.y + rect.width) / texh; + let t = texh === 0 ? 0 : rect.y / texh; + data[0].u = l; + data[0].v = t; + data[1].u = l; + data[1].v = b; + data[2].u = r; + data[2].v = t; + data[3].u = r; + data[3].v = b; } + else { + let l = texw === 0 ? 0 : rect.x / texw; + let r = texw === 0 ? 0 : (rect.x + rect.width) / texw; + let b = texh === 0 ? 0 : (rect.y + rect.height) / texh; + let t = texh === 0 ? 0 : rect.y / texh; + data[0].u = l; + data[0].v = b; + data[1].u = r; + data[1].v = b; + data[2].u = l; + data[2].v = t; + data[3].u = r; + data[3].v = t; + } + + renderData.uvDirty = false; }, updateWorldVerts (sprite) { diff --git a/cocos2d/core/renderer/assemblers/sprite/sliced.js b/cocos2d/core/renderer/assemblers/sprite/sliced.js index cf8a4eab02..68d21b7478 100644 --- a/cocos2d/core/renderer/assemblers/sprite/sliced.js +++ b/cocos2d/core/renderer/assemblers/sprite/sliced.js @@ -43,45 +43,43 @@ module.exports = { updateUVs (sprite) { let material = sprite.getMaterial(); let renderData = sprite._renderData; - if (material && renderData) { - let texture = material.effect.getProperty('texture'); - let frame = sprite.spriteFrame; - let rect = frame._rect; - let atlasWidth = texture._width; - let atlasHeight = texture._height; - - // caculate texture coordinate - let leftWidth = frame.insetLeft; - let rightWidth = frame.insetRight; - let centerWidth = rect.width - leftWidth - rightWidth; - let topHeight = frame.insetTop; - let bottomHeight = frame.insetBottom; - let centerHeight = rect.height - topHeight - bottomHeight; - - // uv computation should take spritesheet into account. - let data = renderData._data; - if (frame._rotated) { - data[0].u = (rect.x) / atlasWidth; - data[0].v = (rect.y) / atlasHeight; - data[1].u = (bottomHeight + rect.x) / atlasWidth; - data[1].v = (leftWidth + rect.y) / atlasHeight; - data[2].u = (bottomHeight + centerHeight + rect.x) / atlasWidth; - data[2].v = (leftWidth + centerWidth + rect.y) / atlasHeight; - data[3].u = (rect.x + rect.height) / atlasWidth; - data[3].v = (rect.y + rect.width) / atlasHeight; - } - else { - data[0].u = (rect.x) / atlasWidth; - data[1].u = (leftWidth + rect.x) / atlasWidth; - data[2].u = (leftWidth + centerWidth + rect.x) / atlasWidth; - data[3].u = (rect.x + rect.width) / atlasWidth; - data[3].v = (rect.y) / atlasHeight; - data[2].v = (topHeight + rect.y) / atlasHeight; - data[1].v = (topHeight + centerHeight + rect.y) / atlasHeight; - data[0].v = (rect.y + rect.height) / atlasHeight; - } - renderData.uvDirty = false; + let texture = material.effect.getProperty('texture'); + let frame = sprite.spriteFrame; + let rect = frame._rect; + let atlasWidth = texture._width; + let atlasHeight = texture._height; + + // caculate texture coordinate + let leftWidth = frame.insetLeft; + let rightWidth = frame.insetRight; + let centerWidth = rect.width - leftWidth - rightWidth; + let topHeight = frame.insetTop; + let bottomHeight = frame.insetBottom; + let centerHeight = rect.height - topHeight - bottomHeight; + + // uv computation should take spritesheet into account. + let data = renderData._data; + if (frame._rotated) { + data[0].u = (rect.x) / atlasWidth; + data[0].v = (rect.y) / atlasHeight; + data[1].u = (bottomHeight + rect.x) / atlasWidth; + data[1].v = (leftWidth + rect.y) / atlasHeight; + data[2].u = (bottomHeight + centerHeight + rect.x) / atlasWidth; + data[2].v = (leftWidth + centerWidth + rect.y) / atlasHeight; + data[3].u = (rect.x + rect.height) / atlasWidth; + data[3].v = (rect.y + rect.width) / atlasHeight; } + else { + data[0].u = (rect.x) / atlasWidth; + data[1].u = (leftWidth + rect.x) / atlasWidth; + data[2].u = (leftWidth + centerWidth + rect.x) / atlasWidth; + data[3].u = (rect.x + rect.width) / atlasWidth; + data[3].v = (rect.y) / atlasHeight; + data[2].v = (topHeight + rect.y) / atlasHeight; + data[1].v = (topHeight + centerHeight + rect.y) / atlasHeight; + data[0].v = (rect.y + rect.height) / atlasHeight; + } + renderData.uvDirty = false; }, updateVerts (sprite) { diff --git a/cocos2d/core/renderer/assemblers/sprite/tiled.js b/cocos2d/core/renderer/assemblers/sprite/tiled.js index 1c6b52d591..a6ef006f17 100644 --- a/cocos2d/core/renderer/assemblers/sprite/tiled.js +++ b/cocos2d/core/renderer/assemblers/sprite/tiled.js @@ -23,8 +23,6 @@ THE SOFTWARE. ****************************************************************************/ -const Sprite = require('../../../components/CCSprite'); - module.exports = { createData (sprite) { return sprite.requestRenderData(); @@ -35,7 +33,6 @@ module.exports = { if (!renderData.uvDirty && !renderData.vertDirty) return; let material = sprite.getMaterial(); - if (!material || !renderData) return; let texture = material.effect.getProperty('texture'); let texw = texture._width,