From 99bedc51ae3814213835b208165d82b01dce100a Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Tue, 29 Jul 2014 14:56:53 -0400 Subject: [PATCH 01/50] Fix index page for Internet Explorer This page stinks anyway. --- index.html | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/index.html b/index.html index 569c373..2ff29a2 100644 --- a/index.html +++ b/index.html @@ -47,11 +47,11 @@ - - + + + + + + diff --git a/examples/index.html b/examples/index.html index 456bfcb..bc8dbe2 100644 --- a/examples/index.html +++ b/examples/index.html @@ -26,6 +26,7 @@
  • Channel Mapping
  • Depth Map/Displacment
  • Gradient Wipe
  • +
  • Crop
  • Linear Color Transfer
  • Multiple Canvas Targets
  • Select
  • From 71b681b6e7ee16baaa86b1a16205aec045f563cd Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Tue, 19 Aug 2014 15:27:35 -0400 Subject: [PATCH 31/50] Change enum input setup and validation - input objects are normalized when node is created - handle numerical values as keys (needed for Layers effect to work) - additional unit tests - enum output of "inputs()" is now a hash object, not an array --- seriously.js | 124 +++++++++++++++++++---------------------- test/seriously.unit.js | 27 ++++++--- 2 files changed, 75 insertions(+), 76 deletions(-) mode change 100644 => 100755 seriously.js diff --git a/seriously.js b/seriously.js old mode 100644 new mode 100755 index 9659701..95cf178 --- a/seriously.js +++ b/seriously.js @@ -434,6 +434,10 @@ return s; } + function isArrayLike(obj) { + return Array.isArray(obj) || + (obj && obj.BYTES_PER_ELEMENT && 'length' in obj); + } /* faster than setTimeout(fn, 0); @@ -464,11 +468,6 @@ window.postMessage('seriously-timeout-message', window.location); } - function isArrayLike(obj) { - return Array.isArray(obj) || - (obj && obj.BYTES_PER_ELEMENT && 'length' in obj); - } - window.addEventListener('message', function (event) { if (event.source === window && event.data === 'seriously-timeout-message') { event.stopPropagation(); @@ -605,8 +604,35 @@ function validateInputSpecs(plugin) { var input, + options, name; + function normalizeEnumOption(option, i) { + var key, + name; + + if (isArrayLike(option)) { + key = option[0]; + name = option[1] || key; + } else { + key = option; + } + + if (typeof key === 'string') { + key = key.toLowerCase(); + } else if (typeof key === 'number') { + key = String(key); + } else if (!key) { + key = ''; + } + + options[key] = name; + + if (!i && (input.defaultValue === undefined || input.defaultValue === null)) { + input.defaultValue = key; + } + } + function passThrough(value) { return value; } @@ -640,17 +666,24 @@ input.step = 0; } + if (input.type === 'enum') { + /* + Normalize options to make validation easy + - all items will have both a key and a name + - all keys will be lowercase strings + */ + if (input.options && isArrayLike(input.options) && input.options.length) { + options = {}; + input.options.forEach(normalizeEnumOption); + input.options = options; + } + } + if (input.defaultValue === undefined || input.defaultValue === null) { if (input.type === 'number') { input.defaultValue = Math.min(Math.max(0, input.min), input.max); } else if (input.type === 'color') { input.defaultValue = [0, 0, 0, 0]; - } else if (input.type === 'enum') { - if (input.options && input.options.length) { - input.defaultValue = input.options[0]; - } else { - input.defaultValue = ''; - } } else if (input.type === 'boolean') { input.defaultValue = false; } else { @@ -1799,20 +1832,9 @@ if (typeof input === 'string' && isNaN(input)) { if (effectInput.type === 'enum') { - if (effectInput.options && effectInput.options.filter) { - i = String(input).toLowerCase(); - value = effectInput.options.filter(function (e) { - return (typeof e === 'string' && e.toLowerCase() === i) || - (e.length && typeof e[0] === 'string' && e[0].toLowerCase() === i); - }); - - value = value.length; - } - - if (!value) { + if (!effectInput.options.hasOwnProperty(input)) { input = getElement(input, ['select']); } - } else if (effectInput.type === 'number' || effectInput.type === 'boolean') { input = getElement(input, ['input', 'select']); } else if (effectInput.type === 'image') { @@ -1997,7 +2019,6 @@ var result, input, inputs, - enumOption, i, key; @@ -2020,18 +2041,8 @@ result.max = input.max; result.step = input.step; } else if (input.type === 'enum') { - //make a deep copy - result.options = []; - if (options) { - for (i = 0; i < input.options.length; i++) { - enumOption = input.options[i]; - if (Array.isArray(enumOption)) { - result.options.push(enumOption.slice(0)); - } else { - result.options.push(enumOption); - } - } - } + //make a copy + result.options = extend({}, input.options); } else if (input.type === 'vector') { result.dimensions = input.dimensions; } @@ -3976,22 +3987,9 @@ //todo: there is some duplicate code with Effect here. Consolidate. if (typeof input === 'string' && isNaN(input)) { if (def.type === 'enum') { - if (def.options && def.options.filter) { - inputKey = String(input).toLowerCase(); - - //todo: possible memory leak on this function? - value = def.options.filter(function (e) { - return (typeof e === 'string' && e.toLowerCase() === inputKey) || - (e.length && typeof e[0] === 'string' && e[0].toLowerCase() === inputKey); - }); - - value = value.length; - } - - if (!value) { + if (!def.options.hasOwnProperty(input)) { input = getElement(input, ['select']); } - } else if (def.type === 'number' || def.type === 'boolean') { input = getElement(input, ['input', 'select']); } else if (def.type === 'image') { @@ -4154,7 +4152,6 @@ var result, input, inputs, - enumOption, i, key; @@ -4181,18 +4178,8 @@ result.max = input.max; result.step = input.step; } else if (input.type === 'enum') { - //make a deep copy - result.options = []; - if (options) { - for (i = 0; i < input.options.length; i++) { - enumOption = input.options[i]; - if (Array.isArray(enumOption)) { - result.options.push(enumOption.slice(0)); - } else { - result.options.push(enumOption); - } - } - } + //make a copy + result.options = extend({}, input.options); } else if (input.type === 'vector') { result.dimensions = input.dimensions; } @@ -5353,13 +5340,14 @@ if (typeof value === 'string') { value = value.toLowerCase(); + } else if (typeof value === 'number') { + value = value.toString(); + } else if (!value) { + value = ''; } - for (i = 0; i < options.length; i++) { - opt = options[i]; - if ((isArrayLike(opt) && opt.length && opt[0] === value) || opt === value) { - return value; - } + if (options.hasOwnProperty(value)) { + return value; } return defaultValue || ''; diff --git a/test/seriously.unit.js b/test/seriously.unit.js index e26e40e..8008b45 100644 --- a/test/seriously.unit.js +++ b/test/seriously.unit.js @@ -509,10 +509,10 @@ equal(inputs.vector.dimensions, 3, 'Vector dimensions reported'); equal(inputs.e.type, 'enum', 'Enum type reported'); - ok(Array.isArray(inputs.e.options), 'Enum options reported'); + ok(inputs.e.options && inputs.e.options.one === 'One', 'Enum options reported'); - inputs.e.options[1][0] = 'three'; - equal(effect.inputs('e').options[1][0], 'two', 'Enum options fully copied, cannot be tampered with'); + inputs.e.options.two = 'three'; + equal(effect.inputs('e').options.two, 'Two', 'Enum options fully copied, cannot be tampered with'); ok(seriously.isEffect(effect), 'isEffect detects effect'); ok(!seriously.isEffect(null), 'isEffect rejects null'); @@ -1233,7 +1233,7 @@ Seriously.removePlugin('testColorInput'); }); - test('Enum', 4, function() { + test('Enum', 7, function() { var s, e, val; Seriously.plugin('testEnumInput', { @@ -1244,7 +1244,9 @@ options: [ ['foo', 'Foo'], ['bar', 'Bar'], - 'baz' + 'baz', + 1, + "2" ] } } @@ -1267,6 +1269,15 @@ val = e.input; equal(val, 'foo', 'Set unknown value reverts to default'); + e.input = 1; + equal(e.input, '1', 'Numerical option'); + + e.input = 2; + equal(e.input, '2', 'Numerical option defined as string'); + + e.input = '1'; + equal(e.input, '1', 'Numerical option set as string'); + s.destroy(); Seriously.removePlugin('testEnumInput'); }); @@ -1635,10 +1646,10 @@ equal(inputs.vector.dimensions, 3, 'Vector dimensions reported'); equal(inputs.e.type, 'enum', 'Enum type reported'); - ok(Array.isArray(inputs.e.options), 'Enum options reported'); + ok(inputs.e.options && inputs.e.options.one === 'One', 'Enum options reported'); - inputs.e.options[1][0] = 'three'; - equal(transform.inputs('e').options[1][0], 'two', 'Enum options fully copied, cannot be tampered with'); + inputs.e.options.two = 'three'; + equal(transform.inputs('e').options.two, 'Two', 'Enum options fully copied, cannot be tampered with'); ok(seriously.isTransform(transform), 'isTransform detects transform'); ok(!seriously.isTransform(null), 'isTransform rejects null'); From bed62bd8f1bdd01dcdf64fea79cab806e1b8b6b1 Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Tue, 19 Aug 2014 15:30:26 -0400 Subject: [PATCH 32/50] Make sure asynchronous unit tests don't leak plugins --- test/seriously.unit.js | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/test/seriously.unit.js b/test/seriously.unit.js index 8008b45..72883f6 100644 --- a/test/seriously.unit.js +++ b/test/seriously.unit.js @@ -2301,9 +2301,9 @@ if (!effect.ready && !target.ready && !seriously.isDestroyed()) { //clean up seriously.destroy(); - Seriously.removePlugin('testReady'); - Seriously.removeSource('deferred'); - Seriously.removeSource('immediate'); + Seriously.removePlugin('ready-testReady'); + Seriously.removeSource('ready-deferred'); + Seriously.removeSource('ready-immediate'); start(); } } @@ -2317,7 +2317,7 @@ } } - Seriously.source('deferred', function (source) { + Seriously.source('ready-deferred', function (source) { var me = this; if (!proceeded) { setTimeout(function () { @@ -2334,7 +2334,7 @@ title: 'delete me' }); - Seriously.source('immediate', function () { + Seriously.source('ready-immediate', function () { return { render: function () {} }; @@ -2342,7 +2342,7 @@ title: 'delete me' }); - Seriously.plugin('testReady', { + Seriously.plugin('ready-testReady', { inputs: { source: { type: 'image' @@ -2356,10 +2356,10 @@ seriously = new Seriously(); - immediate = seriously.source('immediate'); - deferred = seriously.source('deferred', 0); + immediate = seriously.source('ready-immediate'); + deferred = seriously.source('ready-deferred', 0); - effect = seriously.effect('testReady'); + effect = seriously.effect('ready-testReady'); effect.source = immediate; effect.compare = deferred; @@ -2412,7 +2412,10 @@ function proceed() { if (deferredResized && effectResized && transformResized && targetResized) { seriously.destroy(); - Seriously.removeSource('size'); + Seriously.removeSource('resize-size'); + Seriously.removeSource('resize-immediate'); + Seriously.removeSource('resize-deferred'); + Seriously.removePlugin('resize-test'); start(); } } @@ -2421,7 +2424,7 @@ ok(false, 'Removed event listener should not run'); } - Seriously.source('immediate', function (source) { + Seriously.source('resize-immediate', function (source) { this.width = source.width; this.height = source.height; return { @@ -2431,7 +2434,7 @@ title: 'delete me' }); - Seriously.source('deferred', function (source) { + Seriously.source('resize-deferred', function (source) { var that = this; this.width = 1; this.height = 1; @@ -2448,7 +2451,7 @@ title: 'delete me' }); - Seriously.plugin('test', { + Seriously.plugin('resize-test', { title: 'Test Effect', inputs: { source: { @@ -2458,12 +2461,12 @@ }); seriously = new Seriously(); - source = seriously.source('size', { + source = seriously.source('resize-size', { width: 17, height: 19 }); - effect = seriously.effect('test'); + effect = seriously.effect('resize-test'); effect.on('resize', function () { effectResized = true; ok(true, 'Effect resize event runs when connected to a source'); @@ -2487,7 +2490,7 @@ }); target.width = 60; - deferred = seriously.source('deferred', { + deferred = seriously.source('resize-deferred', { width: 17, height: 19 }); From 716f9b125a7b04ceb4fb0c262652c63f1e04d973 Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Tue, 19 Aug 2014 15:32:53 -0400 Subject: [PATCH 33/50] Bug fix: Sizing wasn't working for Layers effect when sizeMode set to a specific layer --- effects/seriously.layers.js | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/effects/seriously.layers.js b/effects/seriously.layers.js index 3b4dff5..93e4326 100644 --- a/effects/seriously.layers.js +++ b/effects/seriously.layers.js @@ -120,13 +120,10 @@ n = Math.min(parseInt(a[0], 10), n); } - for (i = 0; i <= n; i++) { - source = this.inputs['source' + i]; - if (source) { - width = source.width; - height = source.height; - break; - } + source = this.inputs['source' + n]; + if (source) { + width = source.width; + height = source.height; } } @@ -143,10 +140,10 @@ this.emit('resize'); this.setDirty(); - } - for (i = 0; i < this.targets.length; i++) { - this.targets[i].resize(); + for (i = 0; i < this.targets.length; i++) { + this.targets[i].resize(); + } } }; From bb627076a963bcbbfdadf20fca16f04da11ebdbc Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Wed, 20 Aug 2014 09:55:50 -0400 Subject: [PATCH 34/50] Refactor Chroma Key effect to remove branching #69 --- effects/seriously.chroma.js | 62 +++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 26 deletions(-) diff --git a/effects/seriously.chroma.js b/effects/seriously.chroma.js index c44becf..3d09481 100644 --- a/effects/seriously.chroma.js +++ b/effects/seriously.chroma.js @@ -17,15 +17,13 @@ }(this, function (Seriously) { 'use strict'; - /* experimental chroma key algorithm - todo: see if we can minimize branching - todo: calculate HSL of screen color outside shader + /* + experimental chroma key algorithm todo: try allowing some color despill on opaque pixels todo: add different modes? - todo: rename parameters */ + Seriously.plugin('chroma', { - commonShader: true, shader: function (inputs, shaderSource) { shaderSource.vertex = [ 'precision mediump float;', @@ -44,8 +42,8 @@ 'varying vec3 screenPrimary;', 'void main(void) {', - ' float fmin = min(min(screen.r, screen.g), screen.b); //Min. value of RGB', - ' float fmax = max(max(screen.r, screen.g), screen.b); //Max. value of RGB', + ' float fmin = min(min(screen.r, screen.g), screen.b);', //Min. value of RGB + ' float fmax = max(max(screen.r, screen.g), screen.b);', //Max. value of RGB ' float secondaryComponents;', ' screenPrimary = step(fmax, screen.rgb);', @@ -64,6 +62,7 @@ '}' ].join('\n'); shaderSource.fragment = [ + this.inputs.mask ? '#define MASK' : '', 'precision mediump float;', 'varying vec2 vTexCoord;', @@ -79,40 +78,51 @@ 'varying float screenSat;', 'varying vec3 screenPrimary;', - 'const mat3 yuv = mat3(', - ' 54.213, 182.376, 18.411,', - ' -54.213, -182.376, 236.589,', - ' 200.787, -182.376, -18.411', - ');', - 'void main(void) {', ' float pixelSat, secondaryComponents;', - ' vec3 pixelPrimary;', - ' vec4 pixel = vec4(0.0);', ' vec4 sourcePixel = texture2D(source, vTexCoord);', - ' float fmin = min(min(sourcePixel.r, sourcePixel.g), sourcePixel.b); //Min. value of RGB', - ' float fmax = max(max(sourcePixel.r, sourcePixel.g), sourcePixel.b); //Max. value of RGB', + ' float fmin = min(min(sourcePixel.r, sourcePixel.g), sourcePixel.b);', //Min. value of RGB + ' float fmax = max(max(sourcePixel.r, sourcePixel.g), sourcePixel.b);', //Max. value of RGB // luminance = fmax - ' pixelPrimary = step(fmax, sourcePixel.rgb);', + ' vec3 pixelPrimary = step(fmax, sourcePixel.rgb);', ' secondaryComponents = dot(1.0 - pixelPrimary, sourcePixel.rgb);', ' pixelSat = fmax - mix(secondaryComponents - fmin, secondaryComponents / 2.0, balance);', // Saturation + + // solid pixel if primary color component is not the same as the screen color + ' float diffPrimary = dot(abs(pixelPrimary - screenPrimary), vec3(1.0));', + ' float solid = step(1.0, step(pixelSat, 0.1) + step(fmax, 0.1) + diffPrimary);', + + /* + Semi-transparent pixel if the primary component matches but if saturation is less + than that of screen color. Otherwise totally transparent + */ + ' float alpha = max(0.0, 1.0 - pixelSat / screenSat);', + ' alpha = smoothstep(clipBlack, clipWhite, alpha);', + ' vec4 semiTransparentPixel = vec4((sourcePixel.rgb - (1.0 - alpha) * screen.rgb * screenWeight) / alpha, alpha);', + + ' vec4 pixel = mix(semiTransparentPixel, sourcePixel, solid);', + + /* + Old branching code ' if (pixelSat < 0.1 || fmax < 0.1 || any(notEqual(pixelPrimary, screenPrimary))) {', ' pixel = sourcePixel;', ' } else if (pixelSat < screenSat) {', - ' float alpha = 1.0 - pixelSat / screenSat;', + ' float alpha = max(0.0, 1.0 - pixelSat / screenSat);', ' alpha = smoothstep(clipBlack, clipWhite, alpha);', ' pixel = vec4((sourcePixel.rgb - (1.0 - alpha) * screen.rgb * screenWeight) / alpha, alpha);', ' }', + //*/ - ' if (mask) {', - ' gl_FragColor = vec4(vec3(pixel.a), 1.0);', - ' } else {', - ' gl_FragColor = pixel;', - ' }', + + '#ifdef MASK', + ' gl_FragColor = vec4(vec3(pixel.a), 1.0);', + '#else', + ' gl_FragColor = pixel;', + '#endif', '}' ].join('\n'); return shaderSource; @@ -158,9 +168,9 @@ mask: { type: 'boolean', defaultValue: false, - uniform: 'mask' + uniform: 'mask', + shaderDirty: true } - }, title: 'Chroma Key', description: '' From c74e77eb414d4fd3c852b4feaa7e73a22e8f6f6c Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Wed, 20 Aug 2014 12:24:11 -0400 Subject: [PATCH 35/50] Default input values work for transform nodes (#59) --- seriously.js | 69 +++++++++++++++++++++++---------- test/seriously.unit.js | 88 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 135 insertions(+), 22 deletions(-) diff --git a/seriously.js b/seriously.js index 95cf178..2940656 100755 --- a/seriously.js +++ b/seriously.js @@ -628,8 +628,8 @@ options[key] = name; - if (!i && (input.defaultValue === undefined || input.defaultValue === null)) { - input.defaultValue = key; + if (!i) { + input.firstValue = key; } } @@ -679,18 +679,6 @@ } } - if (input.defaultValue === undefined || input.defaultValue === null) { - if (input.type === 'number') { - input.defaultValue = Math.min(Math.max(0, input.min), input.max); - } else if (input.type === 'color') { - input.defaultValue = [0, 0, 0, 0]; - } else if (input.type === 'boolean') { - input.defaultValue = false; - } else { - input.defaultValue = ''; - } - } - if (input.type === 'vector') { if (input.dimensions < 2) { input.dimensions = 2; @@ -2136,6 +2124,20 @@ if (this.effect.inputs.hasOwnProperty(name)) { input = this.effect.inputs[name]; + if (input.defaultValue === undefined || input.defaultValue === null) { + if (input.type === 'number') { + input.defaultValue = Math.min(Math.max(0, input.min), input.max); + } else if (input.type === 'color') { + input.defaultValue = [0, 0, 0, 0]; + } else if (input.type === 'boolean') { + input.defaultValue = false; + } else if (input.type === 'string') { + input.defaultValue = ''; + } else if (input.type === 'enum') { + input.defaultValue = input.firstValue; + } + } + defaultValue = input.validate.call(this, input.defaultValue, input); if (defaults && defaults[name] !== undefined) { defaultValue = input.validate.call(this, defaults[name], input, input.defaultValue, defaultValue); @@ -4123,7 +4125,7 @@ enumerable: true, configurable: true, get: function () { - return me.source.pub; + return me.source && me.source.pub; }, set: function (source) { me.setSource(source); @@ -4244,7 +4246,10 @@ TransformNode = function (hook, options) { var key, - input; + input, + initialValue, + defaultValue, + defaults; this.matrix = new Float32Array(16); this.cumulativeMatrix = new Float32Array(16); @@ -4283,6 +4288,7 @@ extend(this.plugin, this.transformRef.definition.call(this, options)); } + // set up inputs and methods for (key in this.plugin.inputs) { if (this.plugin.inputs.hasOwnProperty(key)) { input = this.plugin.inputs[key]; @@ -4296,6 +4302,29 @@ } validateInputSpecs(this.plugin); + // set default value for all inputs (no defaults for methods) + defaults = defaultInputs[hook]; + for (key in this.plugin.inputs) { + if (this.plugin.inputs.hasOwnProperty(key)) { + input = this.plugin.inputs[key]; + + if (typeof input.set === 'function' && typeof input.get === 'function' && + typeof input.method !== 'function') { + + initialValue = input.get.call(this); + defaultValue = input.defaultValue === undefined ? initialValue : input.defaultValue; + defaultValue = input.validate.call(this, defaultValue, input, initialValue); + if (defaults && defaults[key] !== undefined) { + defaultValue = input.validate.call(this, defaults[key], input, input.defaultValue, defaultValue); + defaults[key] = defaultValue; + } + if (defaultValue !== initialValue) { + input.set.call(this, defaultValue); + } + } + } + } + nodes.push(this); nodesById[this.id] = this; @@ -4402,17 +4431,17 @@ if (this.plugin.inputs.hasOwnProperty(name)) { input = this.plugin.inputs[name]; - /* if (defaultInputs[this.hook] && defaultInputs[this.hook][name] !== undefined) { defaultValue = defaultInputs[this.hook][name]; } else { defaultValue = input.defaultValue; } - defaultValue = input.defaultValue; - */ previous = input.get.call(this); - value = input.validate.call(this, value, input, previous, previous); + if (defaultValue === undefined) { + defaultValue = previous; + } + value = input.validate.call(this, value, input, defaultValue, previous); if (input.set.call(this, value)) { this.setTransformDirty(); diff --git a/test/seriously.unit.js b/test/seriously.unit.js index 72883f6..f3c3181 100644 --- a/test/seriously.unit.js +++ b/test/seriously.unit.js @@ -454,7 +454,7 @@ Seriously.removePlugin('removeme'); }); - test('Effect Info', 23, function () { + test('Effect Info', 24, function () { var inputs, seriously, effect; @@ -510,6 +510,7 @@ equal(inputs.e.type, 'enum', 'Enum type reported'); ok(inputs.e.options && inputs.e.options.one === 'One', 'Enum options reported'); + ok(inputs.e.options && inputs.e.defaultValue === 'one', 'Enum default reported'); inputs.e.options.two = 'three'; equal(effect.inputs('e').options.two, 'Two', 'Enum options fully copied, cannot be tampered with'); @@ -1341,7 +1342,7 @@ Seriously.removePlugin('testVectorInput'); }); - test('Defaults', 8, function (argument) { + test('Effect Defaults', 8, function (argument) { var seriously, effect, source; @@ -1810,6 +1811,89 @@ seriously.destroy(); }); + test('Transform Defaults', 7, function (argument) { + var seriously, + transform, + source; + + Seriously.transform('testDefaults', function (){ + var number = 0, + badNumber = 0; + return { + inputs: { + number: { + get: function () { + return number; + }, + set: function (num) { + number = num; + }, + type: 'number', + defaultValue: 42 + }, + badNumber: { + get: function () { + return badNumber; + }, + set: function (num) { + badNumber = num; + }, + type: 'number', + defaultValue: 9 + } + } + }; + }); + + // Passed as an option to the Seriously constructor + seriously = new Seriously({ + defaults: { + testDefaults: { + number: 1337, + badNumber: 'not a number' + } + } + }); + + transform = seriously.transform('testDefaults'); + equal(transform.number, 1337, 'Default set when passed as an option to the Seriously constructor'); + equal(transform.badNumber, 9, 'Invalid default value ignored'); + transform.destroy(); + + // reset all defaults + seriously.defaults(null); + transform = seriously.transform('testDefaults'); + equal(transform.number, 42, 'All defaults reset successfully'); + seriously.destroy(); + + // defaults method on the Seriously instance + seriously = new Seriously(); + seriously.defaults({ + testDefaults: { + number: 43 + } + }); + + transform = seriously.transform('testDefaults'); + equal(transform.number, 43, 'Default set with defaults method'); + transform.number = 7; + transform.number = 'not a number'; + equal(transform.number, 43, 'New default used when trying to set an invalid value'); + transform.destroy(); + + seriously.defaults('testDefaults', {}); + transform = seriously.transform('testDefaults'); + equal(transform.number, 42, 'Default value reset by setting to a different hash'); + transform.destroy(); + + seriously.defaults('testDefaults', null); + transform = seriously.transform('testDefaults'); + equal(transform.number, 42, 'Defaults reset for single transform'); + + seriously.destroy(); + Seriously.removeTransform('testDefaults'); + }); + module('Target'); test('Canvas Target', 7, function () { var seriously, From 80470ed392cdd91abf4cbeaf40ea8597ce69d860 Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Wed, 20 Aug 2014 14:41:05 -0400 Subject: [PATCH 36/50] Don't use magic number for WebGL error code (#68) --- seriously.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seriously.js b/seriously.js index 39baa31..094449f 100644 --- a/seriously.js +++ b/seriously.js @@ -3343,7 +3343,7 @@ //workaround for lack of video texture support in IE if (noVideoTextureSupport === undefined) { error = gl.getError(); - if (error === 1281) { + if (error === gl.INVALID_VALUE) { noVideoTextureSupport = true; this.renderVideo(); return; From 0578a57d263e7e9c365b6f60b257fc455f840abb Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Thu, 21 Aug 2014 11:36:21 -0400 Subject: [PATCH 37/50] Remove unnecessary variable initialization --- seriously.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seriously.js b/seriously.js index 094449f..e3e1aaa 100644 --- a/seriously.js +++ b/seriously.js @@ -47,7 +47,7 @@ identity, maxSeriouslyId = 0, nop = function () {}, - noVideoTextureSupport = undefined, + noVideoTextureSupport, /* Global reference variables From d9a5c39092a17935eec76434593a020e008721b1 Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Thu, 21 Aug 2014 12:04:29 -0400 Subject: [PATCH 38/50] Log a warning when creating a target node with a target that's already in use --- seriously.js | 35 ++++++++++++++++++++++++++++++--- test/seriously.unit.js | 44 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 3 deletions(-) diff --git a/seriously.js b/seriously.js index 2940656..2b73c7b 100755 --- a/seriously.js +++ b/seriously.js @@ -27,7 +27,7 @@ console = window.console, /* - Global environment variables + Global-ish look-up variables */ testContext, @@ -44,6 +44,7 @@ image: [], video: [] }, + allTargets = window.WeakMap && new WeakMap(), identity, maxSeriouslyId = 0, nop = function () {}, @@ -2252,7 +2253,7 @@ if (this.ready !== ready) { this.ready = ready; this.emit(ready ? 'ready' : 'unready'); - method = ready ? 'setReady' : 'setUnready' + method = ready ? 'setReady' : 'setUnready'; if (this.targets) { for (i = 0; i < this.targets.length; i++) { @@ -3647,6 +3648,7 @@ i, element, elements, context, debugContext = opts.debugContext, frameBuffer, + targetList, triedWebGl = false; Node.call(this, opts); @@ -3758,6 +3760,23 @@ throw new Error('Unknown target type'); } + if (allTargets) { + targetList = allTargets.get(target); + if (targetList) { + Seriously.logger.warn( + 'Target already in use by another instance', + target, + Object.keys(targetList).map(function (key) { + return targetList[key]; + }) + ); + } else { + targetList = {}; + allTargets.set(target, targetList); + } + targetList[seriously.id] = seriously; + } + this.target = target; this.transform = null; this.transformDirty = true; @@ -3947,12 +3966,22 @@ }; TargetNode.prototype.destroy = function () { - var i; + var i, + targetList; //source if (this.source && this.source.removeTarget) { this.source.removeTarget(this); } + + if (allTargets) { + targetList = allTargets.get(this.target); + delete targetList[seriously.id]; + if (!Object.keys(targetList).length) { + allTargets.delete(this.target); + } + } + delete this.source; delete this.target; delete this.pub; diff --git a/test/seriously.unit.js b/test/seriously.unit.js index f3c3181..b0bfb9a 100644 --- a/test/seriously.unit.js +++ b/test/seriously.unit.js @@ -2187,6 +2187,50 @@ Seriously.removePlugin('removeme'); }); + test('Shared target warning', function () { + var seriously1, + seriously2, + target1, + target2, + canvas; + + function firstTarget(message) { + ok(false, 'First target should not fire a warning: ' + message); + } + + function secondTarget(message, target, instances) { + equal(message, 'Target already in use by another instance', 'Warning fired when using a shared target canvas'); + equal(target, canvas, 'Warning passes shared canvas'); + equal(instances[0], seriously1, 'Warning passes Seriously instances using shared canvas'); + } + + function thirdTarget(message) { + ok(false, 'Reused target after other target nodes destroyed should not fire a warning: ' + message); + } + + expect(window.WeakMap ? 3 : 0); + + Seriously.logger.warn = firstTarget; + + canvas = document.createElement('canvas'); + seriously1 = new Seriously(); + seriously2 = new Seriously(); + + target1 = seriously1.target(canvas); + + Seriously.logger.warn = secondTarget; + target2 = seriously2.target(canvas); + + Seriously.logger.warn = thirdTarget; + target1.destroy(); + target2.destroy(); + target1 = seriously1.target(canvas); + + seriously1.destroy(); + seriously2.destroy(); + Seriously.logger.warn = nop; + }); + module('Alias'); test('Effect alias', 2, function () { var seriously, From 85ec91212fd6aad963ed6259a5d2aa85107b09b1 Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Thu, 21 Aug 2014 12:06:43 -0400 Subject: [PATCH 39/50] Don't make functions in a loop --- test/seriously.unit.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/seriously.unit.js b/test/seriously.unit.js index b0bfb9a..26e3cb1 100644 --- a/test/seriously.unit.js +++ b/test/seriously.unit.js @@ -1139,6 +1139,10 @@ yellowgreen: [154 / 255, 205 / 255, 50 / 255, 1] }; + function normalizeChannel(val) { + return val * 255; + } + Seriously.plugin('testColorInput', { inputs: { color: { @@ -1196,7 +1200,7 @@ val = e.color; ok(compare(val, colorNames[name]), 'Set color by name (' + name + ')'); if (!compare(val, colorNames[name])) { - console.log(name + ': ' + JSON.stringify(colorNames[name].map(function (val) { return val * 255; })) + ','); + console.log(name + ': ' + JSON.stringify(colorNames[name].map(normalizeChannel)) + ','); } } } From 21315dcc6306c1e6c7228cbc39487e264e4258d3 Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Fri, 22 Aug 2014 13:28:26 -0400 Subject: [PATCH 40/50] Bug fix: OpenGL blendFuncSeparate didn't support ZERO --- seriously.js | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/seriously.js b/seriously.js index 2b73c7b..5840d8e 100755 --- a/seriously.js +++ b/seriously.js @@ -1399,7 +1399,9 @@ var numTextures = 0, name, value, shaderUniform, width, height, - nodeGl = (node && node.gl) || gl; + nodeGl = (node && node.gl) || gl, + srcRGB, srcAlpha, + dstRGB, dstAlpha; if (!nodeGl) { return; @@ -1440,23 +1442,24 @@ gl.disable(gl.DEPTH_TEST); } - //default for blend is enable - if (!options || options.blend === undefined || options.blend) { + //default for blend is enabled + if (!options) { gl.enable(gl.BLEND); - /* gl.blendFunc( - options && options.srcRGB || gl.ONE, - options && options.dstRGB || gl.ONE_MINUS_SRC_ALPHA + gl.ONE, + gl.ZERO ); - */ + gl.blendEquation(gl.FUNC_ADD); + } else if (options.blend === undefined || options.blend) { + gl.enable(gl.BLEND); - gl.blendFuncSeparate( - options && options.srcRGB || gl.ONE, - options && options.dstRGB || gl.ZERO, - options && (options.srcAlpha || options.srcRGB) || gl.ONE, - options && (options.dstAlpha || options.dstRGB) || gl.ZERO - ); - gl.blendEquation(options && options.blendEquation || gl.FUNC_ADD); + srcRGB = options.srcRGB === undefined ? gl.ONE : options.srcRGB; + dstRGB = options.dstRGB || gl.ZERO; + srcAlpha = options.srcAlpha === undefined ? srcRGB : options.srcAlpha; + dstAlpha = options.dstAlpha === undefined ? dstRGB : options.dstAlpha; + + gl.blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); + gl.blendEquation(options.blendEquation || gl.FUNC_ADD); } else { gl.disable(gl.BLEND); } From 932b61b4d0f4b83b603b6b9f9ab056cda86ce3be Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Tue, 26 Aug 2014 12:44:53 -0400 Subject: [PATCH 41/50] Added Pixelate effect --- README.md | 1 + effects/seriously.pixelate.js | 56 +++++++++++++++++++++++++++++++++++ index.html | 3 +- 3 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 effects/seriously.pixelate.js diff --git a/README.md b/README.md index 1daac58..e26a04f 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ Full documentation is in progress at the [wiki](https://github.com/brianchirls/S - Mirror - Night Vision - Panorama +- Pixelate - Polar Coordinates - Ripple - Scanlines diff --git a/effects/seriously.pixelate.js b/effects/seriously.pixelate.js new file mode 100644 index 0000000..3db971c --- /dev/null +++ b/effects/seriously.pixelate.js @@ -0,0 +1,56 @@ +/* global define, require */ +(function (root, factory) { + 'use strict'; + + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['seriously'], factory); + } else if (typeof exports === 'object') { + // Node/CommonJS + factory(require('seriously')); + } else { + if (!root.Seriously) { + root.Seriously = { plugin: function (name, opt) { this[name] = opt; } }; + } + factory(root.Seriously); + } +}(this, function (Seriously) { + 'use strict'; + + Seriously.plugin('pixelate', { + commonShader: true, + shader: function (inputs, shaderSource) { + shaderSource.fragment = [ + 'precision mediump float;', + + 'varying vec2 vTexCoord;', + + 'uniform sampler2D source;', + 'uniform vec2 resolution;', + 'uniform vec2 pixelSize;', + + 'void main(void) {', + ' vec2 delta = pixelSize / resolution;', + ' gl_FragColor = texture2D(source, delta * floor(vTexCoord / delta));', + '}' + ].join('\n'); + return shaderSource; + }, + inPlace: true, + inputs: { + source: { + type: 'image', + uniform: 'source', + shaderDirty: false + }, + pixelSize: { + type: 'vector', + dimensions: 2, + defaultValue: [8, 8], + min: 0, + uniform: 'pixelSize' + } + }, + title: 'Pixelate' + }); +})); diff --git a/index.html b/index.html index a959681..37e5b3f 100644 --- a/index.html +++ b/index.html @@ -1,4 +1,4 @@ - + @@ -35,6 +35,7 @@ + From a933d756fc09e2d502e41eb206725ee7d5e7cca8 Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Tue, 9 Sep 2014 18:20:20 -0400 Subject: [PATCH 42/50] Added unit tests for video source Known to fail in Safari 7, which reports canplaythrough before video data is actually ready --- seriously.js | 2 + test/media/tiny.mp4 | Bin 0 -> 1867 bytes test/media/tiny.webm | Bin 0 -> 548 bytes test/seriously.unit.js | 112 ++++++++++++++++++++++++++++++++++++++++- 4 files changed, 112 insertions(+), 2 deletions(-) create mode 100644 test/media/tiny.mp4 create mode 100644 test/media/tiny.webm diff --git a/seriously.js b/seriously.js index e3e1aaa..2f2d376 100644 --- a/seriously.js +++ b/seriously.js @@ -3488,6 +3488,7 @@ if (!isNaN(value) && value >0 && me.width !== value) { me.width = me.desiredWidth = value; me.target.width = value; + me.uniforms.resolution[0] = value; me.setTransformDirty(); me.emit('resize'); @@ -3514,6 +3515,7 @@ if (!isNaN(value) && value >0 && me.height !== value) { me.height = me.desiredHeight = value; me.target.height = value; + me.uniforms.resolution[1] = value; me.setTransformDirty(); me.emit('resize'); diff --git a/test/media/tiny.mp4 b/test/media/tiny.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..82479590f14e9597e7a61017267e0452336816a9 GIT binary patch literal 1867 zcmbVNUx*t;7@u4;t+gPPf>$_Us%KwplHE-%<_;Ee9@P^Reb5S}kWO}IZ8F76`5|EY@>OkyK4W$Wc#nPDuVc;W7;|oxFhAG8U`}sV3Euhhd;>i`M&f*U`{|(-APcoVl0dh})KV)-EFpYf# zk>)aF5CryC*p+P1bYhXPv?JIeEm;r&1q4clF`i_CD?r;k*z$D(sLco9wyl*JY>FTP zl`4lv-05n&YG5VFa91Q(J|sz}nRRT}P`4fFQPF~}!OlRj&3eh89qh+8N)XdYkT_jg z->$8KL1~`YRT?C)&v2%23{Z=8;0Wa~cpRzSpPj%!fH$sW@b-cA;nZ4K-zAk>Mw-7%Gt|h?r3?)-G|JFkhVISK4#^PB zP$NT^GBnK4C_{VYX)inXW@wkZh_*ZzaomGGL(%hHSmz}F0Q?U~j^OV={-uEVklr|m zd=y%MFU7}jTiW2fsM~4H{9NFa4Qn5gLviFdFT5yujsp>Oc6}@-I-xr&*OJ!lSOXGF(!8duCWK;WKX1|^KCD? z6W@{x?+PY^p#OMRhIE2+Qt4I*_`1?+b|4t@5q^4MMVaTESQ_xyn*ed3{5N7^KbRNC zV^9oW-N?PXcWiv0JhKJs{wGg-eFF9g8S=z>>gh9Qa-`t@aP{bq6yg_^PPY|#u*NC; za{xIB-QsqmpdH5&*c>!~%xn;!;y(B;r=H1#JhuQIn;TC8o*(nR|BIndC!Ul{`@mPU z)pa$4^@8B(itf|%M-JCSvLwM%$)p%e?$rxl=okr~g+DlTyAeIeo667VQ zdtJ4zZ*1mwa`0{F^+_yCGd0ySHr6vVFbH=<m z%eSGCX;&jt2#^W^((=yRN@4DM-pH`{KqCV~!v!XWxr|y&3``6R?i{VH9jz@LOiWCr ztC)E9tYrK9hT-4;e|!H5bpJV18D!Jt+OzimJ>&oHz-S@^D4L)K3hwUT+{m!K3z!f- LHZj(JXk-Qe=kJ0I literal 0 HcmV?d00001 diff --git a/test/seriously.unit.js b/test/seriously.unit.js index 2fd91eb..d4a6428 100644 --- a/test/seriously.unit.js +++ b/test/seriously.unit.js @@ -3,15 +3,17 @@ (function () { 'use strict'; - function compare(a, b) { + function compare(a, b, epsilon) { var i; if (a.length !== b.length) { return false; } + epsilon = epsilon || 0; + for (i = 0; i < a.length; i++) { - if (a[i] !== b[i]) { + if (Math.abs(a[i] - b[i]) > epsilon) { return false; } } @@ -855,6 +857,112 @@ } }); + asyncTest('Video Source', 5, function () { + var seriously, + source, + dupSource, + target, + reformat, + video, + + //for iOS + div, + + // 2 x 2 pixels + data = [ + 127, 0, 40, 255, + 34, 1, 39, 255, + 126, 1, 123, 255, + 34, 1, 121, 255 + ]; + + function finish() { + if (div && div.parentNode) { + div.parentNode.removeChild(div); + } + seriously.destroy(); + start(); + } + + seriously = new Seriously(); + target = seriously.target(document.createElement('canvas')); + target.width = 2; + target.height = 2; + video = document.createElement('video'); + video.setAttribute('preload', 'auto'); + + video.addEventListener('canplaythrough', function () { + var pixels; + if (!video.videoWidth) { + console.log('Browser failed to properly report video dimensions'); + } + ok(source.width === video.videoWidth && source.height === video.videoHeight, + 'Source node correctly calculates size from video'); + + try { + pixels = target.readPixels(0, 0, 2, 2); + + /* + Allow for slight variations in how different codecs interpret video pixel colors. + */ + ok(compare(pixels, data, 8), 'Video source rendered.'); + } catch (e) { + ok(seriously.incompatible(), 'Cannot read pixels without WebGL support'); + } + finish(); + }); + + if (video.canPlayType('video/mp4')) { + video.src = 'media/tiny.mp4'; + } else { + video.src = 'media/tiny.webm'; + } + video.loop = true; + video.load(); + + /* + iOS will not load any part of a video until there is a touch or click event, + So we give a chance to touch to proceed. If no touch after 10 seconds, just skip the test and move on. + */ + setTimeout(function () { + if (!video.readyState) { + div = document.createElement('div'); + div.innerHTML = 'Touch here to enable video test'; + div.setAttribute('style', 'position: fixed; top: 0; right: 0; padding: 20px;' + + 'color: darkred; background-color: lightgray; font-size: 20px; cursor: pointer;'); + document.body.appendChild(div); + div.onclick = function () { + if (video && !video.readyState) { + video.load(); + } + }; + + setTimeout(function () { + if (!video.readyState) { + console.log('Skipped video source render test'); + expect(3); + finish(); + } + }, 10000); + } + }, 100); + + source = seriously.source(video); + equal(source.original, video, 'Video source created by passing video element'); + source.destroy(); + + source = seriously.source('video', video); + equal(source.original, video, 'Video source created with explicit source plugin hook'); + + dupSource = seriously.source(video); + equal(dupSource, source, 'Trying to create a second source with the same video returns the original'); + + reformat = seriously.transform('reformat'); + reformat.width = reformat.height = target.height; + reformat.source = source; + target.source = reformat; + }); + module('Inputs'); /* * all different types From 3bc49f907c1284a3c7ac87e2b94f4c696fa2bcd0 Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Thu, 11 Sep 2014 09:34:14 -0400 Subject: [PATCH 43/50] Refactor video rendering - slightly simpler and less kludgey - remove timing hack in favor of "seeked" event - added more flexible "checkDirty" method to source plugins --- seriously.js | 182 +++++++++++++++++++----------------- sources/seriously.camera.js | 23 ++++- 2 files changed, 117 insertions(+), 88 deletions(-) diff --git a/seriously.js b/seriously.js index a01f368..63076cf 100755 --- a/seriously.js +++ b/seriously.js @@ -1367,9 +1367,8 @@ node = sources[i]; media = node.source; - if (node.lastRenderTime === undefined || - node.dirty || - media.currentTime !== undefined && node.lastRenderTime !== media.currentTime) { + if (node.dirty || + node.checkDirty && node.checkDirty()) { node.dirty = false; node.setDirty(); } @@ -3134,6 +3133,7 @@ deferTexture = plugin.deferTexture; this.plugin = plugin; this.compare = plugin.compare; + this.checkDirty = plugin.checkDirty; if (plugin.source) { source = plugin.source; } @@ -3220,6 +3220,7 @@ deferTexture = plugin.deferTexture; this.plugin = plugin; this.compare = plugin.compare; + this.checkDirty = plugin.checkDirty; if (plugin.source) { source = plugin.source; } @@ -3366,6 +3367,7 @@ } if (this.plugin && this.plugin.render && + (this.dirty || this.checkDirty && this.checkDirty()) && this.plugin.render.call(this, gl, draw, rectangleModel, baseShader)) { this.dirty = false; @@ -3373,74 +3375,6 @@ } }; - SourceNode.prototype.renderVideo = function () { - var video = this.source, - source, - canvas, - error; - - if (!gl || !video || !video.videoHeight || !video.videoWidth || video.readyState < 2 || !this.ready) { - return; - } - - if (!this.initialized) { - this.initialize(); - } - - if (!this.allowRefresh) { - return; - } - - if (this.dirty || - this.lastRenderFrame !== video.mozPresentedFrames || - this.lastRenderTime !== video.currentTime) { - - if (noVideoTextureSupport) { - if (!this.ctx2d) { - this.ctx2d = document.createElement('canvas').getContext('2d'); - } - source = this.ctx2d.canvas; - source.width = this.width; - source.height = this.height; - this.ctx2d.drawImage(video, 0, 0, this.width, this.height); - } else { - source = video; - } - - gl.bindTexture(gl.TEXTURE_2D, this.texture); - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, this.flip); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - try { - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source); - - //workaround for lack of video texture support in IE - if (noVideoTextureSupport === undefined) { - error = gl.getError(); - if (error === gl.INVALID_VALUE) { - noVideoTextureSupport = true; - this.renderVideo(); - return; - } - noVideoTextureSupport = false; - } - } catch (securityError) { - if (securityError.code === window.DOMException.SECURITY_ERR) { - this.allowRefresh = false; - Seriously.logger.error('Unable to access cross-domain image'); - } - } - - // Render a few extra times because the canvas takes a while to catch up - if (Date.now() - 100 > this.lastRenderTimeStamp) { - this.lastRenderTime = video.currentTime; - } - this.lastRenderFrame = video.mozPresentedFrames; - this.lastRenderTimeStamp = Date.now(); - this.dirty = false; - this.emit('render'); - } - }; - SourceNode.prototype.renderImageCanvas = function () { var media = this.source; @@ -3462,6 +3396,10 @@ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); try { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, media); + + this.dirty = false; + this.emit('render'); + return true; } catch (securityError) { if (securityError.code === window.DOMException.SECURITY_ERR) { this.allowRefresh = false; @@ -3469,9 +3407,7 @@ } } - this.lastRenderTime = Date.now() / 1000; - this.dirty = false; - this.emit('render'); + return false; } }; @@ -5579,7 +5515,6 @@ error: consoleMethod('error') }; - //expose Seriously to the global object Seriously.util = { mat4: mat4, checkSource: checkSource, @@ -5605,23 +5540,32 @@ } }; - Seriously.source('video', function (source, options, force) { + Seriously.source('video', function (video, options, force) { var me = this, video, key, opts, + + canvas, + ctx2d, + destroyed = false, - deferTexture = false; + deferTexture = false, + + isSeeking = false, + lastRenderTime = 0; function initializeVideo() { + video.removeEventListener('loadedmetadata', initializeVideo, true); + if (destroyed) { return; } - if (source.videoWidth) { - if (me.width !== source.videoWidth || me.height !== source.videoHeight) { - me.width = source.videoWidth; - me.height = source.videoHeight; + if (video.videoWidth) { + if (me.width !== video.videoWidth || me.height !== video.videoHeight) { + me.width = video.videoWidth; + me.height = video.videoHeight; me.resize(); } @@ -5635,23 +5579,90 @@ } } - if (source instanceof window.HTMLVideoElement) { - if (source.readyState) { + function seeking() { + // IE doesn't report .seeking properly so make our own + isSeeking = true; + } + + function seeked() { + isSeeking = false; + me.setDirty(); + } + + if (video instanceof window.HTMLVideoElement) { + if (video.readyState) { initializeVideo(); } else { deferTexture = true; - source.addEventListener('loadedmetadata', initializeVideo, true); + video.addEventListener('loadedmetadata', initializeVideo, true); } + video.addEventListener('seeking', seeking, false); + video.addEventListener('seeked', seeked, false); + return { deferTexture: deferTexture, source: video, - render: Object.getPrototypeOf(this).renderVideo, + render: function renderVideo(gl) { + var source, + error; + + lastRenderTime = video.currentTime; + + if (!video.videoHeight || !video.videoWidth) { + return false; + } + + if (noVideoTextureSupport) { + if (!ctx2d) { + ctx2d = document.createElement('canvas').getContext('2d'); + canvas = ctx2d.canvas; + canvas.width = me.width; + canvas.height = me.height; + } + source = canvas; + ctx2d.drawImage(video, 0, 0, me.width, me.height); + } else { + source = video; + } + + gl.bindTexture(gl.TEXTURE_2D, me.texture); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, me.flip); + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); + try { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source); + + //workaround for lack of video texture support in IE + if (noVideoTextureSupport === undefined) { + error = gl.getError(); + if (error === gl.INVALID_VALUE) { + noVideoTextureSupport = true; + return renderVideo(gl); + } + noVideoTextureSupport = false; + } + return true; + } catch (securityError) { + if (securityError.code === window.DOMException.SECURITY_ERR) { + me.allowRefresh = false; + Seriously.logger.error('Unable to access cross-domain image'); + } else { + Seriously.logger.error('Error rendering video source', securityError); + } + } + return false; + }, + checkDirty: function () { + return !isSeeking && video.currentTime !== lastRenderTime; + }, compare: function (source) { return me.source === source; }, destroy: function () { destroyed = true; + video.removeEventListener('seeking', seeking, false); + video.removeEventListener('seeked', seeked, false); + video.removeEventListener('loadedmetadata', initializeVideo, true); } }; } @@ -6543,5 +6554,4 @@ '#endif\n'; return Seriously; - })); diff --git a/sources/seriously.camera.js b/sources/seriously.camera.js index b2ee991..f4ba12a 100644 --- a/sources/seriously.camera.js +++ b/sources/seriously.camera.js @@ -31,7 +31,9 @@ key, opts, destroyed = false, - stream; + stream, + + lastRenderTime = 0; function cleanUp() { if (video) { @@ -113,7 +115,24 @@ return { deferTexture: true, source: video, - render: Object.getPrototypeOf(this).renderVideo, + render: function (gl) { + lastRenderTime = video.currentTime; + + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, this.flip); + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); + try { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, video); + return true; + } catch (error) { + Seriously.logger.error('Error rendering camera video source', error); + } + + return false; + }, + checkDirty: function () { + return video.currentTime !== lastRenderTime; + }, destroy: function () { destroyed = true; cleanUp(); From f0a98920791013dbed9c3a77e3887179961a1c34 Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Wed, 8 Oct 2014 09:07:27 -0400 Subject: [PATCH 44/50] Updated three.js to v68 --- lib/three.js | 26629 ++++++++++++++++++++++--------------------------- 1 file changed, 11990 insertions(+), 14639 deletions(-) diff --git a/lib/three.js b/lib/three.js index 37bf01f..d98a124 100644 --- a/lib/three.js +++ b/lib/three.js @@ -1,59 +1,17 @@ +// File:src/Three.js + /** * @author mrdoob / http://mrdoob.com/ - * @author Larry Battle / http://bateru.com/news - * @author bhouston / http://exocortex.com */ -var THREE = { REVISION: '67' }; - -self.console = self.console || { - - info: function () {}, - log: function () {}, - debug: function () {}, - warn: function () {}, - error: function () {} - -}; - -// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ -// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating - -// requestAnimationFrame polyfill by Erik Möller -// fixes from Paul Irish and Tino Zijdel -// using 'self' instead of 'window' for compatibility with both NodeJS and IE10. -( function () { - - var lastTime = 0; - var vendors = [ 'ms', 'moz', 'webkit', 'o' ]; - - for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) { - - self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ]; - self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ]; - - } - - if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) { - - self.requestAnimationFrame = function ( callback ) { - - var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) ); - var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall ); - lastTime = currTime + timeToCall; - return id; +var THREE = { REVISION: '68' }; - }; - - } - - if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) { +// browserify support +if ( typeof module === 'object' ) { - self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) }; + module.exports = THREE; - } - -}() ); +} // GL STATE CONSTANTS @@ -203,6 +161,8 @@ THREE.RGBA_PVRTC_4BPPV1_Format = 2102; THREE.RGBA_PVRTC_2BPPV1_Format = 2103; */ +// File:src/math/Color.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -585,30 +545,32 @@ THREE.Color.prototype = { }; -THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF, -"beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2, -"brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50, -"cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B, -"darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B, -"darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F, -"darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3, -"deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222, -"floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700, -"goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4, -"indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00, -"lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3, -"lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA, -"lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32, -"linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3, -"mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC, -"mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD, -"navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6, -"palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9, -"peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F, -"royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE, -"sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA, -"springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0, -"violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 }; +THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, +'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, +'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, +'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, +'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, +'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, +'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, +'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, +'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, +'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, +'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, +'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, +'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, +'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, +'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, +'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, +'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, +'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, +'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, +'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, +'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, +'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, +'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, +'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; + +// File:src/math/Quaternion.js /** * @author mikael emtinger / http://gomo.se/ @@ -699,10 +661,10 @@ THREE.Quaternion.prototype = { copy: function ( quaternion ) { - this._x = quaternion._x; - this._y = quaternion._y; - this._z = quaternion._z; - this._w = quaternion._w; + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; this.onChangeCallback(); @@ -714,7 +676,7 @@ THREE.Quaternion.prototype = { if ( euler instanceof THREE.Euler === false ) { - throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' ); + throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); } // http://www.mathworks.com/matlabcentral/fileexchange/ @@ -805,9 +767,9 @@ THREE.Quaternion.prototype = { var te = m.elements, - m11 = te[0], m12 = te[4], m13 = te[8], - m21 = te[1], m22 = te[5], m23 = te[9], - m31 = te[2], m32 = te[6], m33 = te[10], + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], trace = m11 + m22 + m33, s; @@ -825,19 +787,19 @@ THREE.Quaternion.prototype = { s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - this._w = (m32 - m23 ) / s; + this._w = ( m32 - m23 ) / s; this._x = 0.25 * s; - this._y = (m12 + m21 ) / s; - this._z = (m13 + m31 ) / s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; } else if ( m22 > m33 ) { s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - this._w = (m13 - m31 ) / s; - this._x = (m12 + m21 ) / s; + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; this._y = 0.25 * s; - this._z = (m23 + m32 ) / s; + this._z = ( m23 + m32 ) / s; } else { @@ -866,7 +828,7 @@ THREE.Quaternion.prototype = { var EPS = 0.000001; - return function( vFrom, vTo ) { + return function ( vFrom, vTo ) { if ( v1 === undefined ) v1 = new THREE.Vector3(); @@ -915,9 +877,9 @@ THREE.Quaternion.prototype = { conjugate: function () { - this._x *= -1; - this._y *= -1; - this._z *= -1; + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; this.onChangeCallback(); @@ -925,6 +887,12 @@ THREE.Quaternion.prototype = { }, + dot: function ( v ) { + + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + + }, + lengthSq: function () { return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; @@ -969,7 +937,7 @@ THREE.Quaternion.prototype = { if ( p !== undefined ) { - console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); + console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); return this.multiplyQuaternions( q, p ); } @@ -998,7 +966,7 @@ THREE.Quaternion.prototype = { multiplyVector3: function ( vector ) { - console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); + console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); return vector.applyQuaternion( this ); }, @@ -1013,12 +981,12 @@ THREE.Quaternion.prototype = { if ( cosHalfTheta < 0 ) { - this._w = -qb._w; - this._x = -qb._x; - this._y = -qb._y; - this._z = -qb._z; + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; - cosHalfTheta = -cosHalfTheta; + cosHalfTheta = - cosHalfTheta; } else { @@ -1114,6 +1082,8 @@ THREE.Quaternion.slerp = function ( qa, qb, qm, t ) { } +// File:src/math/Vector2.js + /** * @author mrdoob / http://mrdoob.com/ * @author philogb / http://blog.thejit.org/ @@ -1163,7 +1133,7 @@ THREE.Vector2.prototype = { case 0: this.x = value; break; case 1: this.y = value; break; - default: throw new Error( "index is out of range: " + index ); + default: throw new Error( 'index is out of range: ' + index ); } @@ -1175,7 +1145,7 @@ THREE.Vector2.prototype = { case 0: return this.x; case 1: return this.y; - default: throw new Error( "index is out of range: " + index ); + default: throw new Error( 'index is out of range: ' + index ); } @@ -1194,7 +1164,7 @@ THREE.Vector2.prototype = { if ( w !== undefined ) { - console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); return this.addVectors( v, w ); } @@ -1228,7 +1198,7 @@ THREE.Vector2.prototype = { if ( w !== undefined ) { - console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); return this.subVectors( v, w ); } @@ -1248,7 +1218,7 @@ THREE.Vector2.prototype = { return this; }, - + multiply: function ( v ) { this.x *= v.x; @@ -1378,7 +1348,7 @@ THREE.Vector2.prototype = { return this.clamp( min, max ); }; - + } )(), floor: function () { @@ -1419,7 +1389,10 @@ THREE.Vector2.prototype = { negate: function () { - return this.multiplyScalar( - 1 ); + this.x = - this.x; + this.y = - this.y; + + return this; }, @@ -1482,7 +1455,7 @@ THREE.Vector2.prototype = { }, - equals: function( v ) { + equals: function ( v ) { return ( ( v.x === this.x ) && ( v.y === this.y ) ); @@ -1511,6 +1484,8 @@ THREE.Vector2.prototype = { }; +// File:src/math/Vector3.js + /** * @author mrdoob / http://mrdoob.com/ * @author *kile / http://kile.stravaganza.org/ @@ -1573,7 +1548,7 @@ THREE.Vector3.prototype = { case 0: this.x = value; break; case 1: this.y = value; break; case 2: this.z = value; break; - default: throw new Error( "index is out of range: " + index ); + default: throw new Error( 'index is out of range: ' + index ); } @@ -1586,7 +1561,7 @@ THREE.Vector3.prototype = { case 0: return this.x; case 1: return this.y; case 2: return this.z; - default: throw new Error( "index is out of range: " + index ); + default: throw new Error( 'index is out of range: ' + index ); } @@ -1606,7 +1581,7 @@ THREE.Vector3.prototype = { if ( w !== undefined ) { - console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); return this.addVectors( v, w ); } @@ -1643,7 +1618,7 @@ THREE.Vector3.prototype = { if ( w !== undefined ) { - console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); return this.subVectors( v, w ); } @@ -1670,7 +1645,7 @@ THREE.Vector3.prototype = { if ( w !== undefined ) { - console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); + console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); return this.multiplyVectors( v, w ); } @@ -1711,7 +1686,7 @@ THREE.Vector3.prototype = { if ( euler instanceof THREE.Euler === false ) { - console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' ); + console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' ); } @@ -1749,9 +1724,9 @@ THREE.Vector3.prototype = { var e = m.elements; - this.x = e[0] * x + e[3] * y + e[6] * z; - this.y = e[1] * x + e[4] * y + e[7] * z; - this.z = e[2] * x + e[5] * y + e[8] * z; + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; + this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; return this; @@ -1765,9 +1740,9 @@ THREE.Vector3.prototype = { var e = m.elements; - this.x = e[0] * x + e[4] * y + e[8] * z + e[12]; - this.y = e[1] * x + e[5] * y + e[9] * z + e[13]; - this.z = e[2] * x + e[6] * y + e[10] * z + e[14]; + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ]; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ]; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ]; return this; @@ -1780,11 +1755,11 @@ THREE.Vector3.prototype = { var x = this.x, y = this.y, z = this.z; var e = m.elements; - var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide + var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide - this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d; - this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d; - this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d; + this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d; + this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d; + this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d; return this; @@ -1806,13 +1781,13 @@ THREE.Vector3.prototype = { 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; + var iw = - qx * x - qy * y - qz * z; // calculate result * inverse quat - this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; - this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; - this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; + this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; + this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; + this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; return this; @@ -1827,9 +1802,9 @@ THREE.Vector3.prototype = { var e = m.elements; - this.x = e[0] * x + e[4] * y + e[8] * z; - this.y = e[1] * x + e[5] * y + e[9] * z; - this.z = e[2] * x + e[6] * y + e[10] * z; + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; this.normalize(); @@ -2019,7 +1994,11 @@ THREE.Vector3.prototype = { negate: function () { - return this.multiplyScalar( - 1 ); + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + + return this; }, @@ -2080,7 +2059,7 @@ THREE.Vector3.prototype = { if ( w !== undefined ) { - console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); + console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); return this.crossVectors( v, w ); } @@ -2165,7 +2144,7 @@ THREE.Vector3.prototype = { // clamp, to handle numerical problems - return Math.acos( THREE.Math.clamp( theta, -1, 1 ) ); + return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) ); }, @@ -2187,19 +2166,19 @@ THREE.Vector3.prototype = { setEulerFromRotationMatrix: function ( m, order ) { - console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code."); + console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); }, setEulerFromQuaternion: function ( q, order ) { - console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code."); + console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); }, getPositionFromMatrix: function ( m ) { - console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." ); + console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); return this.setFromMatrixPosition( m ); @@ -2207,14 +2186,14 @@ THREE.Vector3.prototype = { getScaleFromMatrix: function ( m ) { - console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." ); + console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); return this.setFromMatrixScale( m ); }, getColumnFromMatrix: function ( index, matrix ) { - console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." ); + console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); return this.setFromMatrixColumn( index, matrix ); @@ -2286,6 +2265,9 @@ THREE.Vector3.prototype = { } }; + +// File:src/math/Vector4.js + /** * @author supereggbert / http://www.paulbrunt.co.uk/ * @author philogb / http://blog.thejit.org/ @@ -2358,7 +2340,7 @@ THREE.Vector4.prototype = { case 1: this.y = value; break; case 2: this.z = value; break; case 3: this.w = value; break; - default: throw new Error( "index is out of range: " + index ); + default: throw new Error( 'index is out of range: ' + index ); } @@ -2372,7 +2354,7 @@ THREE.Vector4.prototype = { case 1: return this.y; case 2: return this.z; case 3: return this.w; - default: throw new Error( "index is out of range: " + index ); + default: throw new Error( 'index is out of range: ' + index ); } @@ -2393,7 +2375,7 @@ THREE.Vector4.prototype = { if ( w !== undefined ) { - console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); return this.addVectors( v, w ); } @@ -2433,7 +2415,7 @@ THREE.Vector4.prototype = { if ( w !== undefined ) { - console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); return this.subVectors( v, w ); } @@ -2478,10 +2460,10 @@ THREE.Vector4.prototype = { var e = m.elements; - this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w; - this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w; - this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w; - this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w; + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; + this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; return this; @@ -2551,22 +2533,22 @@ THREE.Vector4.prototype = { te = m.elements, - m11 = te[0], m12 = te[4], m13 = te[8], - m21 = te[1], m22 = te[5], m23 = te[9], - m31 = te[2], m32 = te[6], m33 = te[10]; + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; if ( ( Math.abs( m12 - m21 ) < epsilon ) - && ( Math.abs( m13 - m31 ) < epsilon ) - && ( Math.abs( m23 - m32 ) < epsilon ) ) { + && ( Math.abs( m13 - m31 ) < epsilon ) + && ( Math.abs( m23 - m32 ) < epsilon ) ) { // singularity found // first check for identity matrix which must have +1 for all terms // in leading diagonal and zero in other terms if ( ( Math.abs( m12 + m21 ) < epsilon2 ) - && ( Math.abs( m13 + m31 ) < epsilon2 ) - && ( Math.abs( m23 + m32 ) < epsilon2 ) - && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + && ( Math.abs( m13 + m31 ) < epsilon2 ) + && ( Math.abs( m23 + m32 ) < epsilon2 ) + && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { // this singularity is identity matrix so angle = 0 @@ -2646,8 +2628,8 @@ THREE.Vector4.prototype = { // as we have reached here there are no singularities so we can handle normally var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) - + ( m13 - m31 ) * ( m13 - m31 ) - + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize if ( Math.abs( s ) < 0.001 ) s = 1; @@ -2839,7 +2821,12 @@ THREE.Vector4.prototype = { negate: function () { - return this.multiplyScalar( -1 ); + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; + + return this; }, @@ -2929,6 +2916,8 @@ THREE.Vector4.prototype = { }; +// File:src/math/Euler.js + /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley @@ -3039,15 +3028,15 @@ THREE.Euler.prototype = { // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) var te = m.elements; - var m11 = te[0], m12 = te[4], m13 = te[8]; - var m21 = te[1], m22 = te[5], m23 = te[9]; - var m31 = te[2], m32 = te[6], m33 = te[10]; + var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; order = order || this._order; if ( order === 'XYZ' ) { - this._y = Math.asin( clamp( m13, -1, 1 ) ); + this._y = Math.asin( clamp( m13, - 1, 1 ) ); if ( Math.abs( m13 ) < 0.99999 ) { @@ -3063,7 +3052,7 @@ THREE.Euler.prototype = { } else if ( order === 'YXZ' ) { - this._x = Math.asin( - clamp( m23, -1, 1 ) ); + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); if ( Math.abs( m23 ) < 0.99999 ) { @@ -3079,7 +3068,7 @@ THREE.Euler.prototype = { } else if ( order === 'ZXY' ) { - this._x = Math.asin( clamp( m32, -1, 1 ) ); + this._x = Math.asin( clamp( m32, - 1, 1 ) ); if ( Math.abs( m32 ) < 0.99999 ) { @@ -3095,7 +3084,7 @@ THREE.Euler.prototype = { } else if ( order === 'ZYX' ) { - this._y = Math.asin( - clamp( m31, -1, 1 ) ); + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); if ( Math.abs( m31 ) < 0.99999 ) { @@ -3111,7 +3100,7 @@ THREE.Euler.prototype = { } else if ( order === 'YZX' ) { - this._z = Math.asin( clamp( m21, -1, 1 ) ); + this._z = Math.asin( clamp( m21, - 1, 1 ) ); if ( Math.abs( m21 ) < 0.99999 ) { @@ -3127,7 +3116,7 @@ THREE.Euler.prototype = { } else if ( order === 'XZY' ) { - this._z = Math.asin( - clamp( m12, -1, 1 ) ); + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); if ( Math.abs( m12 ) < 0.99999 ) { @@ -3143,7 +3132,7 @@ THREE.Euler.prototype = { } else { - console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order ) + console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ) } @@ -3173,42 +3162,42 @@ THREE.Euler.prototype = { if ( order === 'XYZ' ) { this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) ); - this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ), -1, 1 ) ); + this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ), - 1, 1 ) ); this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) ); } else if ( order === 'YXZ' ) { - this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ), -1, 1 ) ); + this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ), - 1, 1 ) ); this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) ); this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) ); } else if ( order === 'ZXY' ) { - this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ), -1, 1 ) ); + this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ), - 1, 1 ) ); this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) ); this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) ); } else if ( order === 'ZYX' ) { this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) ); - this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ), -1, 1 ) ); + this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ), - 1, 1 ) ); this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) ); } else if ( order === 'YZX' ) { this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) ); this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) ); - this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ), -1, 1 ) ); + this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ), - 1, 1 ) ); } else if ( order === 'XZY' ) { this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) ); this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) ); - this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ), -1, 1 ) ); + this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ), - 1, 1 ) ); } else { - console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order ) + console.warn( 'THREE.Euler: .setFromQuaternion() given unsupported order: ' + order ) } @@ -3279,6 +3268,8 @@ THREE.Euler.prototype = { }; +// File:src/math/Line3.js + /** * @author bhouston / http://exocortex.com */ @@ -3346,7 +3337,7 @@ THREE.Line3.prototype = { }, - closestPointToPointParameter: function() { + closestPointToPointParameter: function () { var startP = new THREE.Vector3(); var startEnd = new THREE.Vector3(); @@ -3406,6 +3397,8 @@ THREE.Line3.prototype = { }; +// File:src/math/Box2.js + /** * @author bhouston / http://exocortex.com */ @@ -3413,7 +3406,7 @@ THREE.Line3.prototype = { THREE.Box2 = function ( min, max ) { this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity ); + this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity ); }; @@ -3432,42 +3425,11 @@ THREE.Box2.prototype = { setFromPoints: function ( points ) { - if ( points.length > 0 ) { - - var point = points[ 0 ]; - - this.min.copy( point ); - this.max.copy( point ); - - for ( var i = 1, il = points.length; i < il; i ++ ) { - - point = points[ i ]; - - if ( point.x < this.min.x ) { - - this.min.x = point.x; - - } else if ( point.x > this.max.x ) { - - this.max.x = point.x; - - } - - if ( point.y < this.min.y ) { - - this.min.y = point.y; - - } else if ( point.y > this.max.y ) { - - this.max.y = point.y; - - } - - } + this.makeEmpty(); - } else { + for ( var i = 0, il = points.length; i < il; i ++ ) { - this.makeEmpty(); + this.expandByPoint( points[ i ] ) } @@ -3503,7 +3465,7 @@ THREE.Box2.prototype = { makeEmpty: function () { this.min.x = this.min.y = Infinity; - this.max.x = this.max.y = -Infinity; + this.max.x = this.max.y = - Infinity; return this; @@ -3549,7 +3511,7 @@ THREE.Box2.prototype = { expandByScalar: function ( scalar ) { - this.min.addScalar( -scalar ); + this.min.addScalar( - scalar ); this.max.addScalar( scalar ); return this; @@ -3671,6 +3633,8 @@ THREE.Box2.prototype = { }; +// File:src/math/Box3.js + /** * @author bhouston / http://exocortex.com * @author WestLangley / http://github.com/WestLangley @@ -3679,7 +3643,7 @@ THREE.Box2.prototype = { THREE.Box3 = function ( min, max ) { this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity ); + this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity ); }; @@ -3696,60 +3660,13 @@ THREE.Box3.prototype = { }, - addPoint: function ( point ) { - - if ( point.x < this.min.x ) { - - this.min.x = point.x; - - } else if ( point.x > this.max.x ) { - - this.max.x = point.x; - - } - - if ( point.y < this.min.y ) { - - this.min.y = point.y; - - } else if ( point.y > this.max.y ) { - - this.max.y = point.y; - - } - - if ( point.z < this.min.z ) { - - this.min.z = point.z; - - } else if ( point.z > this.max.z ) { - - this.max.z = point.z; - - } - - return this; - - }, - setFromPoints: function ( points ) { - if ( points.length > 0 ) { - - var point = points[ 0 ]; - - this.min.copy( point ); - this.max.copy( point ); - - for ( var i = 1, il = points.length; i < il; i ++ ) { - - this.addPoint( points[ i ] ) + this.makeEmpty(); - } - - } else { + for ( var i = 0, il = points.length; i < il; i ++ ) { - this.makeEmpty(); + this.expandByPoint( points[ i ] ) } @@ -3757,7 +3674,7 @@ THREE.Box3.prototype = { }, - setFromCenterAndSize: function() { + setFromCenterAndSize: function () { var v1 = new THREE.Vector3(); @@ -3774,14 +3691,14 @@ THREE.Box3.prototype = { }(), - setFromObject: function() { + setFromObject: function () { // Computes the world-axis-aligned bounding box of an object (including its children), // accounting for both the object's, and childrens', world transforms var v1 = new THREE.Vector3(); - return function( object ) { + return function ( object ) { var scope = this; @@ -3795,7 +3712,7 @@ THREE.Box3.prototype = { var vertices = node.geometry.vertices; - for ( var i = 0, il = vertices.length; i < il; i++ ) { + for ( var i = 0, il = vertices.length; i < il; i ++ ) { v1.copy( vertices[ i ] ); @@ -3827,7 +3744,7 @@ THREE.Box3.prototype = { makeEmpty: function () { this.min.x = this.min.y = this.min.z = Infinity; - this.max.x = this.max.y = this.max.z = -Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; return this; @@ -3875,7 +3792,7 @@ THREE.Box3.prototype = { expandByScalar: function ( scalar ) { - this.min.addScalar( -scalar ); + this.min.addScalar( - scalar ); this.max.addScalar( scalar ); return this; @@ -3948,7 +3865,7 @@ THREE.Box3.prototype = { }, - distanceToPoint: function() { + distanceToPoint: function () { var v1 = new THREE.Vector3(); @@ -3961,7 +3878,7 @@ THREE.Box3.prototype = { }(), - getBoundingSphere: function() { + getBoundingSphere: function () { var v1 = new THREE.Vector3(); @@ -3996,7 +3913,7 @@ THREE.Box3.prototype = { }, - applyMatrix4: function() { + applyMatrix4: function () { var points = [ new THREE.Vector3(), @@ -4012,14 +3929,14 @@ THREE.Box3.prototype = { return function ( matrix ) { // NOTE: I am using a binary pattern to specify all 2^3 combinations below - points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 - points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 - points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 - points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 - points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 - points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 - points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 - points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 + points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 + points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 + points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 + points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 + points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 + points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 + points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 + points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 this.makeEmpty(); this.setFromPoints( points ); @@ -4053,6 +3970,8 @@ THREE.Box3.prototype = { }; +// File:src/math/Matrix3.js + /** * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley @@ -4065,9 +3984,9 @@ THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { var te = this.elements; - te[0] = ( n11 !== undefined ) ? n11 : 1; te[3] = n12 || 0; te[6] = n13 || 0; - te[1] = n21 || 0; te[4] = ( n22 !== undefined ) ? n22 : 1; te[7] = n23 || 0; - te[2] = n31 || 0; te[5] = n32 || 0; te[8] = ( n33 !== undefined ) ? n33 : 1; + te[ 0 ] = ( n11 !== undefined ) ? n11 : 1; te[ 3 ] = n12 || 0; te[ 6 ] = n13 || 0; + te[ 1 ] = n21 || 0; te[ 4 ] = ( n22 !== undefined ) ? n22 : 1; te[ 7 ] = n23 || 0; + te[ 2 ] = n31 || 0; te[ 5 ] = n32 || 0; te[ 8 ] = ( n33 !== undefined ) ? n33 : 1; }; @@ -4079,9 +3998,9 @@ THREE.Matrix3.prototype = { var te = this.elements; - te[0] = n11; te[3] = n12; te[6] = n13; - te[1] = n21; te[4] = n22; te[7] = n23; - te[2] = n31; te[5] = n32; te[8] = n33; + te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13; + te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23; + te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33; return this; @@ -4107,9 +4026,9 @@ THREE.Matrix3.prototype = { this.set( - me[0], me[3], me[6], - me[1], me[4], me[7], - me[2], me[5], me[8] + me[ 0 ], me[ 3 ], me[ 6 ], + me[ 1 ], me[ 4 ], me[ 7 ], + me[ 2 ], me[ 5 ], me[ 8 ] ); @@ -4119,19 +4038,19 @@ THREE.Matrix3.prototype = { multiplyVector3: function ( vector ) { - console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); + console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); return vector.applyMatrix3( this ); }, multiplyVector3Array: function ( a ) { - console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); + console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); return this.applyToVector3Array( a ); }, - applyToVector3Array: function() { + applyToVector3Array: function () { var v1 = new THREE.Vector3(); @@ -4164,9 +4083,9 @@ THREE.Matrix3.prototype = { var te = this.elements; - te[0] *= s; te[3] *= s; te[6] *= s; - te[1] *= s; te[4] *= s; te[7] *= s; - te[2] *= s; te[5] *= s; te[8] *= s; + te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; + te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; + te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; return this; @@ -4176,11 +4095,11 @@ THREE.Matrix3.prototype = { var te = this.elements; - var a = te[0], b = te[1], c = te[2], - d = te[3], e = te[4], f = te[5], - g = te[6], h = te[7], i = te[8]; + var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], + d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], + g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; - return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; }, @@ -4192,15 +4111,15 @@ THREE.Matrix3.prototype = { var me = matrix.elements; var te = this.elements; - te[ 0 ] = me[10] * me[5] - me[6] * me[9]; - te[ 1 ] = - me[10] * me[1] + me[2] * me[9]; - te[ 2 ] = me[6] * me[1] - me[2] * me[5]; - te[ 3 ] = - me[10] * me[4] + me[6] * me[8]; - te[ 4 ] = me[10] * me[0] - me[2] * me[8]; - te[ 5 ] = - me[6] * me[0] + me[2] * me[4]; - te[ 6 ] = me[9] * me[4] - me[5] * me[8]; - te[ 7 ] = - me[9] * me[0] + me[1] * me[8]; - te[ 8 ] = me[5] * me[0] - me[1] * me[4]; + te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ]; + te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ]; + te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ]; + te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ]; + te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ]; + te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ]; + te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ]; + te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ]; + te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ]; var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ]; @@ -4236,29 +4155,29 @@ THREE.Matrix3.prototype = { var tmp, m = this.elements; - tmp = m[1]; m[1] = m[3]; m[3] = tmp; - tmp = m[2]; m[2] = m[6]; m[6] = tmp; - tmp = m[5]; m[5] = m[7]; m[7] = tmp; + tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; + tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; + tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; return this; }, - flattenToArrayOffset: function( array, offset ) { + flattenToArrayOffset: function ( array, offset ) { var te = this.elements; - array[ offset ] = te[0]; - array[ offset + 1 ] = te[1]; - array[ offset + 2 ] = te[2]; - - array[ offset + 3 ] = te[3]; - array[ offset + 4 ] = te[4]; - array[ offset + 5 ] = te[5]; - - array[ offset + 6 ] = te[6]; - array[ offset + 7 ] = te[7]; - array[ offset + 8 ] = te[8]; + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + + array[ offset + 3 ] = te[ 3 ]; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; return array; @@ -4318,9 +4237,9 @@ THREE.Matrix3.prototype = { return new THREE.Matrix3( - te[0], te[3], te[6], - te[1], te[4], te[7], - te[2], te[5], te[8] + te[ 0 ], te[ 3 ], te[ 6 ], + te[ 1 ], te[ 4 ], te[ 7 ], + te[ 2 ], te[ 5 ], te[ 8 ] ); @@ -4328,6 +4247,8 @@ THREE.Matrix3.prototype = { }; +// File:src/math/Matrix4.js + /** * @author mrdoob / http://mrdoob.com/ * @author supereggbert / http://www.paulbrunt.co.uk/ @@ -4351,10 +4272,10 @@ THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33 var te = this.elements; - te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0; - te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0; - te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0; - te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1; + te[ 0 ] = ( n11 !== undefined ) ? n11 : 1; te[ 4 ] = n12 || 0; te[ 8 ] = n13 || 0; te[ 12 ] = n14 || 0; + te[ 1 ] = n21 || 0; te[ 5 ] = ( n22 !== undefined ) ? n22 : 1; te[ 9 ] = n23 || 0; te[ 13 ] = n24 || 0; + te[ 2 ] = n31 || 0; te[ 6 ] = n32 || 0; te[ 10 ] = ( n33 !== undefined ) ? n33 : 1; te[ 14 ] = n34 || 0; + te[ 3 ] = n41 || 0; te[ 7 ] = n42 || 0; te[ 11 ] = n43 || 0; te[ 15 ] = ( n44 !== undefined ) ? n44 : 1; }; @@ -4366,10 +4287,10 @@ THREE.Matrix4.prototype = { var te = this.elements; - te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14; - te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24; - te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34; - te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44; + te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; + te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; + te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; + te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; return this; @@ -4400,7 +4321,7 @@ THREE.Matrix4.prototype = { extractPosition: function ( m ) { - console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' ); + console.warn( 'THREEMatrix4: .extractPosition() has been renamed to .copyPosition().' ); return this.copyPosition( m ); }, @@ -4410,9 +4331,9 @@ THREE.Matrix4.prototype = { var te = this.elements; var me = m.elements; - te[12] = me[12]; - te[13] = me[13]; - te[14] = me[14]; + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; return this; @@ -4427,21 +4348,21 @@ THREE.Matrix4.prototype = { var te = this.elements; var me = m.elements; - var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length(); - var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length(); - var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length(); + var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length(); + var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length(); + var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length(); - te[0] = me[0] * scaleX; - te[1] = me[1] * scaleX; - te[2] = me[2] * scaleX; + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; - te[4] = me[4] * scaleY; - te[5] = me[5] * scaleY; - te[6] = me[6] * scaleY; + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; - te[8] = me[8] * scaleZ; - te[9] = me[9] * scaleZ; - te[10] = me[10] * scaleZ; + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; return this; @@ -4453,7 +4374,7 @@ THREE.Matrix4.prototype = { if ( euler instanceof THREE.Euler === false ) { - console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' ); + console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); } @@ -4468,110 +4389,110 @@ THREE.Matrix4.prototype = { var ae = a * e, af = a * f, be = b * e, bf = b * f; - te[0] = c * e; - te[4] = - c * f; - te[8] = d; + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; - te[1] = af + be * d; - te[5] = ae - bf * d; - te[9] = - b * c; + te[ 1 ] = af + be * d; + te[ 5 ] = ae - bf * d; + te[ 9 ] = - b * c; - te[2] = bf - ae * d; - te[6] = be + af * d; - te[10] = a * c; + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; } else if ( euler.order === 'YXZ' ) { var ce = c * e, cf = c * f, de = d * e, df = d * f; - te[0] = ce + df * b; - te[4] = de * b - cf; - te[8] = a * d; + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - te[1] = a * f; - te[5] = a * e; - te[9] = - b; + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; - te[2] = cf * b - de; - te[6] = df + ce * b; - te[10] = a * c; + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; } else if ( euler.order === 'ZXY' ) { var ce = c * e, cf = c * f, de = d * e, df = d * f; - te[0] = ce - df * b; - te[4] = - a * f; - te[8] = de + cf * b; + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - te[1] = cf + de * b; - te[5] = a * e; - te[9] = df - ce * b; + te[ 1 ] = cf + de * b; + te[ 5 ] = a * e; + te[ 9 ] = df - ce * b; - te[2] = - a * d; - te[6] = b; - te[10] = a * c; + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; } else if ( euler.order === 'ZYX' ) { var ae = a * e, af = a * f, be = b * e, bf = b * f; - te[0] = c * e; - te[4] = be * d - af; - te[8] = ae * d + bf; + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; - te[1] = c * f; - te[5] = bf * d + ae; - te[9] = af * d - be; + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; - te[2] = - d; - te[6] = b * c; - te[10] = a * c; + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; } else if ( euler.order === 'YZX' ) { var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - te[0] = c * e; - te[4] = bd - ac * f; - te[8] = bc * f + ad; + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - te[1] = f; - te[5] = a * e; - te[9] = - b * e; + te[ 1 ] = f; + te[ 5 ] = a * e; + te[ 9 ] = - b * e; - te[2] = - d * e; - te[6] = ad * f + bc; - te[10] = ac - bd * f; + te[ 2 ] = - d * e; + te[ 6 ] = ad * f + bc; + te[ 10 ] = ac - bd * f; } else if ( euler.order === 'XZY' ) { var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - te[0] = c * e; - te[4] = - f; - te[8] = d * e; + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; - te[1] = ac * f + bd; - te[5] = a * e; - te[9] = ad * f - bc; + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; - te[2] = bc * f - ad; - te[6] = b * e; - te[10] = bd * f + ac; + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; } // last column - te[3] = 0; - te[7] = 0; - te[11] = 0; + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; // bottom row - te[12] = 0; - te[13] = 0; - te[14] = 0; - te[15] = 1; + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; return this; @@ -4579,7 +4500,7 @@ THREE.Matrix4.prototype = { setRotationFromQuaternion: function ( q ) { - console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' ); + console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); return this.makeRotationFromQuaternion( q ); @@ -4595,34 +4516,34 @@ THREE.Matrix4.prototype = { var yy = y * y2, yz = y * z2, zz = z * z2; var wx = w * x2, wy = w * y2, wz = w * z2; - te[0] = 1 - ( yy + zz ); - te[4] = xy - wz; - te[8] = xz + wy; + te[ 0 ] = 1 - ( yy + zz ); + te[ 4 ] = xy - wz; + te[ 8 ] = xz + wy; - te[1] = xy + wz; - te[5] = 1 - ( xx + zz ); - te[9] = yz - wx; + te[ 1 ] = xy + wz; + te[ 5 ] = 1 - ( xx + zz ); + te[ 9 ] = yz - wx; - te[2] = xz - wy; - te[6] = yz + wx; - te[10] = 1 - ( xx + yy ); + te[ 2 ] = xz - wy; + te[ 6 ] = yz + wx; + te[ 10 ] = 1 - ( xx + yy ); // last column - te[3] = 0; - te[7] = 0; - te[11] = 0; + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; // bottom row - te[12] = 0; - te[13] = 0; - te[14] = 0; - te[15] = 1; + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; return this; }, - lookAt: function() { + lookAt: function () { var x = new THREE.Vector3(); var y = new THREE.Vector3(); @@ -4652,9 +4573,9 @@ THREE.Matrix4.prototype = { y.crossVectors( z, x ); - te[0] = x.x; te[4] = y.x; te[8] = z.x; - te[1] = x.y; te[5] = y.y; te[9] = z.y; - te[2] = x.z; te[6] = y.z; te[10] = z.z; + te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x; + te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y; + te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z; return this; @@ -4666,7 +4587,7 @@ THREE.Matrix4.prototype = { if ( n !== undefined ) { - console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); + console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); return this.multiplyMatrices( m, n ); } @@ -4681,35 +4602,35 @@ THREE.Matrix4.prototype = { var be = b.elements; var te = this.elements; - var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; - var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; - var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; - var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; + var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; - var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; - var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; - var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; - var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; + var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; - te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; - te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; - te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; - te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; - te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; - te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; - te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; return this; @@ -4721,10 +4642,10 @@ THREE.Matrix4.prototype = { this.multiplyMatrices( a, b ); - r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3]; - r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7]; - r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11]; - r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15]; + r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ]; + r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ]; + r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ]; + r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ]; return this; @@ -4734,10 +4655,10 @@ THREE.Matrix4.prototype = { var te = this.elements; - te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s; - te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s; - te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s; - te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s; + te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; + te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; + te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; + te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; return this; @@ -4745,26 +4666,26 @@ THREE.Matrix4.prototype = { multiplyVector3: function ( vector ) { - console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' ); + console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' ); return vector.applyProjection( this ); }, multiplyVector4: function ( vector ) { - console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); + console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); return vector.applyMatrix4( this ); }, multiplyVector3Array: function ( a ) { - console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); + console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); return this.applyToVector3Array( a ); }, - applyToVector3Array: function() { + applyToVector3Array: function () { var v1 = new THREE.Vector3(); @@ -4795,7 +4716,7 @@ THREE.Matrix4.prototype = { rotateAxis: function ( v ) { - console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); + console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); v.transformDirection( this ); @@ -4803,7 +4724,7 @@ THREE.Matrix4.prototype = { crossVector: function ( vector ) { - console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); + console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); return vector.applyMatrix4( this ); }, @@ -4812,46 +4733,46 @@ THREE.Matrix4.prototype = { var te = this.elements; - var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12]; - var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13]; - var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14]; - var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15]; + var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; //TODO: make this more efficient //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) return ( n41 * ( - +n14 * n23 * n32 - -n13 * n24 * n32 - -n14 * n22 * n33 - +n12 * n24 * n33 - +n13 * n22 * n34 - -n12 * n23 * n34 + + n14 * n23 * n32 + - n13 * n24 * n32 + - n14 * n22 * n33 + + n12 * n24 * n33 + + n13 * n22 * n34 + - n12 * n23 * n34 ) + n42 * ( - +n11 * n23 * n34 - -n11 * n24 * n33 - +n14 * n21 * n33 - -n13 * n21 * n34 - +n13 * n24 * n31 - -n14 * n23 * n31 + + n11 * n23 * n34 + - n11 * n24 * n33 + + n14 * n21 * n33 + - n13 * n21 * n34 + + n13 * n24 * n31 + - n14 * n23 * n31 ) + n43 * ( - +n11 * n24 * n32 - -n11 * n22 * n34 - -n14 * n21 * n32 - +n12 * n21 * n34 - +n14 * n22 * n31 - -n12 * n24 * n31 + + n11 * n24 * n32 + - n11 * n22 * n34 + - n14 * n21 * n32 + + n12 * n21 * n34 + + n14 * n22 * n31 + - n12 * n24 * n31 ) + n44 * ( - -n13 * n22 * n31 - -n11 * n23 * n32 - +n11 * n22 * n33 - +n13 * n21 * n32 - -n12 * n21 * n33 - +n12 * n23 * n31 + - n13 * n22 * n31 + - n11 * n23 * n32 + + n11 * n22 * n33 + + n13 * n21 * n32 + - n12 * n21 * n33 + + n12 * n23 * n31 ) ); @@ -4863,56 +4784,56 @@ THREE.Matrix4.prototype = { var te = this.elements; var tmp; - tmp = te[1]; te[1] = te[4]; te[4] = tmp; - tmp = te[2]; te[2] = te[8]; te[8] = tmp; - tmp = te[6]; te[6] = te[9]; te[9] = tmp; + tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; + tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; + tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; - tmp = te[3]; te[3] = te[12]; te[12] = tmp; - tmp = te[7]; te[7] = te[13]; te[13] = tmp; - tmp = te[11]; te[11] = te[14]; te[14] = tmp; + tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; + tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; + tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; return this; }, - flattenToArrayOffset: function( array, offset ) { + flattenToArrayOffset: function ( array, offset ) { var te = this.elements; - array[ offset ] = te[0]; - array[ offset + 1 ] = te[1]; - array[ offset + 2 ] = te[2]; - array[ offset + 3 ] = te[3]; + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; - array[ offset + 4 ] = te[4]; - array[ offset + 5 ] = te[5]; - array[ offset + 6 ] = te[6]; - array[ offset + 7 ] = te[7]; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; - array[ offset + 8 ] = te[8]; - array[ offset + 9 ] = te[9]; - array[ offset + 10 ] = te[10]; - array[ offset + 11 ] = te[11]; + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; - array[ offset + 12 ] = te[12]; - array[ offset + 13 ] = te[13]; - array[ offset + 14 ] = te[14]; - array[ offset + 15 ] = te[15]; + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; return array; }, - getPosition: function() { + getPosition: function () { var v1 = new THREE.Vector3(); return function () { - console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); + console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); var te = this.elements; - return v1.set( te[12], te[13], te[14] ); + return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] ); }; @@ -4922,9 +4843,9 @@ THREE.Matrix4.prototype = { var te = this.elements; - te[12] = v.x; - te[13] = v.y; - te[14] = v.z; + te[ 12 ] = v.x; + te[ 13 ] = v.y; + te[ 14 ] = v.z; return this; @@ -4936,27 +4857,27 @@ THREE.Matrix4.prototype = { var te = this.elements; var me = m.elements; - var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12]; - var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13]; - var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14]; - var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15]; - - te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44; - te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44; - te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44; - te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34; - te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44; - te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44; - te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44; - te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34; - te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44; - te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44; - te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44; - te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34; - te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43; - te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43; - te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43; - te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33; + var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ]; + var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ]; + var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ]; + var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ]; + + te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44; + te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44; + te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44; + te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34; + te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44; + te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44; + te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44; + te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34; + te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43; + te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43; + te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43; + te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33; var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ]; @@ -4966,7 +4887,7 @@ THREE.Matrix4.prototype = { if ( throwOnInvertible || false ) { - throw new Error( msg ); + throw new Error( msg ); } else { @@ -4987,31 +4908,31 @@ THREE.Matrix4.prototype = { translate: function ( v ) { - console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.'); + console.warn( 'THREE.Matrix4: .translate() has been removed.' ); }, rotateX: function ( angle ) { - console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.'); + console.warn( 'THREE.Matrix4: .rotateX() has been removed.' ); }, rotateY: function ( angle ) { - console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.'); + console.warn( 'THREE.Matrix4: .rotateY() has been removed.' ); }, rotateZ: function ( angle ) { - console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.'); + console.warn( 'THREE.Matrix4: .rotateZ() has been removed.' ); }, rotateByAxis: function ( axis, angle ) { - console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.'); + console.warn( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); }, @@ -5020,10 +4941,10 @@ THREE.Matrix4.prototype = { var te = this.elements; var x = v.x, y = v.y, z = v.z; - te[0] *= x; te[4] *= y; te[8] *= z; - te[1] *= x; te[5] *= y; te[9] *= z; - te[2] *= x; te[6] *= y; te[10] *= z; - te[3] *= x; te[7] *= y; te[11] *= z; + te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; + te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; + te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; + te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; return this; @@ -5033,9 +4954,9 @@ THREE.Matrix4.prototype = { var te = this.elements; - var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2]; - var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6]; - var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10]; + var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) ); @@ -5063,7 +4984,7 @@ THREE.Matrix4.prototype = { this.set( 1, 0, 0, 0, - 0, c, -s, 0, + 0, c, - s, 0, 0, s, c, 0, 0, 0, 0, 1 @@ -5081,7 +5002,7 @@ THREE.Matrix4.prototype = { c, 0, s, 0, 0, 1, 0, 0, - -s, 0, c, 0, + - s, 0, c, 0, 0, 0, 0, 1 ); @@ -5096,7 +5017,7 @@ THREE.Matrix4.prototype = { this.set( - c, -s, 0, 0, + c, - s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 @@ -5164,19 +5085,19 @@ THREE.Matrix4.prototype = { var te = this.elements; - var sx = vector.set( te[0], te[1], te[2] ).length(); - var sy = vector.set( te[4], te[5], te[6] ).length(); - var sz = vector.set( te[8], te[9], te[10] ).length(); + var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); // if determine is negative, we need to invert one scale var det = this.determinant(); - if( det < 0 ) { - sx = -sx; + if ( det < 0 ) { + sx = - sx; } - position.x = te[12]; - position.y = te[13]; - position.z = te[14]; + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; // scale the rotation part @@ -5186,17 +5107,17 @@ THREE.Matrix4.prototype = { var invSY = 1 / sy; var invSZ = 1 / sz; - matrix.elements[0] *= invSX; - matrix.elements[1] *= invSX; - matrix.elements[2] *= invSX; + matrix.elements[ 0 ] *= invSX; + matrix.elements[ 1 ] *= invSX; + matrix.elements[ 2 ] *= invSX; - matrix.elements[4] *= invSY; - matrix.elements[5] *= invSY; - matrix.elements[6] *= invSY; + matrix.elements[ 4 ] *= invSY; + matrix.elements[ 5 ] *= invSY; + matrix.elements[ 6 ] *= invSY; - matrix.elements[8] *= invSZ; - matrix.elements[9] *= invSZ; - matrix.elements[10] *= invSZ; + matrix.elements[ 8 ] *= invSZ; + matrix.elements[ 9 ] *= invSZ; + matrix.elements[ 10 ] *= invSZ; quaternion.setFromRotationMatrix( matrix ); @@ -5221,10 +5142,10 @@ THREE.Matrix4.prototype = { var c = - ( far + near ) / ( far - near ); var d = - 2 * far * near / ( far - near ); - te[0] = x; te[4] = 0; te[8] = a; te[12] = 0; - te[1] = 0; te[5] = y; te[9] = b; te[13] = 0; - te[2] = 0; te[6] = 0; te[10] = c; te[14] = d; - te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0; + te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; + te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; return this; @@ -5252,10 +5173,10 @@ THREE.Matrix4.prototype = { var y = ( top + bottom ) / h; var z = ( far + near ) / p; - te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x; - te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y; - te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z; - te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1; + te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; + te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; return this; @@ -5288,10 +5209,10 @@ THREE.Matrix4.prototype = { return new THREE.Matrix4( - te[0], te[4], te[8], te[12], - te[1], te[5], te[9], te[13], - te[2], te[6], te[10], te[14], - te[3], te[7], te[11], te[15] + te[ 0 ], te[ 4 ], te[ 8 ], te[ 12 ], + te[ 1 ], te[ 5 ], te[ 9 ], te[ 13 ], + te[ 2 ], te[ 6 ], te[ 10 ], te[ 14 ], + te[ 3 ], te[ 7 ], te[ 11 ], te[ 15 ] ); @@ -5299,6 +5220,8 @@ THREE.Matrix4.prototype = { }; +// File:src/math/Ray.js + /** * @author bhouston / http://exocortex.com */ @@ -5394,7 +5317,7 @@ THREE.Ray.prototype = { }(), - distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp // It returns the min distance between the ray and the segment @@ -5441,7 +5364,7 @@ THREE.Ray.prototype = { // region 1 s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0) ); + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; } @@ -5451,14 +5374,14 @@ THREE.Ray.prototype = { // region 5 s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0) ); + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; } } else { - if ( s1 <= - extDet) { + if ( s1 <= - extDet ) { // region 4 @@ -5518,6 +5441,47 @@ THREE.Ray.prototype = { }, + intersectSphere: function () { + + // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/ + + var v1 = new THREE.Vector3(); + + return function ( sphere, optionalTarget ) { + + v1.subVectors( sphere.center, this.origin ); + + var tca = v1.dot( this.direction ); + + var d2 = v1.dot( v1 ) - tca * tca; + + var radius2 = sphere.radius * sphere.radius; + + if ( d2 > radius2 ) return null; + + var thc = Math.sqrt( radius2 - d2 ); + + // t0 = first intersect point - entrance on front of sphere + var t0 = tca - thc; + + // t1 = second intersect point - exit point on back of sphere + var t1 = tca + thc; + + // test to see if both t0 and t1 are behind the ray - if so, return null + if ( t0 < 0 && t1 < 0 ) return null; + + // test to see if t0 is behind the ray: + // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, + // in order to always return an intersect point that is in front of the ray. + if ( t0 < 0 ) return this.at( t1, optionalTarget ); + + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, optionalTarget ); + + } + + }(), + isIntersectionPlane: function ( plane ) { // check if the ray lies on the plane first @@ -5534,7 +5498,7 @@ THREE.Ray.prototype = { if ( denominator * distToPoint < 0 ) { - return true + return true; } @@ -5550,7 +5514,7 @@ THREE.Ray.prototype = { if ( denominator == 0 ) { // line is coplanar, return origin - if( plane.distanceToPoint( this.origin ) == 0 ) { + if ( plane.distanceToPoint( this.origin ) == 0 ) { return 0; @@ -5584,14 +5548,14 @@ THREE.Ray.prototype = { }, isIntersectionBox: function () { - + var v = new THREE.Vector3(); return function ( box ) { return this.intersectBox( box, v ) !== null; - } + }; }(), @@ -5601,59 +5565,59 @@ THREE.Ray.prototype = { var tmin,tmax,tymin,tymax,tzmin,tzmax; - var invdirx = 1/this.direction.x, - invdiry = 1/this.direction.y, - invdirz = 1/this.direction.z; + var invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; var origin = this.origin; - if (invdirx >= 0) { - - tmin = (box.min.x - origin.x) * invdirx; - tmax = (box.max.x - origin.x) * invdirx; + if ( invdirx >= 0 ) { - } else { + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; - tmin = (box.max.x - origin.x) * invdirx; - tmax = (box.min.x - origin.x) * invdirx; - } + } else { - if (invdiry >= 0) { - - tymin = (box.min.y - origin.y) * invdiry; - tymax = (box.max.y - origin.y) * invdiry; + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; + } + + if ( invdiry >= 0 ) { + + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; } else { - tymin = (box.max.y - origin.y) * invdiry; - tymax = (box.min.y - origin.y) * invdiry; + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; } - if ((tmin > tymax) || (tymin > tmax)) return null; + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; // These lines also handle the case where tmin or tmax is NaN // (result of 0 * Infinity). x !== x returns true if x is NaN - - if (tymin > tmin || tmin !== tmin ) tmin = tymin; - if (tymax < tmax || tmax !== tmax ) tmax = tymax; + if ( tymin > tmin || tmin !== tmin ) tmin = tymin; - if (invdirz >= 0) { - - tzmin = (box.min.z - origin.z) * invdirz; - tzmax = (box.max.z - origin.z) * invdirz; + if ( tymax < tmax || tmax !== tmax ) tmax = tymax; + + if ( invdirz >= 0 ) { + + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; } else { - tzmin = (box.max.z - origin.z) * invdirz; - tzmax = (box.min.z - origin.z) * invdirz; + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; } - if ((tmin > tzmax) || (tzmin > tmax)) return null; + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - if (tzmin > tmin || tmin !== tmin ) tmin = tzmin; + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - if (tzmax < tmax || tmax !== tmax ) tmax = tzmax; + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; //return point closest to the ray (positive side) @@ -5663,7 +5627,7 @@ THREE.Ray.prototype = { }, - intersectTriangle: function() { + intersectTriangle: function () { // Compute the offset origin, edges, and normal. var diff = new THREE.Vector3(); @@ -5741,9 +5705,9 @@ THREE.Ray.prototype = { // Ray intersects triangle. return this.at( QdN / DdN, optionalTarget ); - - } - + + }; + }(), applyMatrix4: function ( matrix4 ) { @@ -5770,6 +5734,8 @@ THREE.Ray.prototype = { }; +// File:src/math/Sphere.js + /** * @author bhouston / http://exocortex.com * @author mrdoob / http://mrdoob.com/ @@ -5794,7 +5760,6 @@ THREE.Sphere.prototype = { return this; }, - setFromPoints: function () { var box = new THREE.Box3(); @@ -5823,8 +5788,8 @@ THREE.Sphere.prototype = { this.radius = Math.sqrt( maxRadiusSq ); - return this; - + return this; + }; }(), @@ -5924,6 +5889,8 @@ THREE.Sphere.prototype = { }; +// File:src/math/Frustum.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -5953,12 +5920,12 @@ THREE.Frustum.prototype = { var planes = this.planes; - planes[0].copy( p0 ); - planes[1].copy( p1 ); - planes[2].copy( p2 ); - planes[3].copy( p3 ); - planes[4].copy( p4 ); - planes[5].copy( p5 ); + planes[ 0 ].copy( p0 ); + planes[ 1 ].copy( p1 ); + planes[ 2 ].copy( p2 ); + planes[ 3 ].copy( p3 ); + planes[ 4 ].copy( p4 ); + planes[ 5 ].copy( p5 ); return this; @@ -5968,9 +5935,9 @@ THREE.Frustum.prototype = { var planes = this.planes; - for( var i = 0; i < 6; i ++ ) { + for ( var i = 0; i < 6; i ++ ) { - planes[i].copy( frustum.planes[i] ); + planes[ i ].copy( frustum.planes[ i ] ); } @@ -5982,10 +5949,10 @@ THREE.Frustum.prototype = { var planes = this.planes; var me = m.elements; - var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; - var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; - var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; - var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; + var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; + var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; + var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; + var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); @@ -6021,7 +5988,7 @@ THREE.Frustum.prototype = { var planes = this.planes; var center = sphere.center; - var negRadius = -sphere.radius; + var negRadius = - sphere.radius; for ( var i = 0; i < 6; i ++ ) { @@ -6039,19 +6006,19 @@ THREE.Frustum.prototype = { }, - intersectsBox : function() { + intersectsBox: function () { var p1 = new THREE.Vector3(), p2 = new THREE.Vector3(); - return function( box ) { + return function ( box ) { var planes = this.planes; - + for ( var i = 0; i < 6 ; i ++ ) { - - var plane = planes[i]; - + + var plane = planes[ i ]; + p1.x = plane.normal.x > 0 ? box.min.x : box.max.x; p2.x = plane.normal.x > 0 ? box.max.x : box.min.x; p1.y = plane.normal.y > 0 ? box.min.y : box.max.y; @@ -6061,13 +6028,13 @@ THREE.Frustum.prototype = { var d1 = plane.distanceToPoint( p1 ); var d2 = plane.distanceToPoint( p2 ); - + // if both outside plane, no intersection if ( d1 < 0 && d2 < 0 ) { - + return false; - + } } @@ -6103,6 +6070,8 @@ THREE.Frustum.prototype = { }; +// File:src/math/Plane.js + /** * @author bhouston / http://exocortex.com */ @@ -6145,7 +6114,7 @@ THREE.Plane.prototype = { }, - setFromCoplanarPoints: function() { + setFromCoplanarPoints: function () { var v1 = new THREE.Vector3(); var v2 = new THREE.Vector3(); @@ -6188,7 +6157,7 @@ THREE.Plane.prototype = { negate: function () { - this.constant *= -1; + this.constant *= - 1; this.normal.negate(); return this; @@ -6233,7 +6202,7 @@ THREE.Plane.prototype = { }, - intersectLine: function() { + intersectLine: function () { var v1 = new THREE.Vector3(); @@ -6248,7 +6217,7 @@ THREE.Plane.prototype = { if ( denominator == 0 ) { // line is coplanar, return origin - if( this.distanceToPoint( line.start ) == 0 ) { + if ( this.distanceToPoint( line.start ) == 0 ) { return result.copy( line.start ); @@ -6261,7 +6230,7 @@ THREE.Plane.prototype = { var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - if( t < 0 || t > 1 ) { + if ( t < 0 || t > 1 ) { return undefined; @@ -6281,7 +6250,7 @@ THREE.Plane.prototype = { }, - applyMatrix4: function() { + applyMatrix4: function () { var v1 = new THREE.Vector3(); var v2 = new THREE.Vector3(); @@ -6293,7 +6262,7 @@ THREE.Plane.prototype = { // http://www.songho.ca/opengl/gl_normaltransform.html var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix ); - + var newCoplanarPoint = this.coplanarPoint( v2 ); newCoplanarPoint.applyMatrix4( matrix ); @@ -6327,6 +6296,8 @@ THREE.Plane.prototype = { }; +// File:src/math/Math.js + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ @@ -6337,9 +6308,9 @@ THREE.Math = { generateUUID: function () { // http://www.broofa.com/Tools/Math.uuid.htm - - var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); - var uuid = new Array(36); + + var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); + var uuid = new Array( 36 ); var rnd = 0, r; return function () { @@ -6347,24 +6318,24 @@ THREE.Math = { for ( var i = 0; i < 36; i ++ ) { if ( i == 8 || i == 13 || i == 18 || i == 23 ) { - + uuid[ i ] = '-'; - + } else if ( i == 14 ) { - + uuid[ i ] = '4'; - + } else { - - if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; + + if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; r = rnd & 0xf; rnd = rnd >> 4; - uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; + uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ]; } } - - return uuid.join(''); + + return uuid.join( '' ); }; @@ -6401,9 +6372,9 @@ THREE.Math = { if ( x <= min ) return 0; if ( x >= max ) return 1; - x = ( x - min )/( max - min ); + x = ( x - min ) / ( max - min ); - return x*x*(3 - 2*x); + return x * x * ( 3 - 2 * x ); }, @@ -6412,9 +6383,9 @@ THREE.Math = { if ( x <= min ) return 0; if ( x >= max ) return 1; - x = ( x - min )/( max - min ); + x = ( x - min ) / ( max - min ); - return x*x*x*(x*(x*6 - 15) + 10); + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); }, @@ -6457,7 +6428,7 @@ THREE.Math = { }, - degToRad: function() { + degToRad: function () { var degreeToRadiansFactor = Math.PI / 180; @@ -6469,7 +6440,7 @@ THREE.Math = { }(), - radToDeg: function() { + radToDeg: function () { var radianToDegreesFactor = 180 / Math.PI; @@ -6489,6 +6460,8 @@ THREE.Math = { }; +// File:src/math/Spline.js + /** * Spline from Tween.js, slightly optimized (and trashed) * http://sole.github.com/tween.js/examples/05_spline.html @@ -6505,11 +6478,11 @@ THREE.Spline = function ( points ) { point, intPoint, weight, w2, w3, pa, pb, pc, pd; - this.initFromArray = function( a ) { + this.initFromArray = function ( a ) { this.points = []; - for ( var i = 0; i < a.length; i++ ) { + for ( var i = 0; i < a.length; i ++ ) { this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] }; @@ -6575,7 +6548,7 @@ THREE.Spline = function ( points ) { chunkLengths[ 0 ] = 0; - if ( !nSubDivisions ) nSubDivisions = 100; + if ( ! nSubDivisions ) nSubDivisions = 100; nSamples = this.points.length * nSubDivisions; @@ -6624,7 +6597,7 @@ THREE.Spline = function ( points ) { newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); - for ( i = 1; i < this.points.length; i++ ) { + for ( i = 1; i < this.points.length; i ++ ) { //tmpVec.copy( this.points[ i - 1 ] ); //linearDistance = tmpVec.distanceTo( this.points[ i ] ); @@ -6636,7 +6609,7 @@ THREE.Spline = function ( points ) { indexCurrent = ( i - 1 ) / ( this.points.length - 1 ); indexNext = i / ( this.points.length - 1 ); - for ( j = 1; j < sampling - 1; j++ ) { + for ( j = 1; j < sampling - 1; j ++ ) { index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent ); @@ -6666,6 +6639,8 @@ THREE.Spline = function ( points ) { }; +// File:src/math/Triangle.js + /** * @author bhouston / http://exocortex.com * @author mrdoob / http://mrdoob.com/ @@ -6679,7 +6654,7 @@ THREE.Triangle = function ( a, b, c ) { }; -THREE.Triangle.normal = function() { +THREE.Triangle.normal = function () { var v0 = new THREE.Vector3(); @@ -6692,7 +6667,7 @@ THREE.Triangle.normal = function() { result.cross( v0 ); var resultLengthSq = result.lengthSq(); - if( resultLengthSq > 0 ) { + if ( resultLengthSq > 0 ) { return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); @@ -6706,7 +6681,7 @@ THREE.Triangle.normal = function() { // static/instance method to calculate barycoordinates // based on: http://www.blackpawn.com/texts/pointinpoly/default.html -THREE.Triangle.barycoordFromPoint = function() { +THREE.Triangle.barycoordFromPoint = function () { var v0 = new THREE.Vector3(); var v1 = new THREE.Vector3(); @@ -6729,10 +6704,10 @@ THREE.Triangle.barycoordFromPoint = function() { var result = optionalTarget || new THREE.Vector3(); // colinear or singular triangle - if( denom == 0 ) { + if ( denom == 0 ) { // arbitrary location outside of triangle? // not sure if this is the best idea, maybe should be returning undefined - return result.set( -2, -1, -1 ); + return result.set( - 2, - 1, - 1 ); } var invDenom = 1 / denom; @@ -6746,7 +6721,7 @@ THREE.Triangle.barycoordFromPoint = function() { }(); -THREE.Triangle.containsPoint = function() { +THREE.Triangle.containsPoint = function () { var v1 = new THREE.Vector3(); @@ -6776,9 +6751,9 @@ THREE.Triangle.prototype = { setFromPointsAndIndices: function ( points, i0, i1, i2 ) { - this.a.copy( points[i0] ); - this.b.copy( points[i1] ); - this.c.copy( points[i2] ); + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); return this; @@ -6794,7 +6769,7 @@ THREE.Triangle.prototype = { }, - area: function() { + area: function () { var v0 = new THREE.Vector3(); var v1 = new THREE.Vector3(); @@ -6857,16 +6832,7 @@ THREE.Triangle.prototype = { }; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Vertex = function ( v ) { - - console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.') - return v; - -}; +// File:src/core/Clock.js /** * @author alteredq / http://alteredqualia.com/ @@ -6891,8 +6857,8 @@ THREE.Clock.prototype = { start: function () { this.startTime = self.performance !== undefined && self.performance.now !== undefined - ? self.performance.now() - : Date.now(); + ? self.performance.now() + : Date.now(); this.oldTime = this.startTime; this.running = true; @@ -6925,8 +6891,8 @@ THREE.Clock.prototype = { if ( this.running ) { var newTime = self.performance !== undefined && self.performance.now !== undefined - ? self.performance.now() - : Date.now(); + ? self.performance.now() + : Date.now(); diff = 0.001 * ( newTime - this.oldTime ); this.oldTime = newTime; @@ -6941,6 +6907,8 @@ THREE.Clock.prototype = { }; +// File:src/core/EventDispatcher.js + /** * https://github.com/mrdoob/eventdispatcher.js/ */ @@ -7018,7 +6986,7 @@ THREE.EventDispatcher.prototype = { }, dispatchEvent: function ( event ) { - + if ( this._listeners === undefined ) return; var listeners = this._listeners; @@ -7049,6 +7017,8 @@ THREE.EventDispatcher.prototype = { }; +// File:src/core/Raycaster.js + /** * @author mrdoob / http://mrdoob.com/ * @author bhouston / http://exocortex.com/ @@ -7065,15 +7035,15 @@ THREE.EventDispatcher.prototype = { this.near = near || 0; this.far = far || Infinity; - }; - - var sphere = new THREE.Sphere(); - var localRay = new THREE.Ray(); - var facePlane = new THREE.Plane(); - var intersectPoint = new THREE.Vector3(); - var matrixPosition = new THREE.Vector3(); + this.params = { + Sprite: {}, + Mesh: {}, + PointCloud: { threshold: 1 }, + LOD: {}, + Line: {} + }; - var inverseMatrix = new THREE.Matrix4(); + }; var descSort = function ( a, b ) { @@ -7081,481 +7051,125 @@ THREE.EventDispatcher.prototype = { }; - var vA = new THREE.Vector3(); - var vB = new THREE.Vector3(); - var vC = new THREE.Vector3(); + var intersectObject = function ( object, raycaster, intersects, recursive ) { - var intersectObject = function ( object, raycaster, intersects ) { + object.raycast( raycaster, intersects ); - if ( object instanceof THREE.Sprite ) { + if ( recursive === true ) { - matrixPosition.setFromMatrixPosition( object.matrixWorld ); - - var distance = raycaster.ray.distanceToPoint( matrixPosition ); + var children = object.children; - if ( distance > object.scale.x ) { + for ( var i = 0, l = children.length; i < l; i ++ ) { - return intersects; + intersectObject( children[ i ], raycaster, intersects, true ); } - intersects.push( { + } - distance: distance, - point: object.position, - face: null, - object: object + }; - } ); + // + + THREE.Raycaster.prototype = { - } else if ( object instanceof THREE.LOD ) { + constructor: THREE.Raycaster, - matrixPosition.setFromMatrixPosition( object.matrixWorld ); - var distance = raycaster.ray.origin.distanceTo( matrixPosition ); + precision: 0.0001, + linePrecision: 1, - intersectObject( object.getObjectForDistance( distance ), raycaster, intersects ); + set: function ( origin, direction ) { - } else if ( object instanceof THREE.Mesh ) { + this.ray.set( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) - var geometry = object.geometry; + }, - // Checking boundingSphere distance to ray + intersectObject: function ( object, recursive ) { - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + var intersects = []; - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( object.matrixWorld ); + intersectObject( object, this, intersects, recursive ); - if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { + intersects.sort( descSort ); - return intersects; + return intersects; - } + }, - // Check boundingBox before continuing - - inverseMatrix.getInverse( object.matrixWorld ); - localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + intersectObjects: function ( objects, recursive ) { - if ( geometry.boundingBox !== null ) { + var intersects = []; - if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) { + for ( var i = 0, l = objects.length; i < l; i ++ ) { - return intersects; + intersectObject( objects[ i ], this, intersects, recursive ); - } + } - } + intersects.sort( descSort ); - if ( geometry instanceof THREE.BufferGeometry ) { + return intersects; - var material = object.material; + } - if ( material === undefined ) return intersects; + }; - var attributes = geometry.attributes; +}( THREE ) ); - var a, b, c; - var precision = raycaster.precision; +// File:src/core/Object3D.js - if ( attributes.index !== undefined ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + */ - var indices = attributes.index.array; - var positions = attributes.position.array; - var offsets = geometry.offsets; +THREE.Object3D = function () { - if ( offsets.length === 0 ) { + this.id = THREE.Object3DIdCount ++; + this.uuid = THREE.Math.generateUUID(); - offsets = [ { start: 0, count: positions.length, index: 0 } ]; + this.name = ''; - } + this.parent = undefined; + this.children = []; - for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) { - - var start = offsets[ oi ].start; - var count = offsets[ oi ].count; - var index = offsets[ oi ].index; - - for ( var i = start, il = start + count; i < il; i += 3 ) { - - a = index + indices[ i ]; - b = index + indices[ i + 1 ]; - c = index + indices[ i + 2 ]; - - vA.set( - positions[ a * 3 ], - positions[ a * 3 + 1 ], - positions[ a * 3 + 2 ] - ); - vB.set( - positions[ b * 3 ], - positions[ b * 3 + 1 ], - positions[ b * 3 + 2 ] - ); - vC.set( - positions[ c * 3 ], - positions[ c * 3 + 1 ], - positions[ c * 3 + 2 ] - ); + this.up = THREE.Object3D.DefaultUp.clone(); - - if ( material.side === THREE.BackSide ) { - - var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true ); + var scope = this; - } else { + var position = new THREE.Vector3(); + var rotation = new THREE.Euler(); + var quaternion = new THREE.Quaternion(); + var scale = new THREE.Vector3( 1, 1, 1 ); - var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); + rotation.onChange( function () { + quaternion.setFromEuler( rotation, false ); + } ); - } - - if ( intersectionPoint === null ) continue; - - intersectionPoint.applyMatrix4( object.matrixWorld ); - - var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - - if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - - intersects.push( { - - distance: distance, - point: intersectionPoint, - indices: [a, b, c], - face: null, - faceIndex: null, - object: object - - } ); - - } - - } - - } else { - - var offsets = geometry.offsets; - var positions = attributes.position.array; - - for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) { - - a = i; - b = i + 1; - c = i + 2; - - vA.set( - positions[ a * 3 ], - positions[ a * 3 + 1 ], - positions[ a * 3 + 2 ] - ); - vB.set( - positions[ b * 3 ], - positions[ b * 3 + 1 ], - positions[ b * 3 + 2 ] - ); - vC.set( - positions[ c * 3 ], - positions[ c * 3 + 1 ], - positions[ c * 3 + 2 ] - ); - - - if ( material.side === THREE.BackSide ) { - - var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true ); - - } else { - - var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); - - } - - if ( intersectionPoint === null ) continue; - - intersectionPoint.applyMatrix4( object.matrixWorld ); - - var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - - if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - - intersects.push( { - - distance: distance, - point: intersectionPoint, - indices: [a, b, c], - face: null, - faceIndex: null, - object: object - - } ); - - } - - } - - } else if ( geometry instanceof THREE.Geometry ) { - - var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial; - var objectMaterials = isFaceMaterial === true ? object.material.materials : null; - - var a, b, c, d; - var precision = raycaster.precision; - - var vertices = geometry.vertices; - - for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { - - var face = geometry.faces[ f ]; - - var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material; - - if ( material === undefined ) continue; - - a = vertices[ face.a ]; - b = vertices[ face.b ]; - c = vertices[ face.c ]; - - if ( material.morphTargets === true ) { - - var morphTargets = geometry.morphTargets; - var morphInfluences = object.morphTargetInfluences; - - vA.set( 0, 0, 0 ); - vB.set( 0, 0, 0 ); - vC.set( 0, 0, 0 ); - - for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { - - var influence = morphInfluences[ t ]; - - if ( influence === 0 ) continue; - - var targets = morphTargets[ t ].vertices; - - vA.x += ( targets[ face.a ].x - a.x ) * influence; - vA.y += ( targets[ face.a ].y - a.y ) * influence; - vA.z += ( targets[ face.a ].z - a.z ) * influence; - - vB.x += ( targets[ face.b ].x - b.x ) * influence; - vB.y += ( targets[ face.b ].y - b.y ) * influence; - vB.z += ( targets[ face.b ].z - b.z ) * influence; - - vC.x += ( targets[ face.c ].x - c.x ) * influence; - vC.y += ( targets[ face.c ].y - c.y ) * influence; - vC.z += ( targets[ face.c ].z - c.z ) * influence; - - } - - vA.add( a ); - vB.add( b ); - vC.add( c ); - - a = vA; - b = vB; - c = vC; - - } - - if ( material.side === THREE.BackSide ) { - - var intersectionPoint = localRay.intersectTriangle( c, b, a, true ); - - } else { - - var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide ); - - } - - if ( intersectionPoint === null ) continue; - - intersectionPoint.applyMatrix4( object.matrixWorld ); - - var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - - if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - - intersects.push( { - - distance: distance, - point: intersectionPoint, - face: face, - faceIndex: f, - object: object - - } ); - - } - - } - - } else if ( object instanceof THREE.Line ) { - - var precision = raycaster.linePrecision; - var precisionSq = precision * precision; - - var geometry = object.geometry; - - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - - // Checking boundingSphere distance to ray - - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( object.matrixWorld ); - - if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { - - return intersects; - - } - - inverseMatrix.getInverse( object.matrixWorld ); - localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - - /* if ( geometry instanceof THREE.BufferGeometry ) { - - } else */ if ( geometry instanceof THREE.Geometry ) { - - var vertices = geometry.vertices; - var nbVertices = vertices.length; - var interSegment = new THREE.Vector3(); - var interRay = new THREE.Vector3(); - var step = object.type === THREE.LineStrip ? 1 : 2; - - for ( var i = 0; i < nbVertices - 1; i = i + step ) { - - var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); - - if ( distSq > precisionSq ) continue; - - var distance = localRay.origin.distanceTo( interRay ); - - if ( distance < raycaster.near || distance > raycaster.far ) continue; - - intersects.push( { - - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( object.matrixWorld ), - face: null, - faceIndex: null, - object: object - - } ); - - } - - } - - } - - }; - - var intersectDescendants = function ( object, raycaster, intersects ) { - - var descendants = object.getDescendants(); - - for ( var i = 0, l = descendants.length; i < l; i ++ ) { - - intersectObject( descendants[ i ], raycaster, intersects ); - - } - }; - - // - - THREE.Raycaster.prototype.precision = 0.0001; - THREE.Raycaster.prototype.linePrecision = 1; - - THREE.Raycaster.prototype.set = function ( origin, direction ) { - - this.ray.set( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) - - }; - - THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) { - - var intersects = []; - - if ( recursive === true ) { - - intersectDescendants( object, this, intersects ); - - } - - intersectObject( object, this, intersects ); - - intersects.sort( descSort ); - - return intersects; - - }; - - THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) { - - var intersects = []; - - for ( var i = 0, l = objects.length; i < l; i ++ ) { - - intersectObject( objects[ i ], this, intersects ); - - if ( recursive === true ) { - - intersectDescendants( objects[ i ], this, intersects ); - - } - - } - - intersects.sort( descSort ); - - return intersects; - - }; - -}( THREE ) ); - -/** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - */ - -THREE.Object3D = function () { - - this.id = THREE.Object3DIdCount ++; - this.uuid = THREE.Math.generateUUID(); - - this.name = ''; - - this.parent = undefined; - this.children = []; - - this.up = new THREE.Vector3( 0, 1, 0 ); - - this.position = new THREE.Vector3(); - - var scope = this; + quaternion.onChange( function () { + rotation.setFromQuaternion( quaternion, undefined, false ); + } ); Object.defineProperties( this, { + position: { + enumerable: true, + value: position + }, rotation: { enumerable: true, - value: new THREE.Euler().onChange( function () { - scope.quaternion.setFromEuler( scope.rotation, false ); - } ) + value: rotation }, quaternion: { enumerable: true, - value: new THREE.Quaternion().onChange( function () { - scope.rotation.setFromQuaternion( scope.quaternion, undefined, false ); - } ) + value: quaternion }, scale: { enumerable: true, - value: new THREE.Vector3( 1, 1, 1 ) - } + value: scale + }, } ); this.renderDepth = null; @@ -7579,6 +7193,7 @@ THREE.Object3D = function () { }; +THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 ); THREE.Object3D.prototype = { @@ -7586,7 +7201,7 @@ THREE.Object3D.prototype = { get eulerOrder () { - console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' ); + console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' ); return this.rotation.order; @@ -7594,7 +7209,7 @@ THREE.Object3D.prototype = { set eulerOrder ( value ) { - console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' ); + console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' ); this.rotation.order = value; @@ -7602,13 +7217,13 @@ THREE.Object3D.prototype = { get useQuaternion () { - console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' ); + console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); }, set useQuaternion ( value ) { - console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' ); + console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); }, @@ -7650,7 +7265,7 @@ THREE.Object3D.prototype = { }, - rotateOnAxis: function() { + rotateOnAxis: function () { // rotate object on axis in object space // axis is assumed to be normalized @@ -7714,9 +7329,7 @@ THREE.Object3D.prototype = { return function ( axis, distance ) { - v1.copy( axis ); - - v1.applyQuaternion( this.quaternion ); + v1.copy( axis ).applyQuaternion( this.quaternion ); this.position.add( v1.multiplyScalar( distance ) ); @@ -7728,7 +7341,7 @@ THREE.Object3D.prototype = { translate: function ( distance, axis ) { - console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' ); + console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); return this.translateOnAxis( axis, distance ); }, @@ -7805,10 +7418,22 @@ THREE.Object3D.prototype = { add: function ( object ) { + if ( arguments.length > 1 ) { + + for ( var i = 0; i < arguments.length; i++ ) { + + this.add( arguments[ i ] ); + + } + + return this; + + }; + if ( object === this ) { - console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' ); - return; + console.error( "THREE.Object3D.add:", object, "can't be added as a child of itself." ); + return this; } @@ -7841,12 +7466,28 @@ THREE.Object3D.prototype = { } + } else { + + console.error( "THREE.Object3D.add:", object, "is not an instance of THREE.Object3D." ); + } + return this; + }, remove: function ( object ) { + if ( arguments.length > 1 ) { + + for ( var i = 0; i < arguments.length; i++ ) { + + this.remove( arguments[ i ] ); + + } + + }; + var index = this.children.indexOf( object ); if ( index !== - 1 ) { @@ -7876,6 +7517,8 @@ THREE.Object3D.prototype = { }, + raycast: function () {}, + traverse: function ( callback ) { callback( this ); @@ -7888,13 +7531,27 @@ THREE.Object3D.prototype = { }, - getObjectById: function ( id, recursive ) { + traverseVisible: function ( callback ) { - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + if ( this.visible === false ) return; - var child = this.children[ i ]; + callback( this ); - if ( child.id === id ) { + for ( var i = 0, l = this.children.length; i < l; i ++ ) { + + this.children[ i ].traverseVisible( callback ); + + } + + }, + + getObjectById: function ( id, recursive ) { + + for ( var i = 0, l = this.children.length; i < l; i ++ ) { + + var child = this.children[ i ]; + + if ( child.id === id ) { return child; @@ -7950,27 +7607,11 @@ THREE.Object3D.prototype = { getChildByName: function ( name, recursive ) { - console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' ); + console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); return this.getObjectByName( name, recursive ); }, - getDescendants: function ( array ) { - - if ( array === undefined ) array = []; - - Array.prototype.push.apply( array, this.children ); - - for ( var i = 0, l = this.children.length; i < l; i ++ ) { - - this.children[ i ].getDescendants( array ); - - } - - return array; - - }, - updateMatrix: function () { this.matrix.compose( this.position, this.quaternion, this.scale ); @@ -8064,6 +7705,8 @@ THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype ); THREE.Object3DIdCount = 0; +// File:src/core/Projector.js + /** * @author mrdoob / http://mrdoob.com/ * @author supereggbert / http://www.paulbrunt.co.uk/ @@ -8087,7 +7730,7 @@ THREE.Projector = function () { _vector3 = new THREE.Vector3(), _vector4 = new THREE.Vector4(), - _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ), + _clipBox = new THREE.Box3( new THREE.Vector3( - 1, - 1, - 1 ), new THREE.Vector3( 1, 1, 1 ) ), _boundingBox = new THREE.Box3(), _points3 = new Array( 3 ), _points4 = new Array( 4 ), @@ -8133,7 +7776,7 @@ THREE.Projector = function () { this.pickingRay = function ( vector, camera ) { // set two vectors with opposing z values - vector.z = -1.0; + vector.z = - 1.0; var end = new THREE.Vector3( vector.x, vector.y, 1.0 ); this.unprojectVector( vector, camera ); @@ -8146,65 +7789,6 @@ THREE.Projector = function () { }; - var projectObject = function ( object ) { - - if ( object.visible === false ) return; - - if ( object instanceof THREE.Light ) { - - _renderData.lights.push( object ); - - } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) { - - if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) { - - _object = getNextObjectInPool(); - _object.id = object.id; - _object.object = object; - - if ( object.renderDepth !== null ) { - - _object.z = object.renderDepth; - - } else { - - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _viewProjectionMatrix ); - _object.z = _vector3.z; - - } - - _renderData.objects.push( _object ); - - } - - } - - for ( var i = 0, l = object.children.length; i < l; i ++ ) { - - projectObject( object.children[ i ] ); - - } - - }; - - var projectGraph = function ( root, sortObjects ) { - - _objectCount = 0; - - _renderData.objects.length = 0; - _renderData.lights.length = 0; - - projectObject( root ); - - if ( sortObjects === true ) { - - _renderData.objects.sort( painterSort ); - - } - - }; - var RenderList = function () { var normals = []; @@ -8242,9 +7826,9 @@ THREE.Projector = function () { positionScreen.y *= invW; positionScreen.z *= invW; - vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 && - positionScreen.y >= -1 && positionScreen.y <= 1 && - positionScreen.z >= -1 && positionScreen.z <= 1; + vertex.visible = positionScreen.x >= - 1 && positionScreen.x <= 1 && + positionScreen.y >= - 1 && positionScreen.y <= 1 && + positionScreen.z >= - 1 && positionScreen.z <= 1; }; @@ -8369,9 +7953,6 @@ THREE.Projector = function () { this.projectScene = function ( scene, camera, sortObjects, sortElements ) { - var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, - isFaceMaterial, objectMaterials; - _faceCount = 0; _lineCount = 0; _spriteCount = 0; @@ -8386,12 +7967,59 @@ THREE.Projector = function () { _frustum.setFromMatrix( _viewProjectionMatrix ); - projectGraph( scene, sortObjects ); + // + + _objectCount = 0; + + _renderData.objects.length = 0; + _renderData.lights.length = 0; + + scene.traverseVisible( function ( object ) { + + if ( object instanceof THREE.Light ) { + + _renderData.lights.push( object ); + + } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) { + + if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) { + + _object = getNextObjectInPool(); + _object.id = object.id; + _object.object = object; + + if ( object.renderDepth !== null ) { + + _object.z = object.renderDepth; + + } else { + + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyProjection( _viewProjectionMatrix ); + _object.z = _vector3.z; + + } + + _renderData.objects.push( _object ); + + } + + } + + } ); + + if ( sortObjects === true ) { + + _renderData.objects.sort( painterSort ); + + } + + // for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) { - object = _renderData.objects[ o ].object; - geometry = object.geometry; + var object = _renderData.objects[ o ].object; + var geometry = object.geometry; renderList.setObject( object ); @@ -8481,14 +8109,14 @@ THREE.Projector = function () { } else if ( geometry instanceof THREE.Geometry ) { - vertices = geometry.vertices; - faces = geometry.faces; - faceVertexUvs = geometry.faceVertexUvs[ 0 ]; + var vertices = geometry.vertices; + var faces = geometry.faces; + var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; _normalMatrix.getNormalMatrix( _modelMatrix ); - isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial; - objectMaterials = isFaceMaterial === true ? object.material : null; + var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial; + var objectMaterials = isFaceMaterial === true ? object.material : null; for ( var v = 0, vl = vertices.length; v < vl; v ++ ) { @@ -8499,11 +8127,11 @@ THREE.Projector = function () { for ( var f = 0, fl = faces.length; f < fl; f ++ ) { - face = faces[ f ]; + var face = faces[ f ]; var material = isFaceMaterial === true - ? objectMaterials.materials[ face.materialIndex ] - : object.material; + ? objectMaterials.materials[ face.materialIndex ] + : object.material; if ( material === undefined ) continue; @@ -8584,7 +8212,7 @@ THREE.Projector = function () { _face.normalModel.applyMatrix3( _normalMatrix ).normalize(); - faceVertexNormals = face.vertexNormals; + var faceVertexNormals = face.vertexNormals; for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) { @@ -8654,7 +8282,9 @@ THREE.Projector = function () { } else { - for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) { + var step = object.type === THREE.LinePieces ? 2 : 1; + + for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i += step ) { renderList.pushLine( i, i + 1 ); @@ -8668,7 +8298,7 @@ THREE.Projector = function () { _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix ); - vertices = object.geometry.vertices; + var vertices = object.geometry.vertices; if ( vertices.length === 0 ) continue; @@ -8723,14 +8353,14 @@ THREE.Projector = function () { } else if ( object instanceof THREE.Sprite ) { - _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 ); + _vector4.set( _modelMatrix.elements[ 12 ], _modelMatrix.elements[ 13 ], _modelMatrix.elements[ 14 ], 1 ); _vector4.applyMatrix4( _viewProjectionMatrix ); var invW = 1 / _vector4.w; _vector4.z *= invW; - if ( _vector4.z >= -1 && _vector4.z <= 1 ) { + if ( _vector4.z >= - 1 && _vector4.z <= 1 ) { _sprite = getNextSpriteInPool(); _sprite.id = object.id; @@ -8741,8 +8371,8 @@ THREE.Projector = function () { _sprite.rotation = object.rotation; - _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) ); - _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) ); + _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[ 0 ] ) / ( _vector4.w + camera.projectionMatrix.elements[ 12 ] ) ); + _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[ 5 ] ) / ( _vector4.w + camera.projectionMatrix.elements[ 13 ] ) ); _sprite.material = object.material; @@ -8879,7 +8509,7 @@ THREE.Projector = function () { // Both vertices lie entirely within all clip planes. return true; - } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) { + } else if ( ( bc1near < 0 && bc2near < 0 ) || ( bc1far < 0 && bc2far < 0 ) ) { // Both vertices lie entirely outside one of the clip planes. return false; @@ -8935,6 +8565,8 @@ THREE.Projector = function () { }; +// File:src/core/Face3.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -8947,7 +8579,7 @@ THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) { this.c = c; this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3(); - this.vertexNormals = normal instanceof Array ? normal : [ ]; + this.vertexNormals = normal instanceof Array ? normal : []; this.color = color instanceof THREE.Color ? color : new THREE.Color(); this.vertexColors = color instanceof Array ? color : []; @@ -8971,10 +8603,23 @@ THREE.Face3.prototype = { face.materialIndex = this.materialIndex; - var i, il; - for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone(); - for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone(); - for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone(); + for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) { + + face.vertexNormals[ i ] = this.vertexNormals[ i ].clone(); + + } + + for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) { + + face.vertexColors[ i ] = this.vertexColors[ i ].clone(); + + } + + for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) { + + face.vertexTangents[ i ] = this.vertexTangents[ i ].clone(); + + } return face; @@ -8982,23 +8627,31 @@ THREE.Face3.prototype = { }; +// File:src/core/Face4.js + /** * @author mrdoob / http://mrdoob.com/ */ THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) { - console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.') - + console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ) return new THREE.Face3( a, b, c, normal, color, materialIndex ); }; +// File:src/core/BufferAttribute.js + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.BufferAttribute = function () {}; +THREE.BufferAttribute = function ( array, itemSize ) { + + this.array = array; + this.itemSize = itemSize; + +}; THREE.BufferAttribute.prototype = { @@ -9014,24 +8667,32 @@ THREE.BufferAttribute.prototype = { this.array.set( value ); + return this; + }, setX: function ( index, x ) { this.array[ index * this.itemSize ] = x; + return this; + }, setY: function ( index, y ) { this.array[ index * this.itemSize + 1 ] = y; + return this; + }, setZ: function ( index, z ) { this.array[ index * this.itemSize + 2 ] = z; + return this; + }, setXY: function ( index, x, y ) { @@ -9041,6 +8702,8 @@ THREE.BufferAttribute.prototype = { this.array[ index ] = x; this.array[ index + 1 ] = y; + return this; + }, setXYZ: function ( index, x, y, z ) { @@ -9051,6 +8714,8 @@ THREE.BufferAttribute.prototype = { this.array[ index + 1 ] = y; this.array[ index + 2 ] = z; + return this; + }, setXYZW: function ( index, x, y, z, w ) { @@ -9062,92 +8727,80 @@ THREE.BufferAttribute.prototype = { this.array[ index + 2 ] = z; this.array[ index + 3 ] = w; + return this; + } }; // -THREE.Int8Attribute = function ( size, itemSize ) { +THREE.Int8Attribute = function ( data, itemSize ) { - this.array = new Int8Array( size * itemSize ); - this.itemSize = itemSize; + console.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); }; -THREE.Int8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype ); +THREE.Uint8Attribute = function ( data, itemSize ) { -THREE.Uint8Attribute = function ( size, itemSize ) { - - this.array = new Uint8Array( size * itemSize ); - this.itemSize = itemSize; + console.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); }; -THREE.Uint8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype ); +THREE.Uint8ClampedAttribute = function ( data, itemSize ) { -THREE.Uint8ClampedAttribute = function ( size, itemSize ) { + console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); - this.array = new Uint8ClampedArray( size * itemSize ); - this.itemSize = itemSize; }; -THREE.Uint8ClampedAttribute.prototype = Object.create( THREE.BufferAttribute.prototype ); - -THREE.Int16Attribute = function ( size, itemSize ) { +THREE.Int16Attribute = function ( data, itemSize ) { - this.array = new Int16Array( size * itemSize ); - this.itemSize = itemSize; + console.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); }; -THREE.Int16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype ); - -THREE.Uint16Attribute = function ( size, itemSize ) { +THREE.Uint16Attribute = function ( data, itemSize ) { - this.array = new Uint16Array( size * itemSize ); - this.itemSize = itemSize; + console.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); }; -THREE.Uint16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype ); - -THREE.Int32Attribute = function ( size, itemSize ) { +THREE.Int32Attribute = function ( data, itemSize ) { - this.array = new Int32Array( size * itemSize ); - this.itemSize = itemSize; + console.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); }; -THREE.Int32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype ); - -THREE.Uint32Attribute = function ( size, itemSize ) { +THREE.Uint32Attribute = function ( data, itemSize ) { - this.array = new Uint32Array( size * itemSize ); - this.itemSize = itemSize; + console.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); }; -THREE.Uint32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype ); - -THREE.Float32Attribute = function ( size, itemSize ) { +THREE.Float32Attribute = function ( data, itemSize ) { - this.array = new Float32Array( size * itemSize ); - this.itemSize = itemSize; + console.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); }; -THREE.Float32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype ); - -THREE.Float64Attribute = function ( size, itemSize ) { +THREE.Float64Attribute = function ( data, itemSize ) { - this.array = new Float64Array( size * itemSize ); - this.itemSize = itemSize; + console.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); }; -THREE.Float64Attribute.prototype = Object.create( THREE.BufferAttribute.prototype ); +// File:src/core/BufferGeometry.js + /** * @author alteredq / http://alteredqualia.com/ */ @@ -9176,7 +8829,7 @@ THREE.BufferGeometry.prototype = { if ( attribute instanceof THREE.BufferAttribute === false ) { - console.warn( 'DEPRECATED: BufferGeometry\'s addAttribute() now expects ( name, attribute ).' ); + console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] }; @@ -9230,6 +8883,154 @@ THREE.BufferGeometry.prototype = { }, + fromGeometry: function ( geometry, settings ) { + + settings = settings || { 'vertexColors': THREE.NoColors }; + + var vertices = geometry.vertices; + var faces = geometry.faces; + var faceVertexUvs = geometry.faceVertexUvs; + var vertexColors = settings.vertexColors; + var hasFaceVertexUv = faceVertexUvs[ 0 ].length > 0; + var hasFaceVertexNormals = faces[ 0 ].vertexNormals.length == 3; + + var positions = new Float32Array( faces.length * 3 * 3 ); + this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + + var normals = new Float32Array( faces.length * 3 * 3 ); + this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); + + if ( vertexColors !== THREE.NoColors ) { + + var colors = new Float32Array( faces.length * 3 * 3 ); + this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); + + } + + if ( hasFaceVertexUv === true ) { + + var uvs = new Float32Array( faces.length * 3 * 2 ); + this.addAttribute( 'uvs', new THREE.BufferAttribute( uvs, 2 ) ); + + } + + for ( var i = 0, i2 = 0, i3 = 0; i < faces.length; i ++, i2 += 6, i3 += 9 ) { + + var face = faces[ i ]; + + var a = vertices[ face.a ]; + var b = vertices[ face.b ]; + var c = vertices[ face.c ]; + + positions[ i3 ] = a.x; + positions[ i3 + 1 ] = a.y; + positions[ i3 + 2 ] = a.z; + + positions[ i3 + 3 ] = b.x; + positions[ i3 + 4 ] = b.y; + positions[ i3 + 5 ] = b.z; + + positions[ i3 + 6 ] = c.x; + positions[ i3 + 7 ] = c.y; + positions[ i3 + 8 ] = c.z; + + if ( hasFaceVertexNormals === true ) { + + var na = face.vertexNormals[ 0 ]; + var nb = face.vertexNormals[ 1 ]; + var nc = face.vertexNormals[ 2 ]; + + normals[ i3 ] = na.x; + normals[ i3 + 1 ] = na.y; + normals[ i3 + 2 ] = na.z; + + normals[ i3 + 3 ] = nb.x; + normals[ i3 + 4 ] = nb.y; + normals[ i3 + 5 ] = nb.z; + + normals[ i3 + 6 ] = nc.x; + normals[ i3 + 7 ] = nc.y; + normals[ i3 + 8 ] = nc.z; + + } else { + + var n = face.normal; + + normals[ i3 ] = n.x; + normals[ i3 + 1 ] = n.y; + normals[ i3 + 2 ] = n.z; + + normals[ i3 + 3 ] = n.x; + normals[ i3 + 4 ] = n.y; + normals[ i3 + 5 ] = n.z; + + normals[ i3 + 6 ] = n.x; + normals[ i3 + 7 ] = n.y; + normals[ i3 + 8 ] = n.z; + + } + + if ( vertexColors === THREE.FaceColors ) { + + var fc = face.color; + + colors[ i3 ] = fc.r; + colors[ i3 + 1 ] = fc.g; + colors[ i3 + 2 ] = fc.b; + + colors[ i3 + 3 ] = fc.r; + colors[ i3 + 4 ] = fc.g; + colors[ i3 + 5 ] = fc.b; + + colors[ i3 + 6 ] = fc.r; + colors[ i3 + 7 ] = fc.g; + colors[ i3 + 8 ] = fc.b; + + } else if ( vertexColors === THREE.VertexColors ) { + + var vca = face.vertexColors[ 0 ]; + var vcb = face.vertexColors[ 1 ]; + var vcc = face.vertexColors[ 2 ]; + + colors[ i3 ] = vca.r; + colors[ i3 + 1 ] = vca.g; + colors[ i3 + 2 ] = vca.b; + + colors[ i3 + 3 ] = vcb.r; + colors[ i3 + 4 ] = vcb.g; + colors[ i3 + 5 ] = vcb.b; + + colors[ i3 + 6 ] = vcc.r; + colors[ i3 + 7 ] = vcc.g; + colors[ i3 + 8 ] = vcc.b; + + } + + if ( hasFaceVertexUv === true ) { + + var uva = faceVertexUvs[ 0 ][ i ][ 0 ]; + var uvb = faceVertexUvs[ 0 ][ i ][ 1 ]; + var uvc = faceVertexUvs[ 0 ][ i ][ 2 ]; + + uvs[ i2 ] = uva.x; + uvs[ i2 + 1 ] = uva.y; + + uvs[ i2 + 2 ] = uvb.x; + uvs[ i2 + 3 ] = uvb.y; + + uvs[ i2 + 4 ] = uvc.x; + uvs[ i2 + 5 ] = uvc.y; + + } + + } + + this.computeBoundingSphere() + + return this; + + }, + computeBoundingBox: function () { if ( this.boundingBox === null ) { @@ -9238,13 +9039,13 @@ THREE.BufferGeometry.prototype = { } - var positions = this.attributes[ "position" ].array; + var positions = this.attributes[ 'position' ].array; if ( positions ) { var bb = this.boundingBox; - if( positions.length >= 3 ) { + if ( positions.length >= 3 ) { bb.min.x = bb.max.x = positions[ 0 ]; bb.min.y = bb.max.y = positions[ 1 ]; bb.min.z = bb.max.z = positions[ 2 ]; @@ -9299,6 +9100,12 @@ THREE.BufferGeometry.prototype = { } + if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { + + console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.' ); + + } + }, computeBoundingSphere: function () { @@ -9314,7 +9121,7 @@ THREE.BufferGeometry.prototype = { } - var positions = this.attributes[ "position" ].array; + var positions = this.attributes[ 'position' ].array; if ( positions ) { @@ -9325,7 +9132,7 @@ THREE.BufferGeometry.prototype = { for ( var i = 0, il = positions.length; i < il; i += 3 ) { vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); - box.addPoint( vector ); + box.expandByPoint( vector ); } @@ -9345,6 +9152,12 @@ THREE.BufferGeometry.prototype = { this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + if ( isNaN( this.boundingSphere.radius ) ) { + + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.' ); + + } + } } @@ -9359,16 +9172,16 @@ THREE.BufferGeometry.prototype = { computeVertexNormals: function () { - if ( this.attributes[ "position" ] ) { + if ( this.attributes[ 'position' ] ) { var i, il; var j, jl; - var nVertexElements = this.attributes[ "position" ].array.length; + var nVertexElements = this.attributes[ 'position' ].array.length; - if ( this.attributes[ "normal" ] === undefined ) { + if ( this.attributes[ 'normal' ] === undefined ) { - this.attributes[ "normal" ] = { + this.attributes[ 'normal' ] = { itemSize: 3, array: new Float32Array( nVertexElements ) @@ -9379,16 +9192,16 @@ THREE.BufferGeometry.prototype = { // reset existing normals to zero - for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) { + for ( i = 0, il = this.attributes[ 'normal' ].array.length; i < il; i ++ ) { - this.attributes[ "normal" ].array[ i ] = 0; + this.attributes[ 'normal' ].array[ i ] = 0; } } - var positions = this.attributes[ "position" ].array; - var normals = this.attributes[ "normal" ].array; + var positions = this.attributes[ 'position' ].array; + var normals = this.attributes[ 'normal' ].array; var vA, vB, vC, x, y, z, @@ -9401,11 +9214,11 @@ THREE.BufferGeometry.prototype = { // indexed elements - if ( this.attributes[ "index" ] ) { + if ( this.attributes[ 'index' ] ) { - var indices = this.attributes[ "index" ].array; + var indices = this.attributes[ 'index' ].array; - var offsets = (this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ]); + var offsets = ( this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ] ); for ( j = 0, jl = offsets.length; j < jl; ++ j ) { @@ -9508,28 +9321,28 @@ THREE.BufferGeometry.prototype = { // based on http://www.terathon.com/code/tangent.html // (per vertex tangents) - if ( this.attributes[ "index" ] === undefined || - this.attributes[ "position" ] === undefined || - this.attributes[ "normal" ] === undefined || - this.attributes[ "uv" ] === undefined ) { + if ( this.attributes[ 'index' ] === undefined || + this.attributes[ 'position' ] === undefined || + this.attributes[ 'normal' ] === undefined || + this.attributes[ 'uv' ] === undefined ) { - console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" ); + console.warn( 'Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' ); return; } - var indices = this.attributes[ "index" ].array; - var positions = this.attributes[ "position" ].array; - var normals = this.attributes[ "normal" ].array; - var uvs = this.attributes[ "uv" ].array; + var indices = this.attributes[ 'index' ].array; + var positions = this.attributes[ 'position' ].array; + var normals = this.attributes[ 'normal' ].array; + var uvs = this.attributes[ 'uv' ].array; var nVertices = positions.length / 3; - if ( this.attributes[ "tangent" ] === undefined ) { + if ( this.attributes[ 'tangent' ] === undefined ) { var nTangentElements = 4 * nVertices; - this.attributes[ "tangent" ] = { + this.attributes[ 'tangent' ] = { itemSize: 4, array: new Float32Array( nTangentElements ) @@ -9538,7 +9351,7 @@ THREE.BufferGeometry.prototype = { } - var tangents = this.attributes[ "tangent" ].array; + var tangents = this.attributes[ 'tangent' ].array; var tan1 = [], tan2 = []; @@ -9671,7 +9484,7 @@ THREE.BufferGeometry.prototype = { tmp2.crossVectors( n2, t ); test = tmp2.dot( tan2[ v ] ); - w = ( test < 0.0 ) ? -1.0 : 1.0; + w = ( test < 0.0 ) ? - 1.0 : 1.0; tangents[ v * 4 ] = tmp.x; tangents[ v * 4 + 1 ] = tmp.y; @@ -9709,19 +9522,19 @@ THREE.BufferGeometry.prototype = { WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks. */ - computeOffsets: function(indexBufferSize) { + computeOffsets: function ( indexBufferSize ) { var size = indexBufferSize; - if(indexBufferSize === undefined) + if ( indexBufferSize === undefined ) size = 65535; //WebGL limits type of index buffer values to 16-bit. var s = Date.now(); - var indices = this.attributes['index'].array; - var vertices = this.attributes['position'].array; + var indices = this.attributes[ 'index' ].array; + var vertices = this.attributes[ 'position' ].array; - var verticesCount = (vertices.length/3); - var facesCount = (indices.length/3); + var verticesCount = ( vertices.length / 3 ); + var facesCount = ( indices.length / 3 ); /* console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length); @@ -9734,72 +9547,72 @@ THREE.BufferGeometry.prototype = { var vertexPtr = 0; var offsets = [ { start:0, count:0, index:0 } ]; - var offset = offsets[0]; + var offset = offsets[ 0 ]; var duplicatedVertices = 0; var newVerticeMaps = 0; - var faceVertices = new Int32Array(6); + var faceVertices = new Int32Array( 6 ); var vertexMap = new Int32Array( vertices.length ); var revVertexMap = new Int32Array( vertices.length ); - for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; } + for ( var j = 0; j < vertices.length; j ++ ) { vertexMap[ j ] = - 1; revVertexMap[ j ] = - 1; } /* Traverse every face and reorder vertices in the proper offsets of 65k. We can have more than 65k entries in the index buffer per offset, but only reference 65k values. */ - for(var findex = 0; findex < facesCount; findex++) { + for ( var findex = 0; findex < facesCount; findex ++ ) { newVerticeMaps = 0; - for(var vo = 0; vo < 3; vo++) { - var vid = indices[ findex*3 + vo ]; - if(vertexMap[vid] == -1) { + for ( var vo = 0; vo < 3; vo ++ ) { + var vid = indices[ findex * 3 + vo ]; + if ( vertexMap[ vid ] == - 1 ) { //Unmapped vertice - faceVertices[vo*2] = vid; - faceVertices[vo*2+1] = -1; - newVerticeMaps++; - } else if(vertexMap[vid] < offset.index) { + faceVertices[ vo * 2 ] = vid; + faceVertices[ vo * 2 + 1 ] = - 1; + newVerticeMaps ++; + } else if ( vertexMap[ vid ] < offset.index ) { //Reused vertices from previous block (duplicate) - faceVertices[vo*2] = vid; - faceVertices[vo*2+1] = -1; - duplicatedVertices++; + faceVertices[ vo * 2 ] = vid; + faceVertices[ vo * 2 + 1 ] = - 1; + duplicatedVertices ++; } else { //Reused vertice in the current block - faceVertices[vo*2] = vid; - faceVertices[vo*2+1] = vertexMap[vid]; + faceVertices[ vo * 2 ] = vid; + faceVertices[ vo * 2 + 1 ] = vertexMap[ vid ]; } } var faceMax = vertexPtr + newVerticeMaps; - if(faceMax > (offset.index + size)) { + if ( faceMax > ( offset.index + size ) ) { var new_offset = { start:indexPtr, count:0, index:vertexPtr }; - offsets.push(new_offset); + offsets.push( new_offset ); offset = new_offset; //Re-evaluate reused vertices in light of new offset. - for(var v = 0; v < 6; v+=2) { - var new_vid = faceVertices[v+1]; - if(new_vid > -1 && new_vid < offset.index) - faceVertices[v+1] = -1; + for ( var v = 0; v < 6; v += 2 ) { + var new_vid = faceVertices[ v + 1 ]; + if ( new_vid > - 1 && new_vid < offset.index ) + faceVertices[ v + 1 ] = - 1; } } //Reindex the face. - for(var v = 0; v < 6; v+=2) { - var vid = faceVertices[v]; - var new_vid = faceVertices[v+1]; + for ( var v = 0; v < 6; v += 2 ) { + var vid = faceVertices[ v ]; + var new_vid = faceVertices[ v + 1 ]; - if(new_vid === -1) - new_vid = vertexPtr++; + if ( new_vid === - 1 ) + new_vid = vertexPtr ++; - vertexMap[vid] = new_vid; - revVertexMap[new_vid] = vid; - sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit - offset.count++; + vertexMap[ vid ] = new_vid; + revVertexMap[ new_vid ] = vid; + sortedIndices[ indexPtr ++ ] = new_vid - offset.index; //XXX overflows at 16bit + offset.count ++; } } /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */ - this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr); + this.reorderBuffers( sortedIndices, revVertexMap, vertexPtr ); this.offsets = offsets; /* @@ -9821,7 +9634,7 @@ THREE.BufferGeometry.prototype = { normalizeNormals: function () { - var normals = this.attributes[ "normal" ].array; + var normals = this.attributes[ 'normal' ].array; var x, y, z, n; @@ -9848,45 +9661,45 @@ THREE.BufferGeometry.prototype = { indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack). */ - reorderBuffers: function(indexBuffer, indexMap, vertexCount) { + reorderBuffers: function ( indexBuffer, indexMap, vertexCount ) { /* Create a copy of all attributes for reordering. */ var sortedAttributes = {}; var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ]; - for( var attr in this.attributes ) { - if(attr == 'index') + for ( var attr in this.attributes ) { + if ( attr == 'index' ) continue; - var sourceArray = this.attributes[attr].array; - for ( var i = 0, il = types.length; i < il; i++ ) { - var type = types[i]; - if (sourceArray instanceof type) { - sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount ); + var sourceArray = this.attributes[ attr ].array; + for ( var i = 0, il = types.length; i < il; i ++ ) { + var type = types[ i ]; + if ( sourceArray instanceof type ) { + sortedAttributes[ attr ] = new type( this.attributes[ attr ].itemSize * vertexCount ); break; } } } /* Move attribute positions based on the new index map */ - for(var new_vid = 0; new_vid < vertexCount; new_vid++) { - var vid = indexMap[new_vid]; + for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) { + var vid = indexMap[ new_vid ]; for ( var attr in this.attributes ) { - if(attr == 'index') + if ( attr == 'index' ) continue; - var attrArray = this.attributes[attr].array; - var attrSize = this.attributes[attr].itemSize; - var sortedAttr = sortedAttributes[attr]; - for(var k = 0; k < attrSize; k++) + var attrArray = this.attributes[ attr ].array; + var attrSize = this.attributes[ attr ].itemSize; + var sortedAttr = sortedAttributes[ attr ]; + for ( var k = 0; k < attrSize; k ++ ) sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ]; } } /* Carry the new sorted buffers locally */ - this.attributes['index'].array = indexBuffer; + this.attributes[ 'index' ].array = indexBuffer; for ( var attr in this.attributes ) { - if(attr == 'index') + if ( attr == 'index' ) continue; - this.attributes[attr].array = sortedAttributes[attr]; - this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount; + this.attributes[ attr ].array = sortedAttributes[ attr ]; + this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount; } }, @@ -9953,6 +9766,8 @@ THREE.BufferGeometry.prototype = { THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype ); +// File:src/core/Geometry.js + /** * @author mrdoob / http://mrdoob.com/ * @author kile / http://kile.stravaganza.org/ @@ -9970,11 +9785,11 @@ THREE.Geometry = function () { this.name = ''; this.vertices = []; - this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line + this.colors = []; // one-to-one vertex colors, used in Points and Line this.faces = []; - this.faceVertexUvs = [[]]; + this.faceVertexUvs = [ [] ]; this.morphTargets = []; this.morphColors = []; @@ -10003,6 +9818,7 @@ THREE.Geometry = function () { this.lineDistancesNeedUpdate = false; this.buffersNeedUpdate = false; + this.groupsNeedUpdate = false; }; @@ -10048,6 +9864,22 @@ THREE.Geometry.prototype = { }, + center: function () { + + this.computeBoundingBox(); + + var offset = new THREE.Vector3(); + + offset.addVectors( this.boundingBox.min, this.boundingBox.max ); + offset.multiplyScalar( - 0.5 ); + + this.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) ); + this.computeBoundingBox(); + + return offset; + + }, + computeFaceNormals: function () { var cb = new THREE.Vector3(), ab = new THREE.Vector3(); @@ -10336,7 +10168,7 @@ THREE.Geometry.prototype = { face = this.faces[ f ]; - for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) { + for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) { n.copy( face.vertexNormals[ i ] ); @@ -10353,7 +10185,7 @@ THREE.Geometry.prototype = { tmp2.crossVectors( face.vertexNormals[ i ], t ); test = tmp2.dot( tan2[ vertexIndex ] ); - w = (test < 0.0) ? -1.0 : 1.0; + w = ( test < 0.0 ) ? - 1.0 : 1.0; face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w ); @@ -10365,7 +10197,7 @@ THREE.Geometry.prototype = { }, - computeLineDistances: function ( ) { + computeLineDistances: function () { var d = 0; var vertices = this.vertices; @@ -10500,11 +10332,11 @@ THREE.Geometry.prototype = { for ( i = 0, il = uvs2.length; i < il; i ++ ) { var uv = uvs2[ i ], uvCopy = []; - + if ( uv === undefined ) { - + continue; - + } for ( var j = 0, jl = uv.length; j < jl; j ++ ) { @@ -10561,7 +10393,7 @@ THREE.Geometry.prototype = { // have to remove them from the geometry. var faceIndicesToRemove = []; - for( i = 0, il = this.faces.length; i < il; i ++ ) { + for ( i = 0, il = this.faces.length; i < il; i ++ ) { face = this.faces[ i ]; @@ -10571,7 +10403,7 @@ THREE.Geometry.prototype = { indices = [ face.a, face.b, face.c ]; - var dupIndex = -1; + var dupIndex = - 1; // if any duplicate vertices are found in a Face3 // we have to remove the face as nothing can be saved @@ -10613,16 +10445,17 @@ THREE.Geometry.prototype = { makeGroups: ( function () { var geometryGroupCounter = 0; - + return function ( usesFaceMaterial, maxVerticesInGroup ) { var f, fl, face, materialIndex, - groupHash, hash_map = {}; + groupHash, hash_map = {},geometryGroup; var numMorphTargets = this.morphTargets.length; var numMorphNormals = this.morphNormals.length; this.geometryGroups = {}; + this.geometryGroupsList = []; for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { @@ -10639,8 +10472,9 @@ THREE.Geometry.prototype = { if ( ! ( groupHash in this.geometryGroups ) ) { - this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals }; - + geometryGroup = { 'id': geometryGroupCounter++, 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals }; + this.geometryGroups[ groupHash ] = geometryGroup; + this.geometryGroupsList.push(geometryGroup); } if ( this.geometryGroups[ groupHash ].vertices + 3 > maxVerticesInGroup ) { @@ -10650,8 +10484,10 @@ THREE.Geometry.prototype = { if ( ! ( groupHash in this.geometryGroups ) ) { - this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals }; - + geometryGroup = { 'id': geometryGroupCounter++, 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals }; + this.geometryGroups[ groupHash ] = geometryGroup; + this.geometryGroupsList.push(geometryGroup); + } } @@ -10661,23 +10497,13 @@ THREE.Geometry.prototype = { } - this.geometryGroupsList = []; + }; - for ( var g in this.geometryGroups ) { + } )(), - this.geometryGroups[ g ].id = geometryGroupCounter ++; + clone: function () { - this.geometryGroupsList.push( this.geometryGroups[ g ] ); - - } - - }; - - } )(), - - clone: function () { - - var geometry = new THREE.Geometry(); + var geometry = new THREE.Geometry(); var vertices = this.vertices; @@ -10727,6 +10553,8 @@ THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype ); THREE.GeometryIdCount = 0; +// File:src/cameras/Camera.js + /** * @author mrdoob / http://mrdoob.com/ * @author mikael emtinger / http://gomo.se/ @@ -10760,7 +10588,7 @@ THREE.Camera.prototype.lookAt = function () { }(); -THREE.Camera.prototype.clone = function (camera) { +THREE.Camera.prototype.clone = function ( camera ) { if ( camera === undefined ) camera = new THREE.Camera(); @@ -10772,6 +10600,88 @@ THREE.Camera.prototype.clone = function (camera) { return camera; }; +// File:src/cameras/CubeCamera.js + +/** + * Camera for rendering cube maps + * - renders scene into axis-aligned cube + * + * @author alteredq / http://alteredqualia.com/ + */ + +THREE.CubeCamera = function ( near, far, cubeResolution ) { + + THREE.Object3D.call( this ); + + var fov = 90, aspect = 1; + + var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraPX.up.set( 0, - 1, 0 ); + cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) ); + this.add( cameraPX ); + + var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraNX.up.set( 0, - 1, 0 ); + cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) ); + this.add( cameraNX ); + + var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraPY.up.set( 0, 0, 1 ); + cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) ); + this.add( cameraPY ); + + var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraNY.up.set( 0, 0, - 1 ); + cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) ); + this.add( cameraNY ); + + var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.up.set( 0, - 1, 0 ); + cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) ); + this.add( cameraPZ ); + + var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.up.set( 0, - 1, 0 ); + cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) ); + this.add( cameraNZ ); + + this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } ); + + this.updateCubeMap = function ( renderer, scene ) { + + var renderTarget = this.renderTarget; + var generateMipmaps = renderTarget.generateMipmaps; + + renderTarget.generateMipmaps = false; + + renderTarget.activeCubeFace = 0; + renderer.render( scene, cameraPX, renderTarget ); + + renderTarget.activeCubeFace = 1; + renderer.render( scene, cameraNX, renderTarget ); + + renderTarget.activeCubeFace = 2; + renderer.render( scene, cameraPY, renderTarget ); + + renderTarget.activeCubeFace = 3; + renderer.render( scene, cameraNY, renderTarget ); + + renderTarget.activeCubeFace = 4; + renderer.render( scene, cameraPZ, renderTarget ); + + renderTarget.generateMipmaps = generateMipmaps; + + renderTarget.activeCubeFace = 5; + renderer.render( scene, cameraNZ, renderTarget ); + + }; + +}; + +THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype ); + +// File:src/cameras/OrthographicCamera.js + /** * @author alteredq / http://alteredqualia.com/ */ @@ -10810,13 +10720,15 @@ THREE.OrthographicCamera.prototype.clone = function () { camera.right = this.right; camera.top = this.top; camera.bottom = this.bottom; - + camera.near = this.near; camera.far = this.far; return camera; }; +// File:src/cameras/PerspectiveCamera.js + /** * @author mrdoob / http://mrdoob.com/ * @author greggman / http://games.greggman.com/ @@ -10911,7 +10823,7 @@ THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () { var aspect = this.fullWidth / this.fullHeight; var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near; - var bottom = -top; + var bottom = - top; var left = aspect * bottom; var right = aspect * top; var width = Math.abs( right - left ); @@ -10948,11 +10860,13 @@ THREE.PerspectiveCamera.prototype.clone = function () { return camera; }; +// File:src/lights/Light.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ - + THREE.Light = function ( color ) { THREE.Object3D.call( this ); @@ -10975,6 +10889,8 @@ THREE.Light.prototype.clone = function ( light ) { }; +// File:src/lights/AmbientLight.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -10997,6 +10913,8 @@ THREE.AmbientLight.prototype.clone = function () { }; +// File:src/lights/AreaLight.js + /** * @author MPanknin / http://www.redplant.de/ * @author alteredq / http://alteredqualia.com/ @@ -11006,7 +10924,7 @@ THREE.AreaLight = function ( color, intensity ) { THREE.Light.call( this, color ); - this.normal = new THREE.Vector3( 0, -1, 0 ); + this.normal = new THREE.Vector3( 0, - 1, 0 ); this.right = new THREE.Vector3( 1, 0, 0 ); this.intensity = ( intensity !== undefined ) ? intensity : 1; @@ -11023,6 +10941,8 @@ THREE.AreaLight = function ( color, intensity ) { THREE.AreaLight.prototype = Object.create( THREE.Light.prototype ); +// File:src/lights/DirectionalLight.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -11045,10 +10965,10 @@ THREE.DirectionalLight = function ( color, intensity ) { this.shadowCameraNear = 50; this.shadowCameraFar = 5000; - this.shadowCameraLeft = -500; + this.shadowCameraLeft = - 500; this.shadowCameraRight = 500; this.shadowCameraTop = 500; - this.shadowCameraBottom = -500; + this.shadowCameraBottom = - 500; this.shadowCameraVisible = false; @@ -11062,14 +10982,14 @@ THREE.DirectionalLight = function ( color, intensity ) { this.shadowCascade = false; - this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 ); + this.shadowCascadeOffset = new THREE.Vector3( 0, 0, - 1000 ); this.shadowCascadeCount = 2; this.shadowCascadeBias = [ 0, 0, 0 ]; this.shadowCascadeWidth = [ 512, 512, 512 ]; this.shadowCascadeHeight = [ 512, 512, 512 ]; - this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ]; + this.shadowCascadeNearZ = [ - 1.000, 0.990, 0.998 ]; this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ]; this.shadowCascadeArray = []; @@ -11134,6 +11054,8 @@ THREE.DirectionalLight.prototype.clone = function () { }; +// File:src/lights/HemisphereLight.js + /** * @author alteredq / http://alteredqualia.com/ */ @@ -11164,6 +11086,8 @@ THREE.HemisphereLight.prototype.clone = function () { }; +// File:src/lights/PointLight.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -11192,6 +11116,8 @@ THREE.PointLight.prototype.clone = function () { }; +// File:src/lights/SpotLight.js + /** * @author alteredq / http://alteredqualia.com/ */ @@ -11270,2963 +11196,1791 @@ THREE.SpotLight.prototype.clone = function () { }; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Cache = function () { - - this.files = {}; - -}; - -THREE.Cache.prototype = { - - constructor: THREE.Cache, - - add: function ( key, file ) { - - // console.log( 'THREE.Cache', 'Adding key:', key ); - - this.files[ key ] = file; - - }, - - get: function ( key ) { - - // console.log( 'THREE.Cache', 'Checking key:', key ); - - return this.files[ key ]; - - }, - - remove: function ( key ) { - - delete this.files[ key ]; - - }, - - clear: function () { - - this.files = {} - - } - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Loader = function ( showStatus ) { - - this.showStatus = showStatus; - this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null; - - this.imageLoader = new THREE.ImageLoader(); - - this.onLoadStart = function () {}; - this.onLoadProgress = function () {}; - this.onLoadComplete = function () {}; - -}; - -THREE.Loader.prototype = { - - constructor: THREE.Loader, - - crossOrigin: undefined, - - addStatusElement: function () { - - var e = document.createElement( "div" ); - - e.style.position = "absolute"; - e.style.right = "0px"; - e.style.top = "0px"; - e.style.fontSize = "0.8em"; - e.style.textAlign = "left"; - e.style.background = "rgba(0,0,0,0.25)"; - e.style.color = "#fff"; - e.style.width = "120px"; - e.style.padding = "0.5em 0.5em 0.5em 0.5em"; - e.style.zIndex = 1000; - - e.innerHTML = "Loading ..."; - - return e; - - }, - - updateProgress: function ( progress ) { - - var message = "Loaded "; - - if ( progress.total ) { - - message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%"; - - - } else { - - message += ( progress.loaded / 1024 ).toFixed(2) + " KB"; - - } - - this.statusDomElement.innerHTML = message; - - }, - - extractUrlBase: function ( url ) { - - var parts = url.split( '/' ); - - if ( parts.length === 1 ) return './'; - - parts.pop(); - - return parts.join( '/' ) + '/'; - - }, - - initMaterials: function ( materials, texturePath ) { - - var array = []; - - for ( var i = 0; i < materials.length; ++ i ) { - - array[ i ] = this.createMaterial( materials[ i ], texturePath ); - - } - - return array; - - }, - - needsTangents: function ( materials ) { - - for( var i = 0, il = materials.length; i < il; i ++ ) { - - var m = materials[ i ]; - - if ( m instanceof THREE.ShaderMaterial ) return true; - - } - - return false; - - }, - - createMaterial: function ( m, texturePath ) { - - var scope = this; - - function nearest_pow2( n ) { - - var l = Math.log( n ) / Math.LN2; - return Math.pow( 2, Math.round( l ) ); - - } - - function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) { - - var isCompressed = /\.dds$/i.test( sourceFile ); - - var fullPath = texturePath + sourceFile; - - if ( isCompressed ) { - - var texture = THREE.ImageUtils.loadCompressedTexture( fullPath ); - - where[ name ] = texture; - - } else { - - var texture = document.createElement( 'canvas' ); - - where[ name ] = new THREE.Texture( texture ); - - } - - where[ name ].sourceFile = sourceFile; - - if( repeat ) { - - where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] ); - - if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping; - if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping; - - } - - if ( offset ) { - - where[ name ].offset.set( offset[ 0 ], offset[ 1 ] ); - - } - - if ( wrap ) { - - var wrapMap = { - "repeat": THREE.RepeatWrapping, - "mirror": THREE.MirroredRepeatWrapping - } - - if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ]; - if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ]; - - } - - if ( anisotropy ) { - - where[ name ].anisotropy = anisotropy; - - } - - if ( ! isCompressed ) { - - var texture = where[ name ]; - - scope.imageLoader.crossOrigin = scope.crossOrigin; - scope.imageLoader.load( fullPath, function ( image ) { - - if ( THREE.Math.isPowerOfTwo( image.width ) === false || - THREE.Math.isPowerOfTwo( image.height ) === false ) { - - var width = nearest_pow2( image.width ); - var height = nearest_pow2( image.height ); - - texture.image.width = width; - texture.image.height = height; - texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height ); - - } else { - - texture.image = image; - - } - - texture.needsUpdate = true; - - } ); - - } - - } - - function rgb2hex( rgb ) { - - return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255; - - } - - // defaults - - var mtype = "MeshLambertMaterial"; - var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false }; - - // parameters from model file - - if ( m.shading ) { - - var shading = m.shading.toLowerCase(); - - if ( shading === "phong" ) mtype = "MeshPhongMaterial"; - else if ( shading === "basic" ) mtype = "MeshBasicMaterial"; - - } - - if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) { - - mpars.blending = THREE[ m.blending ]; - - } - - if ( m.transparent !== undefined || m.opacity < 1.0 ) { - - mpars.transparent = m.transparent; - - } - - if ( m.depthTest !== undefined ) { - - mpars.depthTest = m.depthTest; - - } - - if ( m.depthWrite !== undefined ) { - - mpars.depthWrite = m.depthWrite; - - } - - if ( m.visible !== undefined ) { - - mpars.visible = m.visible; - - } - - if ( m.flipSided !== undefined ) { - - mpars.side = THREE.BackSide; - - } - - if ( m.doubleSided !== undefined ) { - - mpars.side = THREE.DoubleSide; - - } - - if ( m.wireframe !== undefined ) { - - mpars.wireframe = m.wireframe; - - } - - if ( m.vertexColors !== undefined ) { - - if ( m.vertexColors === "face" ) { - - mpars.vertexColors = THREE.FaceColors; - - } else if ( m.vertexColors ) { - - mpars.vertexColors = THREE.VertexColors; - - } - - } - - // colors - - if ( m.colorDiffuse ) { - - mpars.color = rgb2hex( m.colorDiffuse ); - - } else if ( m.DbgColor ) { - - mpars.color = m.DbgColor; - - } - - if ( m.colorSpecular ) { - - mpars.specular = rgb2hex( m.colorSpecular ); - - } - - if ( m.colorAmbient ) { - - mpars.ambient = rgb2hex( m.colorAmbient ); - - } - - if ( m.colorEmissive ) { - - mpars.emissive = rgb2hex( m.colorEmissive ); - - } - - // modifiers - - if ( m.transparency ) { - - mpars.opacity = m.transparency; - - } - - if ( m.specularCoef ) { - - mpars.shininess = m.specularCoef; - - } - - // textures - - if ( m.mapDiffuse && texturePath ) { - - create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); - - } - - if ( m.mapLight && texturePath ) { - - create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); - - } - - if ( m.mapBump && texturePath ) { - - create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); - - } - - if ( m.mapNormal && texturePath ) { - - create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); - - } - - if ( m.mapSpecular && texturePath ) { - - create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); - - } - - // - - if ( m.mapBumpScale ) { - - mpars.bumpScale = m.mapBumpScale; - - } - - // special case for normal mapped material - - if ( m.mapNormal ) { - - var shader = THREE.ShaderLib[ "normalmap" ]; - var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); - - uniforms[ "tNormal" ].value = mpars.normalMap; - - if ( m.mapNormalFactor ) { - - uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor ); - - } - - if ( mpars.map ) { - - uniforms[ "tDiffuse" ].value = mpars.map; - uniforms[ "enableDiffuse" ].value = true; - - } - - if ( mpars.specularMap ) { - - uniforms[ "tSpecular" ].value = mpars.specularMap; - uniforms[ "enableSpecular" ].value = true; - - } - - if ( mpars.lightMap ) { - - uniforms[ "tAO" ].value = mpars.lightMap; - uniforms[ "enableAO" ].value = true; - - } - - // for the moment don't handle displacement texture - - uniforms[ "diffuse" ].value.setHex( mpars.color ); - uniforms[ "specular" ].value.setHex( mpars.specular ); - uniforms[ "ambient" ].value.setHex( mpars.ambient ); - - uniforms[ "shininess" ].value = mpars.shininess; - - if ( mpars.opacity !== undefined ) { - - uniforms[ "opacity" ].value = mpars.opacity; - - } - - var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true }; - var material = new THREE.ShaderMaterial( parameters ); - - if ( mpars.transparent ) { - - material.transparent = true; - - } - - } else { - - var material = new THREE[ mtype ]( mpars ); - - } - - if ( m.DbgName !== undefined ) material.name = m.DbgName; - - return material; - - } - -}; +// File:src/loaders/Cache.js /** * @author mrdoob / http://mrdoob.com/ */ -THREE.XHRLoader = function ( manager ) { +THREE.Cache = function () { - this.cache = new THREE.Cache(); - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.files = {}; }; -THREE.XHRLoader.prototype = { +THREE.Cache.prototype = { - constructor: THREE.XHRLoader, + constructor: THREE.Cache, - load: function ( url, onLoad, onProgress, onError ) { + add: function ( key, file ) { - var scope = this; + // console.log( 'THREE.Cache', 'Adding key:', key ); - var cached = scope.cache.get( url ); + this.files[ key ] = file; - if ( cached !== undefined ) { + }, - onLoad( cached ); - return; + get: function ( key ) { - } + // console.log( 'THREE.Cache', 'Checking key:', key ); - var request = new XMLHttpRequest(); + return this.files[ key ]; - if ( onLoad !== undefined ) { + }, - request.addEventListener( 'load', function ( event ) { + remove: function ( key ) { - scope.cache.add( url, event.target.responseText ); + delete this.files[ key ]; - onLoad( event.target.responseText ); - scope.manager.itemEnd( url ); + }, - }, false ); + clear: function () { - } + this.files = {} - if ( onProgress !== undefined ) { + } - request.addEventListener( 'progress', function ( event ) { +}; - onProgress( event ); +// File:src/loaders/Loader.js - }, false ); +/** + * @author alteredq / http://alteredqualia.com/ + */ - } +THREE.Loader = function ( showStatus ) { - if ( onError !== undefined ) { + this.showStatus = showStatus; + this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null; - request.addEventListener( 'error', function ( event ) { + this.imageLoader = new THREE.ImageLoader(); - onError( event ); + this.onLoadStart = function () {}; + this.onLoadProgress = function () {}; + this.onLoadComplete = function () {}; - }, false ); +}; - } +THREE.Loader.prototype = { - if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin; + constructor: THREE.Loader, - request.open( 'GET', url, true ); - request.send( null ); + crossOrigin: undefined, - scope.manager.itemStart( url ); + addStatusElement: function () { - }, + var e = document.createElement( 'div' ); - setCrossOrigin: function ( value ) { + e.style.position = 'absolute'; + e.style.right = '0px'; + e.style.top = '0px'; + e.style.fontSize = '0.8em'; + e.style.textAlign = 'left'; + e.style.background = 'rgba(0,0,0,0.25)'; + e.style.color = '#fff'; + e.style.width = '120px'; + e.style.padding = '0.5em 0.5em 0.5em 0.5em'; + e.style.zIndex = 1000; - this.crossOrigin = value; + e.innerHTML = 'Loading ...'; - } + return e; -}; + }, -/** - * @author mrdoob / http://mrdoob.com/ - */ + updateProgress: function ( progress ) { -THREE.ImageLoader = function ( manager ) { + var message = 'Loaded '; - this.cache = new THREE.Cache(); - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + if ( progress.total ) { -}; + message += ( 100 * progress.loaded / progress.total ).toFixed( 0 ) + '%'; -THREE.ImageLoader.prototype = { - constructor: THREE.ImageLoader, + } else { - load: function ( url, onLoad, onProgress, onError ) { + message += ( progress.loaded / 1024 ).toFixed( 2 ) + ' KB'; - var scope = this; + } - var cached = scope.cache.get( url ); + this.statusDomElement.innerHTML = message; - if ( cached !== undefined ) { + }, - onLoad( cached ); - return; + extractUrlBase: function ( url ) { - } + var parts = url.split( '/' ); - var image = document.createElement( 'img' ); + if ( parts.length === 1 ) return './'; - if ( onLoad !== undefined ) { + parts.pop(); - image.addEventListener( 'load', function ( event ) { + return parts.join( '/' ) + '/'; - scope.cache.add( url, this ); + }, - onLoad( this ); - scope.manager.itemEnd( url ); + initMaterials: function ( materials, texturePath ) { - }, false ); + var array = []; + + for ( var i = 0; i < materials.length; ++ i ) { + + array[ i ] = this.createMaterial( materials[ i ], texturePath ); } - if ( onProgress !== undefined ) { + return array; - image.addEventListener( 'progress', function ( event ) { + }, - onProgress( event ); + needsTangents: function ( materials ) { - }, false ); + for ( var i = 0, il = materials.length; i < il; i ++ ) { + + var m = materials[ i ]; + + if ( m instanceof THREE.ShaderMaterial ) return true; } - if ( onError !== undefined ) { + return false; - image.addEventListener( 'error', function ( event ) { + }, - onError( event ); + createMaterial: function ( m, texturePath ) { - }, false ); + var scope = this; + + function nearest_pow2( n ) { + + var l = Math.log( n ) / Math.LN2; + return Math.pow( 2, Math.round( l ) ); } - if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) { - image.src = url; + var fullPath = texturePath + sourceFile; - scope.manager.itemStart( url ); + var texture; - return image; + var loader = THREE.Loader.Handlers.get( fullPath ); - }, + if ( loader !== null ) { - setCrossOrigin: function ( value ) { + texture = loader.load( fullPath ); - this.crossOrigin = value; + } else { - } + texture = new THREE.Texture(); -} + loader = scope.imageLoader; + loader.crossOrigin = scope.crossOrigin; + loader.load( fullPath, function ( image ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.JSONLoader = function ( showStatus ) { - - THREE.Loader.call( this, showStatus ); - - this.withCredentials = false; - -}; - -THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype ); - -THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) { - - var scope = this; - - // todo: unify load API to for easier SceneLoader use - - texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url ); - - this.onLoadStart(); - this.loadAjaxJSON( this, url, callback, texturePath ); - -}; - -THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) { - - var xhr = new XMLHttpRequest(); - - var length = 0; - - xhr.onreadystatechange = function () { - - if ( xhr.readyState === xhr.DONE ) { - - if ( xhr.status === 200 || xhr.status === 0 ) { - - if ( xhr.responseText ) { - - var json = JSON.parse( xhr.responseText ); - - if ( json.metadata !== undefined && json.metadata.type === 'scene' ) { - - console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' ); - return; - - } - - var result = context.parse( json, texturePath ); - callback( result.geometry, result.materials ); - - } else { - - console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' ); - - } - - // in context of more complex asset initialization - // do not block on single failed file - // maybe should go even one more level up - - context.onLoadComplete(); - - } else { - - console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' ); - - } - - } else if ( xhr.readyState === xhr.LOADING ) { - - if ( callbackProgress ) { - - if ( length === 0 ) { - - length = xhr.getResponseHeader( 'Content-Length' ); - - } - - callbackProgress( { total: length, loaded: xhr.responseText.length } ); - - } - - } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) { - - if ( callbackProgress !== undefined ) { - - length = xhr.getResponseHeader( "Content-Length" ); - - } - - } - - }; - - xhr.open( "GET", url, true ); - xhr.withCredentials = this.withCredentials; - xhr.send( null ); - -}; - -THREE.JSONLoader.prototype.parse = function ( json, texturePath ) { - - var scope = this, - geometry = new THREE.Geometry(), - scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; - - parseModel( scale ); - - parseSkin(); - parseMorphing( scale ); - - geometry.computeFaceNormals(); - geometry.computeBoundingSphere(); - - function parseModel( scale ) { - - function isBitSet( value, position ) { - - return value & ( 1 << position ); - - } - - var i, j, fi, - - offset, zLength, - - colorIndex, normalIndex, uvIndex, materialIndex, - - type, - isQuad, - hasMaterial, - hasFaceVertexUv, - hasFaceNormal, hasFaceVertexNormal, - hasFaceColor, hasFaceVertexColor, - - vertex, face, faceA, faceB, color, hex, normal, - - uvLayer, uv, u, v, - - faces = json.faces, - vertices = json.vertices, - normals = json.normals, - colors = json.colors, - - nUvLayers = 0; - - if ( json.uvs !== undefined ) { - - // disregard empty arrays - - for ( i = 0; i < json.uvs.length; i++ ) { - - if ( json.uvs[ i ].length ) nUvLayers ++; - - } - - for ( i = 0; i < nUvLayers; i++ ) { - - geometry.faceVertexUvs[ i ] = []; - - } - - } - - offset = 0; - zLength = vertices.length; - - while ( offset < zLength ) { - - vertex = new THREE.Vector3(); - - vertex.x = vertices[ offset ++ ] * scale; - vertex.y = vertices[ offset ++ ] * scale; - vertex.z = vertices[ offset ++ ] * scale; - - geometry.vertices.push( vertex ); - - } - - offset = 0; - zLength = faces.length; - - while ( offset < zLength ) { - - type = faces[ offset ++ ]; - - - isQuad = isBitSet( type, 0 ); - hasMaterial = isBitSet( type, 1 ); - hasFaceVertexUv = isBitSet( type, 3 ); - hasFaceNormal = isBitSet( type, 4 ); - hasFaceVertexNormal = isBitSet( type, 5 ); - hasFaceColor = isBitSet( type, 6 ); - hasFaceVertexColor = isBitSet( type, 7 ); - - // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); - - if ( isQuad ) { - - faceA = new THREE.Face3(); - faceA.a = faces[ offset ]; - faceA.b = faces[ offset + 1 ]; - faceA.c = faces[ offset + 3 ]; - - faceB = new THREE.Face3(); - faceB.a = faces[ offset + 1 ]; - faceB.b = faces[ offset + 2 ]; - faceB.c = faces[ offset + 3 ]; - - offset += 4; - - if ( hasMaterial ) { - - materialIndex = faces[ offset ++ ]; - faceA.materialIndex = materialIndex; - faceB.materialIndex = materialIndex; - - } - - // to get face <=> uv index correspondence - - fi = geometry.faces.length; - - if ( hasFaceVertexUv ) { - - for ( i = 0; i < nUvLayers; i++ ) { - - uvLayer = json.uvs[ i ]; - - geometry.faceVertexUvs[ i ][ fi ] = []; - geometry.faceVertexUvs[ i ][ fi + 1 ] = [] - - for ( j = 0; j < 4; j ++ ) { - - uvIndex = faces[ offset ++ ]; - - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; - - uv = new THREE.Vector2( u, v ); - - if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); - if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); - - } - - } - - } - - if ( hasFaceNormal ) { - - normalIndex = faces[ offset ++ ] * 3; - - faceA.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); - - faceB.normal.copy( faceA.normal ); - - } - - if ( hasFaceVertexNormal ) { - - for ( i = 0; i < 4; i++ ) { - - normalIndex = faces[ offset ++ ] * 3; - - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); - - - if ( i !== 2 ) faceA.vertexNormals.push( normal ); - if ( i !== 0 ) faceB.vertexNormals.push( normal ); - - } - - } - - - if ( hasFaceColor ) { - - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; - - faceA.color.setHex( hex ); - faceB.color.setHex( hex ); - - } - - - if ( hasFaceVertexColor ) { - - for ( i = 0; i < 4; i++ ) { - - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; - - if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) ); - if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) ); - - } - - } - - geometry.faces.push( faceA ); - geometry.faces.push( faceB ); - - } else { - - face = new THREE.Face3(); - face.a = faces[ offset ++ ]; - face.b = faces[ offset ++ ]; - face.c = faces[ offset ++ ]; - - if ( hasMaterial ) { - - materialIndex = faces[ offset ++ ]; - face.materialIndex = materialIndex; - - } - - // to get face <=> uv index correspondence - - fi = geometry.faces.length; - - if ( hasFaceVertexUv ) { - - for ( i = 0; i < nUvLayers; i++ ) { - - uvLayer = json.uvs[ i ]; - - geometry.faceVertexUvs[ i ][ fi ] = []; - - for ( j = 0; j < 3; j ++ ) { - - uvIndex = faces[ offset ++ ]; - - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; - - uv = new THREE.Vector2( u, v ); - - geometry.faceVertexUvs[ i ][ fi ].push( uv ); - - } - - } - - } - - if ( hasFaceNormal ) { - - normalIndex = faces[ offset ++ ] * 3; - - face.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); - - } - - if ( hasFaceVertexNormal ) { - - for ( i = 0; i < 3; i++ ) { - - normalIndex = faces[ offset ++ ] * 3; - - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); - - face.vertexNormals.push( normal ); - - } - - } - - - if ( hasFaceColor ) { - - colorIndex = faces[ offset ++ ]; - face.color.setHex( colors[ colorIndex ] ); - - } - - - if ( hasFaceVertexColor ) { - - for ( i = 0; i < 3; i++ ) { - - colorIndex = faces[ offset ++ ]; - face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) ); - - } - - } - - geometry.faces.push( face ); - - } - - } - - }; - - function parseSkin() { - var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; - - if ( json.skinWeights ) { - - for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { - - var x = json.skinWeights[ i ]; - var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0; - var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; - var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; - - geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) ); - - } - - } - - if ( json.skinIndices ) { - - for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { - - var a = json.skinIndices[ i ]; - var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; - var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; - var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; - - geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) ); - - } - - } - - geometry.bones = json.bones; - - if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { - - console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + - geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); - - } - - - // could change this to json.animations[0] or remove completely - - geometry.animation = json.animation; - geometry.animations = json.animations; - - }; - - function parseMorphing( scale ) { - - if ( json.morphTargets !== undefined ) { - - var i, l, v, vl, dstVertices, srcVertices; - - for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) { - - geometry.morphTargets[ i ] = {}; - geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; - geometry.morphTargets[ i ].vertices = []; - - dstVertices = geometry.morphTargets[ i ].vertices; - srcVertices = json.morphTargets [ i ].vertices; - - for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) { - - var vertex = new THREE.Vector3(); - vertex.x = srcVertices[ v ] * scale; - vertex.y = srcVertices[ v + 1 ] * scale; - vertex.z = srcVertices[ v + 2 ] * scale; - - dstVertices.push( vertex ); - - } - - } - - } - - if ( json.morphColors !== undefined ) { - - var i, l, c, cl, dstColors, srcColors, color; - - for ( i = 0, l = json.morphColors.length; i < l; i++ ) { - - geometry.morphColors[ i ] = {}; - geometry.morphColors[ i ].name = json.morphColors[ i ].name; - geometry.morphColors[ i ].colors = []; - - dstColors = geometry.morphColors[ i ].colors; - srcColors = json.morphColors [ i ].colors; - - for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) { - - color = new THREE.Color( 0xffaa00 ); - color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] ); - dstColors.push( color ); - - } - - } - - } - - }; - - if ( json.materials === undefined || json.materials.length === 0 ) { - - return { geometry: geometry }; - - } else { - - var materials = this.initMaterials( json.materials, texturePath ); - - if ( this.needsTangents( materials ) ) { - - geometry.computeTangents(); - - } - - return { geometry: geometry, materials: materials }; - - } - -}; + if ( THREE.Math.isPowerOfTwo( image.width ) === false || + THREE.Math.isPowerOfTwo( image.height ) === false ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + var width = nearest_pow2( image.width ); + var height = nearest_pow2( image.height ); -THREE.LoadingManager = function ( onLoad, onProgress, onError ) { + var canvas = document.createElement( 'canvas' ); + canvas.width = width; + canvas.height = height; - var scope = this; + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, width, height ); - var loaded = 0, total = 0; + texture.image = canvas; - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; + } else { - this.itemStart = function ( url ) { + texture.image = image; - total ++; + } - }; + texture.needsUpdate = true; - this.itemEnd = function ( url ) { + } ); - loaded ++; + } - if ( scope.onProgress !== undefined ) { + texture.sourceFile = sourceFile; - scope.onProgress( url, loaded, total ); + if ( repeat ) { - } + texture.repeat.set( repeat[ 0 ], repeat[ 1 ] ); - if ( loaded === total && scope.onLoad !== undefined ) { + if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping; + if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping; - scope.onLoad(); + } - } + if ( offset ) { - }; + texture.offset.set( offset[ 0 ], offset[ 1 ] ); -}; + } -THREE.DefaultLoadingManager = new THREE.LoadingManager(); + if ( wrap ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.BufferGeometryLoader = function ( manager ) { - - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - -}; - -THREE.BufferGeometryLoader.prototype = { - - constructor: THREE.BufferGeometryLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - - var loader = new THREE.XHRLoader(); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { - - onLoad( scope.parse( JSON.parse( text ) ) ); - - } ); - - }, - - setCrossOrigin: function ( value ) { - - this.crossOrigin = value; - - }, - - parse: function ( json ) { - - var geometry = new THREE.BufferGeometry(); - - var attributes = json.attributes; - var offsets = json.offsets; - var boundingSphere = json.boundingSphere; - - for ( var key in attributes ) { - - var attribute = attributes[ key ]; - - geometry.attributes[ key ] = { - itemSize: attribute.itemSize, - array: new self[ attribute.type ]( attribute.array ) - } - - } - - if ( offsets !== undefined ) { - - geometry.offsets = JSON.parse( JSON.stringify( offsets ) ); - - } - - if ( boundingSphere !== undefined ) { - - geometry.boundingSphere = new THREE.Sphere( - new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ), - boundingSphere.radius - ); - - } - - return geometry; - - } - -}; - -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.MaterialLoader = function ( manager ) { - - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - -}; - -THREE.MaterialLoader.prototype = { - - constructor: THREE.MaterialLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - - var loader = new THREE.XHRLoader(); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { - - onLoad( scope.parse( JSON.parse( text ) ) ); - - } ); - - }, - - setCrossOrigin: function ( value ) { - - this.crossOrigin = value; - - }, - - parse: function ( json ) { - - var material = new THREE[ json.type ]; - - if ( json.color !== undefined ) material.color.setHex( json.color ); - if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient ); - if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); - if ( json.specular !== undefined ) material.specular.setHex( json.specular ); - if ( json.shininess !== undefined ) material.shininess = json.shininess; - if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; - if ( json.blending !== undefined ) material.blending = json.blending; - if ( json.side !== undefined ) material.side = json.side; - if ( json.opacity !== undefined ) material.opacity = json.opacity; - if ( json.transparent !== undefined ) material.transparent = json.transparent; - if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; - - if ( json.materials !== undefined ) { - - for ( var i = 0, l = json.materials.length; i < l; i ++ ) { - - material.materials.push( this.parse( json.materials[ i ] ) ); - - } - - } - - return material; - - } - -}; + var wrapMap = { + 'repeat': THREE.RepeatWrapping, + 'mirror': THREE.MirroredRepeatWrapping + } -/** - * @author mrdoob / http://mrdoob.com/ - */ + if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ]; + if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ]; -THREE.ObjectLoader = function ( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + if ( anisotropy ) { -}; + texture.anisotropy = anisotropy; -THREE.ObjectLoader.prototype = { + } - constructor: THREE.ObjectLoader, + where[ name ] = texture; - load: function ( url, onLoad, onProgress, onError ) { + } - var scope = this; + function rgb2hex( rgb ) { - var loader = new THREE.XHRLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { + return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255; - onLoad( scope.parse( JSON.parse( text ) ) ); + } - } ); + // defaults - }, + var mtype = 'MeshLambertMaterial'; + var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false }; - setCrossOrigin: function ( value ) { + // parameters from model file - this.crossOrigin = value; + if ( m.shading ) { - }, + var shading = m.shading.toLowerCase(); - parse: function ( json ) { + if ( shading === 'phong' ) mtype = 'MeshPhongMaterial'; + else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial'; - var geometries = this.parseGeometries( json.geometries ); - var materials = this.parseMaterials( json.materials ); - var object = this.parseObject( json.object, geometries, materials ); - - return object; - - }, + } - parseGeometries: function ( json ) { + if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) { - var geometries = {}; + mpars.blending = THREE[ m.blending ]; - if ( json !== undefined ) { + } - var geometryLoader = new THREE.JSONLoader(); - var bufferGeometryLoader = new THREE.BufferGeometryLoader(); + if ( m.transparent !== undefined || m.opacity < 1.0 ) { - for ( var i = 0, l = json.length; i < l; i ++ ) { + mpars.transparent = m.transparent; - var geometry; - var data = json[ i ]; + } - switch ( data.type ) { + if ( m.depthTest !== undefined ) { - case 'PlaneGeometry': + mpars.depthTest = m.depthTest; - geometry = new THREE.PlaneGeometry( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); + } - break; + if ( m.depthWrite !== undefined ) { - case 'BoxGeometry': - case 'CubeGeometry': // DEPRECATED + mpars.depthWrite = m.depthWrite; - geometry = new THREE.BoxGeometry( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); + } - break; + if ( m.visible !== undefined ) { - case 'CircleGeometry': + mpars.visible = m.visible; - geometry = new THREE.CircleGeometry( - data.radius, - data.segments - ); + } - break; + if ( m.flipSided !== undefined ) { - case 'CylinderGeometry': + mpars.side = THREE.BackSide; - geometry = new THREE.CylinderGeometry( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded - ); + } - break; + if ( m.doubleSided !== undefined ) { - case 'SphereGeometry': + mpars.side = THREE.DoubleSide; - geometry = new THREE.SphereGeometry( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + } - break; + if ( m.wireframe !== undefined ) { - case 'IcosahedronGeometry': + mpars.wireframe = m.wireframe; - geometry = new THREE.IcosahedronGeometry( - data.radius, - data.detail - ); + } - break; + if ( m.vertexColors !== undefined ) { - case 'TorusGeometry': + if ( m.vertexColors === 'face' ) { - geometry = new THREE.TorusGeometry( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); + mpars.vertexColors = THREE.FaceColors; - break; + } else if ( m.vertexColors ) { - case 'TorusKnotGeometry': + mpars.vertexColors = THREE.VertexColors; - geometry = new THREE.TorusKnotGeometry( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.p, - data.q, - data.heightScale - ); + } - break; + } - case 'BufferGeometry': + // colors - geometry = bufferGeometryLoader.parse( data.data ); + if ( m.colorDiffuse ) { - break; + mpars.color = rgb2hex( m.colorDiffuse ); - case 'Geometry': + } else if ( m.DbgColor ) { - geometry = geometryLoader.parse( data.data ).geometry; + mpars.color = m.DbgColor; - break; + } - } + if ( m.colorSpecular ) { - geometry.uuid = data.uuid; + mpars.specular = rgb2hex( m.colorSpecular ); - if ( data.name !== undefined ) geometry.name = data.name; + } - geometries[ data.uuid ] = geometry; + if ( m.colorAmbient ) { - } + mpars.ambient = rgb2hex( m.colorAmbient ); } - return geometries; + if ( m.colorEmissive ) { - }, + mpars.emissive = rgb2hex( m.colorEmissive ); - parseMaterials: function ( json ) { + } - var materials = {}; + // modifiers - if ( json !== undefined ) { + if ( m.transparency ) { - var loader = new THREE.MaterialLoader(); + mpars.opacity = m.transparency; - for ( var i = 0, l = json.length; i < l; i ++ ) { + } - var data = json[ i ]; - var material = loader.parse( data ); + if ( m.specularCoef ) { - material.uuid = data.uuid; + mpars.shininess = m.specularCoef; - if ( data.name !== undefined ) material.name = data.name; + } - materials[ data.uuid ] = material; + // textures - } + if ( m.mapDiffuse && texturePath ) { + + create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); } - return materials; + if ( m.mapLight && texturePath ) { - }, + create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); - parseObject: function () { + } - var matrix = new THREE.Matrix4(); + if ( m.mapBump && texturePath ) { - return function ( data, geometries, materials ) { + create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); - var object; + } - switch ( data.type ) { + if ( m.mapNormal && texturePath ) { - case 'Scene': + create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); - object = new THREE.Scene(); + } - break; + if ( m.mapSpecular && texturePath ) { - case 'PerspectiveCamera': + create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); - object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + } - break; + if ( m.mapAlpha && texturePath ) { - case 'OrthographicCamera': + create_texture( mpars, 'alphaMap', m.mapAlpha, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); - object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + } - break; + // - case 'AmbientLight': + if ( m.mapBumpScale ) { - object = new THREE.AmbientLight( data.color ); + mpars.bumpScale = m.mapBumpScale; - break; + } - case 'DirectionalLight': + // special case for normal mapped material - object = new THREE.DirectionalLight( data.color, data.intensity ); + if ( m.mapNormal ) { - break; + var shader = THREE.ShaderLib[ 'normalmap' ]; + var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); - case 'PointLight': + uniforms[ 'tNormal' ].value = mpars.normalMap; - object = new THREE.PointLight( data.color, data.intensity, data.distance ); + if ( m.mapNormalFactor ) { - break; + uniforms[ 'uNormalScale' ].value.set( m.mapNormalFactor, m.mapNormalFactor ); - case 'SpotLight': + } - object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent ); + if ( mpars.map ) { - break; + uniforms[ 'tDiffuse' ].value = mpars.map; + uniforms[ 'enableDiffuse' ].value = true; - case 'HemisphereLight': + } - object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); + if ( mpars.specularMap ) { - break; + uniforms[ 'tSpecular' ].value = mpars.specularMap; + uniforms[ 'enableSpecular' ].value = true; - case 'Mesh': + } - var geometry = geometries[ data.geometry ]; - var material = materials[ data.material ]; + if ( mpars.lightMap ) { - if ( geometry === undefined ) { + uniforms[ 'tAO' ].value = mpars.lightMap; + uniforms[ 'enableAO' ].value = true; - console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry ); + } - } + // for the moment don't handle displacement texture - if ( material === undefined ) { + uniforms[ 'diffuse' ].value.setHex( mpars.color ); + uniforms[ 'specular' ].value.setHex( mpars.specular ); + uniforms[ 'ambient' ].value.setHex( mpars.ambient ); - console.error( 'THREE.ObjectLoader: Undefined material ' + data.material ); + uniforms[ 'shininess' ].value = mpars.shininess; - } + if ( mpars.opacity !== undefined ) { - object = new THREE.Mesh( geometry, material ); + uniforms[ 'opacity' ].value = mpars.opacity; - break; + } - case 'Sprite': + var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true }; + var material = new THREE.ShaderMaterial( parameters ); - var material = materials[ data.material ]; + if ( mpars.transparent ) { - if ( material === undefined ) { + material.transparent = true; - console.error( 'THREE.ObjectLoader: Undefined material ' + data.material ); + } - } + } else { - object = new THREE.Sprite( material ); + var material = new THREE[ mtype ]( mpars ); - break; + } - default: + if ( m.DbgName !== undefined ) material.name = m.DbgName; - object = new THREE.Object3D(); + return material; - } + } - object.uuid = data.uuid; +}; - if ( data.name !== undefined ) object.name = data.name; - if ( data.matrix !== undefined ) { +THREE.Loader.Handlers = { - matrix.fromArray( data.matrix ); - matrix.decompose( object.position, object.quaternion, object.scale ); + handlers: [], - } else { + add: function ( regex, loader ) { - if ( data.position !== undefined ) object.position.fromArray( data.position ); - if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); - if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); + this.handlers.push( regex, loader ); - } + }, - if ( data.visible !== undefined ) object.visible = data.visible; - if ( data.userData !== undefined ) object.userData = data.userData; + get: function ( file ) { - if ( data.children !== undefined ) { + for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) { - for ( var child in data.children ) { + var regex = this.handlers[ i ]; + var loader = this.handlers[ i + 1 ]; - object.add( this.parseObject( data.children[ child ], geometries, materials ) ); + if ( regex.test( file ) ) { - } + return loader; } - return object; - } - }() + return null; + + } }; +// File:src/loaders/XHRLoader.js + /** - * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ */ -THREE.SceneLoader = function () { - - this.onLoadStart = function () {}; - this.onLoadProgress = function() {}; - this.onLoadComplete = function () {}; - - this.callbackSync = function () {}; - this.callbackProgress = function () {}; - - this.geometryHandlers = {}; - this.hierarchyHandlers = {}; +THREE.XHRLoader = function ( manager ) { - this.addGeometryHandler( "ascii", THREE.JSONLoader ); + this.cache = new THREE.Cache(); + this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; }; -THREE.SceneLoader.prototype = { +THREE.XHRLoader.prototype = { - constructor: THREE.SceneLoader, + constructor: THREE.XHRLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; - var loader = new THREE.XHRLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { + var cached = scope.cache.get( url ); - scope.parse( JSON.parse( text ), onLoad, url ); + if ( cached !== undefined ) { - } ); + if ( onLoad ) onLoad( cached ); + return; - }, + } - setCrossOrigin: function ( value ) { + var request = new XMLHttpRequest(); + request.open( 'GET', url, true ); - this.crossOrigin = value; + request.addEventListener( 'load', function ( event ) { - }, + scope.cache.add( url, this.response ); - addGeometryHandler: function ( typeID, loaderClass ) { + if ( onLoad ) onLoad( this.response ); - this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass }; + scope.manager.itemEnd( url ); - }, + }, false ); - addHierarchyHandler: function ( typeID, loaderClass ) { + if ( onProgress !== undefined ) { - this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass }; + request.addEventListener( 'progress', function ( event ) { - }, + onProgress( event ); - parse: function ( json, callbackFinished, url ) { + }, false ); - var scope = this; + } - var urlBase = THREE.Loader.prototype.extractUrlBase( url ); + if ( onError !== undefined ) { - var geometry, material, camera, fog, - texture, images, color, - light, hex, intensity, - counter_models, counter_textures, - total_models, total_textures, - result; + request.addEventListener( 'error', function ( event ) { - var target_array = []; - - var data = json; - - // async geometry loaders - - for ( var typeID in this.geometryHandlers ) { + onError( event ); - var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ]; - this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass(); + }, false ); } - // async hierachy loaders - - for ( var typeID in this.hierarchyHandlers ) { - - var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ]; - this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass(); - - } + if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin; + if ( this.responseType !== undefined ) request.responseType = this.responseType; - counter_models = 0; - counter_textures = 0; + request.send( null ); - result = { + scope.manager.itemStart( url ); - scene: new THREE.Scene(), - geometries: {}, - face_materials: {}, - materials: {}, - textures: {}, - objects: {}, - cameras: {}, - lights: {}, - fogs: {}, - empties: {}, - groups: {} + }, - }; + setResponseType: function ( value ) { - if ( data.transform ) { + this.responseType = value; - var position = data.transform.position, - rotation = data.transform.rotation, - scale = data.transform.scale; + }, - if ( position ) { + setCrossOrigin: function ( value ) { - result.scene.position.fromArray( position ); + this.crossOrigin = value; - } + } - if ( rotation ) { +}; - result.scene.rotation.fromArray( rotation ); +// File:src/loaders/ImageLoader.js - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - if ( scale ) { +THREE.ImageLoader = function ( manager ) { - result.scene.scale.fromArray( scale ); + this.cache = new THREE.Cache(); + this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - } +}; - if ( position || rotation || scale ) { +THREE.ImageLoader.prototype = { - result.scene.updateMatrix(); - result.scene.updateMatrixWorld(); + constructor: THREE.ImageLoader, - } + load: function ( url, onLoad, onProgress, onError ) { - } + var scope = this; - function get_url( source_url, url_type ) { + var cached = scope.cache.get( url ); - if ( url_type == "relativeToHTML" ) { + if ( cached !== undefined ) { - return source_url; + onLoad( cached ); + return; - } else { + } - return urlBase + source_url; + var image = document.createElement( 'img' ); - } + if ( onLoad !== undefined ) { - }; + image.addEventListener( 'load', function ( event ) { - // toplevel loader function, delegates to handle_children + scope.cache.add( url, this ); - function handle_objects() { + onLoad( this ); + scope.manager.itemEnd( url ); - handle_children( result.scene, data.objects ); + }, false ); } - // handle all the children from the loaded json and attach them to given parent + if ( onProgress !== undefined ) { - function handle_children( parent, children ) { + image.addEventListener( 'progress', function ( event ) { - var mat, dst, pos, rot, scl, quat; + onProgress( event ); - for ( var objID in children ) { + }, false ); - // check by id if child has already been handled, - // if not, create new object + } - var object = result.objects[ objID ]; - var objJSON = children[ objID ]; + if ( onError !== undefined ) { - if ( object === undefined ) { + image.addEventListener( 'error', function ( event ) { - // meshes + onError( event ); - if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) { + }, false ); - if ( objJSON.loading === undefined ) { + } - var reservedTypes = { - "type": 1, "url": 1, "material": 1, - "position": 1, "rotation": 1, "scale" : 1, - "visible": 1, "children": 1, "userData": 1, - "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 - }; + if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; - var loaderParameters = {}; + image.src = url; - for ( var parType in objJSON ) { + scope.manager.itemStart( url ); - if ( ! ( parType in reservedTypes ) ) { + return image; - loaderParameters[ parType ] = objJSON[ parType ]; + }, - } + setCrossOrigin: function ( value ) { - } + this.crossOrigin = value; - material = result.materials[ objJSON.material ]; + } - objJSON.loading = true; +} - var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ]; +// File:src/loaders/JSONLoader.js - // ColladaLoader +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - if ( loader.options ) { +THREE.JSONLoader = function ( showStatus ) { - loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) ); + THREE.Loader.call( this, showStatus ); - // UTF8Loader - // OBJLoader + this.withCredentials = false; - } else { +}; - loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters ); +THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype ); - } +THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) { - } + var scope = this; - } else if ( objJSON.geometry !== undefined ) { + // todo: unify load API to for easier SceneLoader use - geometry = result.geometries[ objJSON.geometry ]; + texturePath = texturePath && ( typeof texturePath === 'string' ) ? texturePath : this.extractUrlBase( url ); - // geometry already loaded + this.onLoadStart(); + this.loadAjaxJSON( this, url, callback, texturePath ); - if ( geometry ) { +}; - var needsTangents = false; +THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) { - material = result.materials[ objJSON.material ]; - needsTangents = material instanceof THREE.ShaderMaterial; + var xhr = new XMLHttpRequest(); - pos = objJSON.position; - rot = objJSON.rotation; - scl = objJSON.scale; - mat = objJSON.matrix; - quat = objJSON.quaternion; + var length = 0; - // use materials from the model file - // if there is no material specified in the object + xhr.onreadystatechange = function () { - if ( ! objJSON.material ) { + if ( xhr.readyState === xhr.DONE ) { - material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] ); + if ( xhr.status === 200 || xhr.status === 0 ) { - } + if ( xhr.responseText ) { - // use materials from the model file - // if there is just empty face material - // (must create new material as each model has its own face material) + var json = JSON.parse( xhr.responseText ); - if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) { + if ( json.metadata !== undefined && json.metadata.type === 'scene' ) { - material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] ); + console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' ); + return; - } + } - if ( material instanceof THREE.MeshFaceMaterial ) { + var result = context.parse( json, texturePath ); + callback( result.geometry, result.materials ); - for ( var i = 0; i < material.materials.length; i ++ ) { + } else { - needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial ); + console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' ); - } + } - } + // in context of more complex asset initialization + // do not block on single failed file + // maybe should go even one more level up - if ( needsTangents ) { + context.onLoadComplete(); - geometry.computeTangents(); + } else { - } + console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' ); - if ( objJSON.skin ) { + } - object = new THREE.SkinnedMesh( geometry, material ); + } else if ( xhr.readyState === xhr.LOADING ) { - } else if ( objJSON.morph ) { + if ( callbackProgress ) { - object = new THREE.MorphAnimMesh( geometry, material ); + if ( length === 0 ) { - if ( objJSON.duration !== undefined ) { + length = xhr.getResponseHeader( 'Content-Length' ); - object.duration = objJSON.duration; + } - } + callbackProgress( { total: length, loaded: xhr.responseText.length } ); - if ( objJSON.time !== undefined ) { + } - object.time = objJSON.time; + } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) { - } + if ( callbackProgress !== undefined ) { - if ( objJSON.mirroredLoop !== undefined ) { + length = xhr.getResponseHeader( 'Content-Length' ); - object.mirroredLoop = objJSON.mirroredLoop; + } - } + } - if ( material.morphNormals ) { + }; - geometry.computeMorphNormals(); + xhr.open( 'GET', url, true ); + xhr.withCredentials = this.withCredentials; + xhr.send( null ); - } +}; - } else { +THREE.JSONLoader.prototype.parse = function ( json, texturePath ) { - object = new THREE.Mesh( geometry, material ); + var scope = this, + geometry = new THREE.Geometry(), + scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; - } + parseModel( scale ); - object.name = objID; + parseSkin(); + parseMorphing( scale ); - if ( mat ) { + geometry.computeFaceNormals(); + geometry.computeBoundingSphere(); - object.matrixAutoUpdate = false; - object.matrix.set( - mat[0], mat[1], mat[2], mat[3], - mat[4], mat[5], mat[6], mat[7], - mat[8], mat[9], mat[10], mat[11], - mat[12], mat[13], mat[14], mat[15] - ); + function parseModel( scale ) { - } else { + function isBitSet( value, position ) { - object.position.fromArray( pos ); + return value & ( 1 << position ); - if ( quat ) { + } - object.quaternion.fromArray( quat ); + var i, j, fi, - } else { + offset, zLength, - object.rotation.fromArray( rot ); + colorIndex, normalIndex, uvIndex, materialIndex, - } + type, + isQuad, + hasMaterial, + hasFaceVertexUv, + hasFaceNormal, hasFaceVertexNormal, + hasFaceColor, hasFaceVertexColor, - object.scale.fromArray( scl ); + vertex, face, faceA, faceB, color, hex, normal, - } + uvLayer, uv, u, v, - object.visible = objJSON.visible; - object.castShadow = objJSON.castShadow; - object.receiveShadow = objJSON.receiveShadow; + faces = json.faces, + vertices = json.vertices, + normals = json.normals, + colors = json.colors, - parent.add( object ); + nUvLayers = 0; - result.objects[ objID ] = object; + if ( json.uvs !== undefined ) { - } + // disregard empty arrays - // lights + for ( i = 0; i < json.uvs.length; i ++ ) { - } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" || - objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" || - objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) { + if ( json.uvs[ i ].length ) nUvLayers ++; - var color = objJSON.color; - var intensity = objJSON.intensity; - var distance = objJSON.distance; - var position = objJSON.position; - var rotation = objJSON.rotation; + } - switch ( objJSON.type ) { + for ( i = 0; i < nUvLayers; i ++ ) { - case 'AmbientLight': - light = new THREE.AmbientLight( color ); - break; + geometry.faceVertexUvs[ i ] = []; - case 'PointLight': - light = new THREE.PointLight( color, intensity, distance ); - light.position.fromArray( position ); - break; + } - case 'DirectionalLight': - light = new THREE.DirectionalLight( color, intensity ); - light.position.fromArray( objJSON.direction ); - break; + } - case 'SpotLight': - light = new THREE.SpotLight( color, intensity, distance, 1 ); - light.angle = objJSON.angle; - light.position.fromArray( position ); - light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] ); - light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) ); - break; + offset = 0; + zLength = vertices.length; - case 'HemisphereLight': - light = new THREE.DirectionalLight( color, intensity, distance ); - light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] ); - light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) ); - break; + while ( offset < zLength ) { - case 'AreaLight': - light = new THREE.AreaLight(color, intensity); - light.position.fromArray( position ); - light.width = objJSON.size; - light.height = objJSON.size_y; - break; + vertex = new THREE.Vector3(); - } + vertex.x = vertices[ offset ++ ] * scale; + vertex.y = vertices[ offset ++ ] * scale; + vertex.z = vertices[ offset ++ ] * scale; - parent.add( light ); + geometry.vertices.push( vertex ); - light.name = objID; - result.lights[ objID ] = light; - result.objects[ objID ] = light; + } - // cameras + offset = 0; + zLength = faces.length; - } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) { + while ( offset < zLength ) { - pos = objJSON.position; - rot = objJSON.rotation; - quat = objJSON.quaternion; + type = faces[ offset ++ ]; - if ( objJSON.type === "PerspectiveCamera" ) { - camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far ); + isQuad = isBitSet( type, 0 ); + hasMaterial = isBitSet( type, 1 ); + hasFaceVertexUv = isBitSet( type, 3 ); + hasFaceNormal = isBitSet( type, 4 ); + hasFaceVertexNormal = isBitSet( type, 5 ); + hasFaceColor = isBitSet( type, 6 ); + hasFaceVertexColor = isBitSet( type, 7 ); - } else if ( objJSON.type === "OrthographicCamera" ) { + // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); - camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far ); + if ( isQuad ) { - } + faceA = new THREE.Face3(); + faceA.a = faces[ offset ]; + faceA.b = faces[ offset + 1 ]; + faceA.c = faces[ offset + 3 ]; - camera.name = objID; - camera.position.fromArray( pos ); + faceB = new THREE.Face3(); + faceB.a = faces[ offset + 1 ]; + faceB.b = faces[ offset + 2 ]; + faceB.c = faces[ offset + 3 ]; - if ( quat !== undefined ) { + offset += 4; - camera.quaternion.fromArray( quat ); + if ( hasMaterial ) { - } else if ( rot !== undefined ) { + materialIndex = faces[ offset ++ ]; + faceA.materialIndex = materialIndex; + faceB.materialIndex = materialIndex; - camera.rotation.fromArray( rot ); + } - } + // to get face <=> uv index correspondence - parent.add( camera ); + fi = geometry.faces.length; - result.cameras[ objID ] = camera; - result.objects[ objID ] = camera; + if ( hasFaceVertexUv ) { - // pure Object3D + for ( i = 0; i < nUvLayers; i ++ ) { - } else { + uvLayer = json.uvs[ i ]; - pos = objJSON.position; - rot = objJSON.rotation; - scl = objJSON.scale; - quat = objJSON.quaternion; + geometry.faceVertexUvs[ i ][ fi ] = []; + geometry.faceVertexUvs[ i ][ fi + 1 ] = [] - object = new THREE.Object3D(); - object.name = objID; - object.position.fromArray( pos ); + for ( j = 0; j < 4; j ++ ) { - if ( quat ) { + uvIndex = faces[ offset ++ ]; - object.quaternion.fromArray( quat ); + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - } else { + uv = new THREE.Vector2( u, v ); - object.rotation.fromArray( rot ); + if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); + if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); } - object.scale.fromArray( scl ); - object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false; - - parent.add( object ); - - result.objects[ objID ] = object; - result.empties[ objID ] = object; - } - if ( object ) { - - if ( objJSON.userData !== undefined ) { - - for ( var key in objJSON.userData ) { - - var value = objJSON.userData[ key ]; - object.userData[ key ] = value; + } - } + if ( hasFaceNormal ) { - } + normalIndex = faces[ offset ++ ] * 3; - if ( objJSON.groups !== undefined ) { + faceA.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - for ( var i = 0; i < objJSON.groups.length; i ++ ) { + faceB.normal.copy( faceA.normal ); - var groupID = objJSON.groups[ i ]; + } - if ( result.groups[ groupID ] === undefined ) { + if ( hasFaceVertexNormal ) { - result.groups[ groupID ] = []; + for ( i = 0; i < 4; i ++ ) { - } + normalIndex = faces[ offset ++ ] * 3; - result.groups[ groupID ].push( objID ); + normal = new THREE.Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - } - } + if ( i !== 2 ) faceA.vertexNormals.push( normal ); + if ( i !== 0 ) faceB.vertexNormals.push( normal ); } } - if ( object !== undefined && objJSON.children !== undefined ) { - handle_children( object, objJSON.children ); + if ( hasFaceColor ) { - } + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - } + faceA.color.setHex( hex ); + faceB.color.setHex( hex ); - }; + } - function handle_mesh( geo, mat, id ) { - result.geometries[ id ] = geo; - result.face_materials[ id ] = mat; - handle_objects(); + if ( hasFaceVertexColor ) { - }; + for ( i = 0; i < 4; i ++ ) { - function handle_hierarchy( node, id, parent, material, obj ) { + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - var p = obj.position; - var r = obj.rotation; - var q = obj.quaternion; - var s = obj.scale; + if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) ); + if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) ); - node.position.fromArray( p ); + } - if ( q ) { + } - node.quaternion.fromArray( q ); + geometry.faces.push( faceA ); + geometry.faces.push( faceB ); } else { - node.rotation.fromArray( r ); + face = new THREE.Face3(); + face.a = faces[ offset ++ ]; + face.b = faces[ offset ++ ]; + face.c = faces[ offset ++ ]; - } + if ( hasMaterial ) { - node.scale.fromArray( s ); + materialIndex = faces[ offset ++ ]; + face.materialIndex = materialIndex; - // override children materials - // if object material was specified in JSON explicitly + } - if ( material ) { + // to get face <=> uv index correspondence - node.traverse( function ( child ) { + fi = geometry.faces.length; - child.material = material; + if ( hasFaceVertexUv ) { - } ); + for ( i = 0; i < nUvLayers; i ++ ) { - } + uvLayer = json.uvs[ i ]; - // override children visibility - // with root node visibility as specified in JSON + geometry.faceVertexUvs[ i ][ fi ] = []; - var visible = ( obj.visible !== undefined ) ? obj.visible : true; + for ( j = 0; j < 3; j ++ ) { - node.traverse( function ( child ) { + uvIndex = faces[ offset ++ ]; - child.visible = visible; + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - } ); + uv = new THREE.Vector2( u, v ); - parent.add( node ); + geometry.faceVertexUvs[ i ][ fi ].push( uv ); - node.name = id; + } - result.objects[ id ] = node; - handle_objects(); + } - }; + } - function create_callback_geometry( id ) { + if ( hasFaceNormal ) { - return function ( geo, mat ) { + normalIndex = faces[ offset ++ ] * 3; - geo.name = id; + face.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - handle_mesh( geo, mat, id ); + } - counter_models -= 1; + if ( hasFaceVertexNormal ) { - scope.onLoadComplete(); + for ( i = 0; i < 3; i ++ ) { - async_callback_gate(); + normalIndex = faces[ offset ++ ] * 3; - } + normal = new THREE.Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - }; + face.vertexNormals.push( normal ); - function create_callback_hierachy( id, parent, material, obj ) { + } - return function ( event ) { + } - var result; - // loaders which use EventDispatcher + if ( hasFaceColor ) { - if ( event.content ) { + colorIndex = faces[ offset ++ ]; + face.color.setHex( colors[ colorIndex ] ); - result = event.content; + } - // ColladaLoader - } else if ( event.dae ) { + if ( hasFaceVertexColor ) { - result = event.scene; + for ( i = 0; i < 3; i ++ ) { + colorIndex = faces[ offset ++ ]; + face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) ); - // UTF8Loader + } - } else { + } - result = event; + geometry.faces.push( face ); - } + } - handle_hierarchy( result, id, parent, material, obj ); + } - counter_models -= 1; + }; - scope.onLoadComplete(); + function parseSkin() { + var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; - async_callback_gate(); + if ( json.skinWeights ) { - } + for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { - }; + var x = json.skinWeights[ i ]; + var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0; + var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; + var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; - function create_callback_embed( id ) { + geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) ); - return function ( geo, mat ) { + } - geo.name = id; + } - result.geometries[ id ] = geo; - result.face_materials[ id ] = mat; + if ( json.skinIndices ) { - } + for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { - }; + var a = json.skinIndices[ i ]; + var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; + var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; + var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; - function async_callback_gate() { + geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) ); - var progress = { + } - totalModels : total_models, - totalTextures : total_textures, - loadedModels : total_models - counter_models, - loadedTextures : total_textures - counter_textures + } - }; + geometry.bones = json.bones; - scope.callbackProgress( progress, result ); + if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { - scope.onLoadProgress(); + console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + + geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); - if ( counter_models === 0 && counter_textures === 0 ) { + } - finalize(); - callbackFinished( result ); - } + // could change this to json.animations[0] or remove completely - }; + geometry.animation = json.animation; + geometry.animations = json.animations; - function finalize() { + }; - // take care of targets which could be asynchronously loaded objects + function parseMorphing( scale ) { - for ( var i = 0; i < target_array.length; i ++ ) { + if ( json.morphTargets !== undefined ) { - var ta = target_array[ i ]; + var i, l, v, vl, dstVertices, srcVertices; - var target = result.objects[ ta.targetName ]; + for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) { - if ( target ) { + geometry.morphTargets[ i ] = {}; + geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; + geometry.morphTargets[ i ].vertices = []; - ta.object.target = target; + dstVertices = geometry.morphTargets[ i ].vertices; + srcVertices = json.morphTargets [ i ].vertices; - } else { + for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) { - // if there was error and target of specified name doesn't exist in the scene file - // create instead dummy target - // (target must be added to scene explicitly as parent is already added) + var vertex = new THREE.Vector3(); + vertex.x = srcVertices[ v ] * scale; + vertex.y = srcVertices[ v + 1 ] * scale; + vertex.z = srcVertices[ v + 2 ] * scale; - ta.object.target = new THREE.Object3D(); - result.scene.add( ta.object.target ); + dstVertices.push( vertex ); } - ta.object.target.userData.targetInverse = ta.object; - } - }; + } - var callbackTexture = function ( count ) { + if ( json.morphColors !== undefined ) { - counter_textures -= count; - async_callback_gate(); + var i, l, c, cl, dstColors, srcColors, color; - scope.onLoadComplete(); + for ( i = 0, l = json.morphColors.length; i < l; i ++ ) { - }; + geometry.morphColors[ i ] = {}; + geometry.morphColors[ i ].name = json.morphColors[ i ].name; + geometry.morphColors[ i ].colors = []; - // must use this instead of just directly calling callbackTexture - // because of closure in the calling context loop + dstColors = geometry.morphColors[ i ].colors; + srcColors = json.morphColors [ i ].colors; - var generateTextureCallback = function ( count ) { + for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) { - return function () { + color = new THREE.Color( 0xffaa00 ); + color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] ); + dstColors.push( color ); - callbackTexture( count ); + } - }; + } - }; + } - function traverse_json_hierarchy( objJSON, callback ) { + }; - callback( objJSON ); + if ( json.materials === undefined || json.materials.length === 0 ) { - if ( objJSON.children !== undefined ) { + return { geometry: geometry }; - for ( var objChildID in objJSON.children ) { + } else { - traverse_json_hierarchy( objJSON.children[ objChildID ], callback ); + var materials = this.initMaterials( json.materials, texturePath ); - } + if ( this.needsTangents( materials ) ) { - } + geometry.computeTangents(); - }; + } - // first go synchronous elements + return { geometry: geometry, materials: materials }; - // fogs + } - var fogID, fogJSON; +}; - for ( fogID in data.fogs ) { +// File:src/loaders/LoadingManager.js - fogJSON = data.fogs[ fogID ]; +/** + * @author mrdoob / http://mrdoob.com/ + */ - if ( fogJSON.type === "linear" ) { +THREE.LoadingManager = function ( onLoad, onProgress, onError ) { - fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far ); + var scope = this; - } else if ( fogJSON.type === "exp2" ) { + var loaded = 0, total = 0; - fog = new THREE.FogExp2( 0x000000, fogJSON.density ); + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; - } + this.itemStart = function ( url ) { - color = fogJSON.color; - fog.color.setRGB( color[0], color[1], color[2] ); + total ++; - result.fogs[ fogID ] = fog; + }; - } + this.itemEnd = function ( url ) { - // now come potentially asynchronous elements + loaded ++; - // geometries + if ( scope.onProgress !== undefined ) { - // count how many geometries will be loaded asynchronously + scope.onProgress( url, loaded, total ); - var geoID, geoJSON; + } - for ( geoID in data.geometries ) { + if ( loaded === total && scope.onLoad !== undefined ) { - geoJSON = data.geometries[ geoID ]; + scope.onLoad(); - if ( geoJSON.type in this.geometryHandlers ) { + } - counter_models += 1; + }; - scope.onLoadStart(); +}; - } +THREE.DefaultLoadingManager = new THREE.LoadingManager(); - } +// File:src/loaders/BufferGeometryLoader.js - // count how many hierarchies will be loaded asynchronously +/** + * @author mrdoob / http://mrdoob.com/ + */ - for ( var objID in data.objects ) { +THREE.BufferGeometryLoader = function ( manager ) { - traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) { + this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) { +}; - counter_models += 1; +THREE.BufferGeometryLoader.prototype = { - scope.onLoadStart(); + constructor: THREE.BufferGeometryLoader, - } + load: function ( url, onLoad, onProgress, onError ) { - }); + var scope = this; - } + var loader = new THREE.XHRLoader(); + loader.setCrossOrigin( this.crossOrigin ); + loader.load( url, function ( text ) { - total_models = counter_models; + onLoad( scope.parse( JSON.parse( text ) ) ); - for ( geoID in data.geometries ) { + }, onProgress, onError ); - geoJSON = data.geometries[ geoID ]; + }, - if ( geoJSON.type === "cube" ) { + setCrossOrigin: function ( value ) { - geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; + this.crossOrigin = value; - } else if ( geoJSON.type === "plane" ) { + }, - geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; + parse: function ( json ) { - } else if ( geoJSON.type === "sphere" ) { + var geometry = new THREE.BufferGeometry(); - geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; + var attributes = json.attributes; - } else if ( geoJSON.type === "cylinder" ) { + for ( var key in attributes ) { - geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; + var attribute = attributes[ key ]; - } else if ( geoJSON.type === "torus" ) { + geometry.attributes[ key ] = { + itemSize: attribute.itemSize, + array: new self[ attribute.type ]( attribute.array ) + } - geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; + } - } else if ( geoJSON.type === "icosahedron" ) { + var offsets = json.offsets; - geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; + if ( offsets !== undefined ) { - } else if ( geoJSON.type in this.geometryHandlers ) { + geometry.offsets = JSON.parse( JSON.stringify( offsets ) ); - var loaderParameters = {}; + } - for ( var parType in geoJSON ) { + var boundingSphere = json.boundingSphere; - if ( parType !== "type" && parType !== "url" ) { + if ( boundingSphere !== undefined ) { - loaderParameters[ parType ] = geoJSON[ parType ]; + geometry.boundingSphere = new THREE.Sphere( + new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ), + boundingSphere.radius + ); - } + } - } + return geometry; - var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ]; - loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters ); + } - } else if ( geoJSON.type === "embedded" ) { +}; - var modelJson = data.embeds[ geoJSON.id ], - texture_path = ""; +// File:src/loaders/MaterialLoader.js - // pass metadata along to jsonLoader so it knows the format version +/** + * @author mrdoob / http://mrdoob.com/ + */ - modelJson.metadata = data.metadata; +THREE.MaterialLoader = function ( manager ) { - if ( modelJson ) { + this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ]; - var model = jsonLoader.parse( modelJson, texture_path ); - create_callback_embed( geoID )( model.geometry, model.materials ); +}; - } +THREE.MaterialLoader.prototype = { - } + constructor: THREE.MaterialLoader, - } + load: function ( url, onLoad, onProgress, onError ) { - // textures + var scope = this; - // count how many textures will be loaded asynchronously + var loader = new THREE.XHRLoader(); + loader.setCrossOrigin( this.crossOrigin ); + loader.load( url, function ( text ) { + + onLoad( scope.parse( JSON.parse( text ) ) ); - var textureID, textureJSON; + }, onProgress, onError ); - for ( textureID in data.textures ) { + }, - textureJSON = data.textures[ textureID ]; + setCrossOrigin: function ( value ) { - if ( textureJSON.url instanceof Array ) { + this.crossOrigin = value; - counter_textures += textureJSON.url.length; + }, - for( var n = 0; n < textureJSON.url.length; n ++ ) { + parse: function ( json ) { - scope.onLoadStart(); + var material = new THREE[ json.type ]; - } + if ( json.color !== undefined ) material.color.setHex( json.color ); + if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient ); + if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); + if ( json.specular !== undefined ) material.specular.setHex( json.specular ); + if ( json.shininess !== undefined ) material.shininess = json.shininess; + if ( json.uniforms !== undefined ) material.uniforms = json.uniforms; + if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; + if ( json.blending !== undefined ) material.blending = json.blending; + if ( json.side !== undefined ) material.side = json.side; + if ( json.opacity !== undefined ) material.opacity = json.opacity; + if ( json.transparent !== undefined ) material.transparent = json.transparent; + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; - } else { + if ( json.materials !== undefined ) { - counter_textures += 1; + for ( var i = 0, l = json.materials.length; i < l; i ++ ) { - scope.onLoadStart(); + material.materials.push( this.parse( json.materials[ i ] ) ); } } - total_textures = counter_textures; + return material; + + } - for ( textureID in data.textures ) { +}; - textureJSON = data.textures[ textureID ]; +// File:src/loaders/ObjectLoader.js - if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - textureJSON.mapping = new THREE[ textureJSON.mapping ](); +THREE.ObjectLoader = function ( manager ) { - } + this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - if ( textureJSON.url instanceof Array ) { +}; - var count = textureJSON.url.length; - var url_array = []; +THREE.ObjectLoader.prototype = { - for( var i = 0; i < count; i ++ ) { + constructor: THREE.ObjectLoader, - url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType ); + load: function ( url, onLoad, onProgress, onError ) { - } + var scope = this; - var isCompressed = /\.dds$/i.test( url_array[ 0 ] ); + var loader = new THREE.XHRLoader( scope.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.load( url, function ( text ) { - if ( isCompressed ) { + onLoad( scope.parse( JSON.parse( text ) ) ); - texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) ); + }, onProgress, onError ); - } else { + }, - texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) ); + setCrossOrigin: function ( value ) { - } + this.crossOrigin = value; - } else { + }, - var isCompressed = /\.dds$/i.test( textureJSON.url ); - var fullUrl = get_url( textureJSON.url, data.urlBaseType ); - var textureCallback = generateTextureCallback( 1 ); + parse: function ( json ) { - if ( isCompressed ) { + var geometries = this.parseGeometries( json.geometries ); + var materials = this.parseMaterials( json.materials ); + var object = this.parseObject( json.object, geometries, materials ); - texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback ); + return object; - } else { + }, - texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback ); + parseGeometries: function ( json ) { - } + var geometries = {}; - if ( THREE[ textureJSON.minFilter ] !== undefined ) - texture.minFilter = THREE[ textureJSON.minFilter ]; + if ( json !== undefined ) { - if ( THREE[ textureJSON.magFilter ] !== undefined ) - texture.magFilter = THREE[ textureJSON.magFilter ]; + var geometryLoader = new THREE.JSONLoader(); + var bufferGeometryLoader = new THREE.BufferGeometryLoader(); - if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy; + for ( var i = 0, l = json.length; i < l; i ++ ) { - if ( textureJSON.repeat ) { + var geometry; + var data = json[ i ]; - texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] ); + switch ( data.type ) { - if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping; - if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping; + case 'PlaneGeometry': - } + geometry = new THREE.PlaneGeometry( + data.width, + data.height, + data.widthSegments, + data.heightSegments + ); - if ( textureJSON.offset ) { + break; - texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] ); + case 'BoxGeometry': + case 'CubeGeometry': // backwards compatible - } + geometry = new THREE.BoxGeometry( + data.width, + data.height, + data.depth, + data.widthSegments, + data.heightSegments, + data.depthSegments + ); - // handle wrap after repeat so that default repeat can be overriden + break; - if ( textureJSON.wrap ) { + case 'CircleGeometry': - var wrapMap = { - "repeat": THREE.RepeatWrapping, - "mirror": THREE.MirroredRepeatWrapping - } + geometry = new THREE.CircleGeometry( + data.radius, + data.segments + ); - if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ]; - if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ]; + break; - } + case 'CylinderGeometry': - } + geometry = new THREE.CylinderGeometry( + data.radiusTop, + data.radiusBottom, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded + ); - result.textures[ textureID ] = texture; + break; - } + case 'SphereGeometry': - // materials + geometry = new THREE.SphereGeometry( + data.radius, + data.widthSegments, + data.heightSegments, + data.phiStart, + data.phiLength, + data.thetaStart, + data.thetaLength + ); - var matID, matJSON; - var parID; + break; - for ( matID in data.materials ) { + case 'IcosahedronGeometry': - matJSON = data.materials[ matID ]; + geometry = new THREE.IcosahedronGeometry( + data.radius, + data.detail + ); - for ( parID in matJSON.parameters ) { + break; - if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) { + case 'TorusGeometry': - matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ]; + geometry = new THREE.TorusGeometry( + data.radius, + data.tube, + data.radialSegments, + data.tubularSegments, + data.arc + ); - } else if ( parID === "shading" ) { + break; - matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading; + case 'TorusKnotGeometry': - } else if ( parID === "side" ) { + geometry = new THREE.TorusKnotGeometry( + data.radius, + data.tube, + data.radialSegments, + data.tubularSegments, + data.p, + data.q, + data.heightScale + ); - if ( matJSON.parameters[ parID ] == "double" ) { + break; - matJSON.parameters[ parID ] = THREE.DoubleSide; + case 'BufferGeometry': - } else if ( matJSON.parameters[ parID ] == "back" ) { + geometry = bufferGeometryLoader.parse( data.data ); - matJSON.parameters[ parID ] = THREE.BackSide; + break; - } else { + case 'Geometry': - matJSON.parameters[ parID ] = THREE.FrontSide; + geometry = geometryLoader.parse( data.data ).geometry; - } + break; - } else if ( parID === "blending" ) { + } - matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending; + geometry.uuid = data.uuid; - } else if ( parID === "combine" ) { + if ( data.name !== undefined ) geometry.name = data.name; - matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation; + geometries[ data.uuid ] = geometry; - } else if ( parID === "vertexColors" ) { + } - if ( matJSON.parameters[ parID ] == "face" ) { + } - matJSON.parameters[ parID ] = THREE.FaceColors; + return geometries; - // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false + }, - } else if ( matJSON.parameters[ parID ] ) { + parseMaterials: function ( json ) { - matJSON.parameters[ parID ] = THREE.VertexColors; + var materials = {}; - } + if ( json !== undefined ) { - } else if ( parID === "wrapRGB" ) { + var loader = new THREE.MaterialLoader(); - var v3 = matJSON.parameters[ parID ]; - matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] ); + for ( var i = 0, l = json.length; i < l; i ++ ) { - } + var data = json[ i ]; + var material = loader.parse( data ); - } + material.uuid = data.uuid; - if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) { + if ( data.name !== undefined ) material.name = data.name; - matJSON.parameters.transparent = true; + materials[ data.uuid ] = material; } - if ( matJSON.parameters.normalMap ) { + } - var shader = THREE.ShaderLib[ "normalmap" ]; - var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); + return materials; - var diffuse = matJSON.parameters.color; - var specular = matJSON.parameters.specular; - var ambient = matJSON.parameters.ambient; - var shininess = matJSON.parameters.shininess; + }, - uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ]; + parseObject: function () { - if ( matJSON.parameters.normalScale ) { + var matrix = new THREE.Matrix4(); - uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] ); + return function ( data, geometries, materials ) { - } + var object; - if ( matJSON.parameters.map ) { + switch ( data.type ) { - uniforms[ "tDiffuse" ].value = matJSON.parameters.map; - uniforms[ "enableDiffuse" ].value = true; + case 'Scene': - } + object = new THREE.Scene(); - if ( matJSON.parameters.envMap ) { + break; - uniforms[ "tCube" ].value = matJSON.parameters.envMap; - uniforms[ "enableReflection" ].value = true; - uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity; + case 'PerspectiveCamera': - } + object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); - if ( matJSON.parameters.lightMap ) { + break; - uniforms[ "tAO" ].value = matJSON.parameters.lightMap; - uniforms[ "enableAO" ].value = true; + case 'OrthographicCamera': - } + object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); - if ( matJSON.parameters.specularMap ) { + break; - uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ]; - uniforms[ "enableSpecular" ].value = true; + case 'AmbientLight': - } + object = new THREE.AmbientLight( data.color ); - if ( matJSON.parameters.displacementMap ) { + break; - uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ]; - uniforms[ "enableDisplacement" ].value = true; + case 'DirectionalLight': - uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias; - uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale; + object = new THREE.DirectionalLight( data.color, data.intensity ); - } + break; - uniforms[ "diffuse" ].value.setHex( diffuse ); - uniforms[ "specular" ].value.setHex( specular ); - uniforms[ "ambient" ].value.setHex( ambient ); + case 'PointLight': - uniforms[ "shininess" ].value = shininess; + object = new THREE.PointLight( data.color, data.intensity, data.distance ); - if ( matJSON.parameters.opacity ) { + break; - uniforms[ "opacity" ].value = matJSON.parameters.opacity; + case 'SpotLight': - } + object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent ); - var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true }; + break; - material = new THREE.ShaderMaterial( parameters ); + case 'HemisphereLight': - } else { + object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); - material = new THREE[ matJSON.type ]( matJSON.parameters ); + break; - } + case 'Mesh': - material.name = matID; + var geometry = geometries[ data.geometry ]; + var material = materials[ data.material ]; - result.materials[ matID ] = material; + if ( geometry === undefined ) { - } + console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry ); - // second pass through all materials to initialize MeshFaceMaterials - // that could be referring to other materials out of order + } - for ( matID in data.materials ) { + if ( material === undefined ) { - matJSON = data.materials[ matID ]; + console.error( 'THREE.ObjectLoader: Undefined material ' + data.material ); - if ( matJSON.parameters.materials ) { + } - var materialArray = []; + object = new THREE.Mesh( geometry, material ); - for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) { + break; - var label = matJSON.parameters.materials[ i ]; - materialArray.push( result.materials[ label ] ); + case 'Sprite': - } + var material = materials[ data.material ]; - result.materials[ matID ].materials = materialArray; + if ( material === undefined ) { - } + console.error( 'THREE.ObjectLoader: Undefined material ' + data.material ); - } + } - // objects ( synchronous init of procedural primitives ) + object = new THREE.Sprite( material ); - handle_objects(); + break; - // defaults + default: - if ( result.cameras && data.defaults.camera ) { + object = new THREE.Object3D(); - result.currentCamera = result.cameras[ data.defaults.camera ]; + } - } + object.uuid = data.uuid; - if ( result.fogs && data.defaults.fog ) { + if ( data.name !== undefined ) object.name = data.name; + if ( data.matrix !== undefined ) { - result.scene.fog = result.fogs[ data.defaults.fog ]; + matrix.fromArray( data.matrix ); + matrix.decompose( object.position, object.quaternion, object.scale ); - } + } else { - // synchronous callback + if ( data.position !== undefined ) object.position.fromArray( data.position ); + if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); + if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); - scope.callbackSync( result ); + } - // just in case there are no async elements + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.userData !== undefined ) object.userData = data.userData; - async_callback_gate(); + if ( data.children !== undefined ) { - } + for ( var child in data.children ) { -} + object.add( this.parseObject( data.children[ child ], geometries, materials ) ); + + } + + } + + return object; + + } + + }() + +}; + +// File:src/loaders/TextureLoader.js /** * @author mrdoob / http://mrdoob.com/ @@ -14259,7 +13013,7 @@ THREE.TextureLoader.prototype = { } - } ); + }, onProgress, onError ); }, @@ -14271,6 +13025,8 @@ THREE.TextureLoader.prototype = { }; +// File:src/materials/Material.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -14325,7 +13081,7 @@ THREE.Material.prototype = { if ( newValue === undefined ) { - console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' ); + console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); continue; } @@ -14342,10 +13098,10 @@ THREE.Material.prototype = { currentValue.copy( newValue ); - } else if ( key == 'overdraw') { + } else if ( key == 'overdraw' ) { // ensure overdraw is backwards-compatable with legacy boolean type - this[ key ] = Number(newValue); + this[ key ] = Number( newValue ); } else { @@ -14405,6 +13161,8 @@ THREE.EventDispatcher.prototype.apply( THREE.Material.prototype ); THREE.MaterialIdCount = 0; +// File:src/materials/LineBasicMaterial.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -14437,7 +13195,7 @@ THREE.LineBasicMaterial = function ( parameters ) { this.linecap = 'round'; this.linejoin = 'round'; - this.vertexColors = false; + this.vertexColors = THREE.NoColors; this.fog = true; @@ -14467,6 +13225,8 @@ THREE.LineBasicMaterial.prototype.clone = function () { }; +// File:src/materials/LineDashedMaterial.js + /** * @author alteredq / http://alteredqualia.com/ * @@ -14534,6 +13294,8 @@ THREE.LineDashedMaterial.prototype.clone = function () { }; +// File:src/materials/MeshBasicMaterial.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -14547,6 +13309,8 @@ THREE.LineDashedMaterial.prototype.clone = function () { * * specularMap: new THREE.Texture( ), * + * alphaMap: new THREE.Texture( ), + * * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , @@ -14581,6 +13345,8 @@ THREE.MeshBasicMaterial = function ( parameters ) { this.specularMap = null; + this.alphaMap = null; + this.envMap = null; this.combine = THREE.MultiplyOperation; this.reflectivity = 1; @@ -14620,6 +13386,8 @@ THREE.MeshBasicMaterial.prototype.clone = function () { material.specularMap = this.specularMap; + material.alphaMap = this.alphaMap; + material.envMap = this.envMap; material.combine = this.combine; material.reflectivity = this.reflectivity; @@ -14643,6 +13411,8 @@ THREE.MeshBasicMaterial.prototype.clone = function () { }; +// File:src/materials/MeshLambertMaterial.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -14659,6 +13429,8 @@ THREE.MeshBasicMaterial.prototype.clone = function () { * * specularMap: new THREE.Texture( ), * + * alphaMap: new THREE.Texture( ), + * * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , @@ -14699,6 +13471,8 @@ THREE.MeshLambertMaterial = function ( parameters ) { this.specularMap = null; + this.alphaMap = null; + this.envMap = null; this.combine = THREE.MultiplyOperation; this.reflectivity = 1; @@ -14744,6 +13518,8 @@ THREE.MeshLambertMaterial.prototype.clone = function () { material.specularMap = this.specularMap; + material.alphaMap = this.alphaMap; + material.envMap = this.envMap; material.combine = this.combine; material.reflectivity = this.reflectivity; @@ -14768,6 +13544,8 @@ THREE.MeshLambertMaterial.prototype.clone = function () { }; +// File:src/materials/MeshPhongMaterial.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -14792,6 +13570,8 @@ THREE.MeshLambertMaterial.prototype.clone = function () { * * specularMap: new THREE.Texture( ), * + * alphaMap: new THREE.Texture( ), + * * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , @@ -14842,6 +13622,8 @@ THREE.MeshPhongMaterial = function ( parameters ) { this.specularMap = null; + this.alphaMap = null; + this.envMap = null; this.combine = THREE.MultiplyOperation; this.reflectivity = 1; @@ -14897,6 +13679,8 @@ THREE.MeshPhongMaterial.prototype.clone = function () { material.specularMap = this.specularMap; + material.alphaMap = this.alphaMap; + material.envMap = this.envMap; material.combine = this.combine; material.reflectivity = this.reflectivity; @@ -14921,6 +13705,8 @@ THREE.MeshPhongMaterial.prototype.clone = function () { }; +// File:src/materials/MeshDepthMaterial.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -14964,6 +13750,8 @@ THREE.MeshDepthMaterial.prototype.clone = function () { }; +// File:src/materials/MeshNormalMaterial.js + /** * @author mrdoob / http://mrdoob.com/ * @@ -15012,6 +13800,8 @@ THREE.MeshNormalMaterial.prototype.clone = function () { }; +// File:src/materials/MeshFaceMaterial.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -15036,6 +13826,8 @@ THREE.MeshFaceMaterial.prototype.clone = function () { }; +// File:src/materials/PointCloudMaterial.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -15057,7 +13849,7 @@ THREE.MeshFaceMaterial.prototype.clone = function () { * } */ -THREE.ParticleSystemMaterial = function ( parameters ) { +THREE.PointCloudMaterial = function ( parameters ) { THREE.Material.call( this ); @@ -15068,7 +13860,7 @@ THREE.ParticleSystemMaterial = function ( parameters ) { this.size = 1; this.sizeAttenuation = true; - this.vertexColors = false; + this.vertexColors = THREE.NoColors; this.fog = true; @@ -15076,11 +13868,11 @@ THREE.ParticleSystemMaterial = function ( parameters ) { }; -THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype ); +THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.ParticleSystemMaterial.prototype.clone = function () { +THREE.PointCloudMaterial.prototype.clone = function () { - var material = new THREE.ParticleSystemMaterial(); + var material = new THREE.PointCloudMaterial(); THREE.Material.prototype.clone.call( this, material ); @@ -15101,18 +13893,31 @@ THREE.ParticleSystemMaterial.prototype.clone = function () { // backwards compatibility -THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial; +THREE.ParticleBasicMaterial = function ( parameters ) { + + console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointCloudMaterial.' ); + return new THREE.PointCloudMaterial( parameters ); + +}; + +THREE.ParticleSystemMaterial = function ( parameters ) { + + console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' ); + return new THREE.PointCloudMaterial( parameters ); + +}; + +// File:src/materials/ShaderMaterial.js /** * @author alteredq / http://alteredqualia.com/ * * parameters = { - * fragmentShader: , - * vertexShader: , - * + * defines: { "label" : "value" }, * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } }, * - * defines: { "label" : "value" }, + * fragmentShader: , + * vertexShader: , * * shading: THREE.SmoothShading, * blending: THREE.NormalBlending, @@ -15138,12 +13943,13 @@ THREE.ShaderMaterial = function ( parameters ) { THREE.Material.call( this ); - this.fragmentShader = "void main() {}"; - this.vertexShader = "void main() {}"; - this.uniforms = {}; this.defines = {}; + this.uniforms = {}; this.attributes = null; + this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}'; + this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}'; + this.shading = THREE.SmoothShading; this.linewidth = 1; @@ -15165,9 +13971,9 @@ THREE.ShaderMaterial = function ( parameters ) { // When rendered geometry doesn't include these attributes but the material does, // use these default values in WebGL. This avoids errors when buffer data is missing. this.defaultAttributeValues = { - "color" : [ 1, 1, 1 ], - "uv" : [ 0, 0 ], - "uv2" : [ 0, 0 ] + 'color': [ 1, 1, 1 ], + 'uv': [ 0, 0 ], + 'uv2': [ 0, 0 ] }; this.index0AttributeName = undefined; @@ -15212,6 +14018,8 @@ THREE.ShaderMaterial.prototype.clone = function () { }; +// File:src/materials/RawShaderMaterial.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -15234,6 +14042,8 @@ THREE.RawShaderMaterial.prototype.clone = function () { }; +// File:src/materials/SpriteMaterial.js + /** * @author alteredq / http://alteredqualia.com/ * @@ -15291,6 +14101,8 @@ THREE.SpriteMaterial.prototype.clone = function () { }; +// File:src/materials/SpriteCanvasMaterial.js + /** * @author mrdoob / http://mrdoob.com/ * @@ -15331,6 +14143,9 @@ THREE.SpriteCanvasMaterial.prototype.clone = function () { // backwards compatibility THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial; + +// File:src/textures/Texture.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -15344,10 +14159,10 @@ THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, f this.name = ''; - this.image = image; + this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE; this.mipmaps = []; - this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping(); + this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING; this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping; this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping; @@ -15373,6 +14188,9 @@ THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, f }; +THREE.Texture.DEFAULT_IMAGE = undefined; +THREE.Texture.DEFAULT_MAPPING = new THREE.UVMapping(); + THREE.Texture.prototype = { constructor: THREE.Texture, @@ -15396,7 +14214,7 @@ THREE.Texture.prototype = { if ( texture === undefined ) texture = new THREE.Texture(); texture.image = this.image; - texture.mipmaps = this.mipmaps.slice(0); + texture.mipmaps = this.mipmaps.slice( 0 ); texture.mapping = this.mapping; @@ -15441,6 +14259,36 @@ THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype ); THREE.TextureIdCount = 0; +// File:src/textures/CubeTexture.js + +/** + * @author mrdoob / http://mrdoob.com/ + */ + +THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.images = images; + +}; + +THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype ); + +THREE.CubeTexture.clone = function ( texture ) { + + if ( texture === undefined ) texture = new THREE.CubeTexture(); + + THREE.Texture.prototype.clone.call( this, texture ); + + texture.images = this.images; + + return texture; + +}; + +// File:src/textures/CompressedTexture.js + /** * @author alteredq / http://alteredqualia.com/ */ @@ -15468,6 +14316,8 @@ THREE.CompressedTexture.prototype.clone = function () { }; +// File:src/textures/DataTexture.js + /** * @author alteredq / http://alteredqualia.com/ */ @@ -15492,27 +14342,159 @@ THREE.DataTexture.prototype.clone = function () { }; +// File:src/objects/PointCloud.js + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.ParticleSystem = function ( geometry, material ) { +THREE.PointCloud = function ( geometry, material ) { THREE.Object3D.call( this ); this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); - this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } ); + this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } ); this.sortParticles = false; - this.frustumCulled = false; }; -THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype ); +THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype ); + +THREE.PointCloud.prototype.raycast = ( function () { + + var inverseMatrix = new THREE.Matrix4(); + var ray = new THREE.Ray(); + + return function ( raycaster, intersects ) { + + var object = this; + var geometry = object.geometry; + var threshold = raycaster.params.PointCloud.threshold; + + inverseMatrix.getInverse( this.matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + + if ( geometry.boundingBox !== null ) { + + if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) { + + return; + + } + + } + + var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + var position = new THREE.Vector3(); + + var testPoint = function ( point, index ) { + + var rayPointDistance = ray.distanceToPoint( point ); + + if ( rayPointDistance < localThreshold ) { + + var intersectPoint = ray.closestPointToPoint( point ); + intersectPoint.applyMatrix4( object.matrixWorld ); + + var distance = raycaster.ray.origin.distanceTo( intersectPoint ); + + intersects.push( { + + distance: distance, + distanceToRay: rayPointDistance, + point: intersectPoint.clone(), + index: index, + face: null, + object: object + + } ); + + } + + }; + + if ( geometry instanceof THREE.BufferGeometry ) { + + var attributes = geometry.attributes; + var positions = attributes.position.array; + + if ( attributes.index !== undefined ) { + + var indices = attributes.index.array; + var offsets = geometry.offsets; + + if ( offsets.length === 0 ) { + + var offset = { + start: 0, + count: indices.length, + index: 0 + }; + + offsets = [ offset ]; + + } + + for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) { + + var start = offsets[ oi ].start; + var count = offsets[ oi ].count; + var index = offsets[ oi ].index; + + for ( var i = start, il = start + count; i < il; i ++ ) { + + var a = index + indices[ i ]; + + position.set( + positions[ a * 3 ], + positions[ a * 3 + 1 ], + positions[ a * 3 + 2 ] + ); + + testPoint( position, a ); + + } + + } + + } else { + + var pointCount = positions.length / 3; + + for ( var i = 0; i < pointCount; i ++ ) { + + position.set( + positions[ 3 * i ], + positions[ 3 * i + 1 ], + positions[ 3 * i + 2 ] + ); + + testPoint( position, i ); + + } + + } -THREE.ParticleSystem.prototype.clone = function ( object ) { + } else { + + var vertices = this.geometry.vertices; + + for ( var i = 0; i < vertices.length; i ++ ) { + + testPoint( vertices[ i ], i ); + + } + + } - if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material ); + }; + +}() ); + +THREE.PointCloud.prototype.clone = function ( object ) { + + if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material ); object.sortParticles = this.sortParticles; @@ -15522,6 +14504,17 @@ THREE.ParticleSystem.prototype.clone = function ( object ) { }; +// Backwards compatibility + +THREE.ParticleSystem = function ( geometry, material ) { + + console.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' ); + return new THREE.PointCloud( geometry, material ); + +}; + +// File:src/objects/Line.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -15542,6 +14535,75 @@ THREE.LinePieces = 1; THREE.Line.prototype = Object.create( THREE.Object3D.prototype ); +THREE.Line.prototype.raycast = ( function () { + + var inverseMatrix = new THREE.Matrix4(); + var ray = new THREE.Ray(); + var sphere = new THREE.Sphere(); + + return function ( raycaster, intersects ) { + + var precision = raycaster.linePrecision; + var precisionSq = precision * precision; + + var geometry = this.geometry; + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + // Checking boundingSphere distance to ray + + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( this.matrixWorld ); + + if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { + + return; + + } + + inverseMatrix.getInverse( this.matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + + /* if ( geometry instanceof THREE.BufferGeometry ) { + + } else */ if ( geometry instanceof THREE.Geometry ) { + + var vertices = geometry.vertices; + var nbVertices = vertices.length; + var interSegment = new THREE.Vector3(); + var interRay = new THREE.Vector3(); + var step = this.type === THREE.LineStrip ? 1 : 2; + + for ( var i = 0; i < nbVertices - 1; i = i + step ) { + + var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); + + if ( distSq > precisionSq ) continue; + + var distance = ray.origin.distanceTo( interRay ); + + if ( distance < raycaster.near || distance > raycaster.far ) continue; + + intersects.push( { + + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + face: null, + faceIndex: null, + object: this + + } ); + + } + + } + + }; + +}() ); + THREE.Line.prototype.clone = function ( object ) { if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type ); @@ -15552,6 +14614,8 @@ THREE.Line.prototype.clone = function ( object ) { }; +// File:src/objects/Mesh.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -15576,7 +14640,7 @@ THREE.Mesh.prototype.updateMorphTargets = function () { if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { - this.morphTargetBase = -1; + this.morphTargetBase = - 1; this.morphTargetForcedOrder = []; this.morphTargetInfluences = []; this.morphTargetDictionary = {}; @@ -15600,506 +14664,814 @@ THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) { } - console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." ); + console.log( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); return 0; }; -THREE.Mesh.prototype.clone = function ( object, recursive ) { - if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material ); +THREE.Mesh.prototype.raycast = ( function () { - THREE.Object3D.prototype.clone.call( this, object, recursive ); + var inverseMatrix = new THREE.Matrix4(); + var ray = new THREE.Ray(); + var sphere = new THREE.Sphere(); - return object; + var vA = new THREE.Vector3(); + var vB = new THREE.Vector3(); + var vC = new THREE.Vector3(); -}; + return function ( raycaster, intersects ) { -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + var geometry = this.geometry; -THREE.Bone = function( belongsToSkin ) { + // Checking boundingSphere distance to ray - THREE.Object3D.call( this ); + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - this.skin = belongsToSkin; - this.skinMatrix = new THREE.Matrix4(); + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( this.matrixWorld ); - this.accumulatedRotWeight = 0; - this.accumulatedPosWeight = 0; - this.accumulatedSclWeight = 0; + if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { -}; + return; -THREE.Bone.prototype = Object.create( THREE.Object3D.prototype ); + } -THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) { + // Check boundingBox before continuing - // update local + inverseMatrix.getInverse( this.matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - if ( this.matrixAutoUpdate ) { + if ( geometry.boundingBox !== null ) { - forceUpdate |= this.updateMatrix(); + if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) { - } + return; - // update skin matrix + } - if ( forceUpdate || this.matrixWorldNeedsUpdate ) { + } - if ( parentSkinMatrix ) { + if ( geometry instanceof THREE.BufferGeometry ) { - this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix ); + var material = this.material; - } else { + if ( material === undefined ) return; - this.skinMatrix.copy( this.matrix ); + var attributes = geometry.attributes; - } + var a, b, c; + var precision = raycaster.precision; - this.matrixWorldNeedsUpdate = false; - forceUpdate = true; + if ( attributes.index !== undefined ) { - // Reset weights to be re-accumulated in the next frame + var indices = attributes.index.array; + var positions = attributes.position.array; + var offsets = geometry.offsets; - this.accumulatedRotWeight = 0; - this.accumulatedPosWeight = 0; - this.accumulatedSclWeight = 0; + if ( offsets.length === 0 ) { - } + offsets = [ { start: 0, count: indices.length, index: 0 } ]; - // update children + } - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) { - this.children[ i ].update( this.skinMatrix, forceUpdate ); + var start = offsets[ oi ].start; + var count = offsets[ oi ].count; + var index = offsets[ oi ].index; - } - -}; + for ( var i = start, il = start + count; i < il; i += 3 ) { + a = index + indices[ i ]; + b = index + indices[ i + 1 ]; + c = index + indices[ i + 2 ]; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author michael guerrero / http://realitymeltdown.com - */ + vA.set( + positions[ a * 3 ], + positions[ a * 3 + 1 ], + positions[ a * 3 + 2 ] + ); + vB.set( + positions[ b * 3 ], + positions[ b * 3 + 1 ], + positions[ b * 3 + 2 ] + ); + vC.set( + positions[ c * 3 ], + positions[ c * 3 + 1 ], + positions[ c * 3 + 2 ] + ); -THREE.Skeleton = function ( boneList, useVertexTexture ) { - this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; + if ( material.side === THREE.BackSide ) { - // init bones + var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true ); - this.bones = []; - this.boneMatrices = []; + } else { - var bone, gbone, p, q, s; + var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); - if ( boneList !== undefined ) { + } - for ( var b = 0; b < boneList.length; ++b ) { + if ( intersectionPoint === null ) continue; - gbone = boneList[ b ]; + intersectionPoint.applyMatrix4( this.matrixWorld ); - p = gbone.pos; - q = gbone.rotq; - s = gbone.scl; + var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - bone = this.addBone(); + if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - bone.name = gbone.name; - bone.position.set( p[0], p[1], p[2] ); - bone.quaternion.set( q[0], q[1], q[2], q[3] ); + intersects.push( { - if ( s !== undefined ) { + distance: distance, + point: intersectionPoint, + indices: [ a, b, c ], + face: null, + faceIndex: null, + object: this - bone.scale.set( s[0], s[1], s[2] ); + } ); - } else { + } - bone.scale.set( 1, 1, 1 ); + } - } + } else { - } + var positions = attributes.position.array; - for ( var b = 0; b < boneList.length; ++b ) { + for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) { - gbone = boneList[ b ]; + a = i; + b = i + 1; + c = i + 2; - if ( gbone.parent !== -1 ) { + vA.set( + positions[ j ], + positions[ j + 1 ], + positions[ j + 2 ] + ); + vB.set( + positions[ j + 3 ], + positions[ j + 4 ], + positions[ j + 5 ] + ); + vC.set( + positions[ j + 6 ], + positions[ j + 7 ], + positions[ j + 8 ] + ); - this.bones[ gbone.parent ].add( this.bones[ b ] ); - } + if ( material.side === THREE.BackSide ) { - } + var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true ); - // + } else { - var nBones = this.bones.length; + var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); - if ( this.useVertexTexture ) { + } - // layout (1 matrix = 4 pixels) - // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) - // with 8x8 pixel texture max 16 bones (8 * 8 / 4) - // 16x16 pixel texture max 64 bones (16 * 16 / 4) - // 32x32 pixel texture max 256 bones (32 * 32 / 4) - // 64x64 pixel texture max 1024 bones (64 * 64 / 4) + if ( intersectionPoint === null ) continue; - var size; + intersectionPoint.applyMatrix4( this.matrixWorld ); - if ( nBones > 256 ) - size = 64; - else if ( nBones > 64 ) - size = 32; - else if ( nBones > 16 ) - size = 16; - else - size = 8; + var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - this.boneTextureWidth = size; - this.boneTextureHeight = size; + if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel - this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType ); - this.boneTexture.minFilter = THREE.NearestFilter; - this.boneTexture.magFilter = THREE.NearestFilter; - this.boneTexture.generateMipmaps = false; - this.boneTexture.flipY = false; + intersects.push( { - } else { + distance: distance, + point: intersectionPoint, + indices: [ a, b, c ], + face: null, + faceIndex: null, + object: this - this.boneMatrices = new Float32Array( 16 * nBones ); + } ); - } + } - } + } -}; + } else if ( geometry instanceof THREE.Geometry ) { + var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial; + var objectMaterials = isFaceMaterial === true ? this.material.materials : null; -THREE.Skeleton.prototype = Object.create( THREE.Mesh.prototype ); + var a, b, c, d; + var precision = raycaster.precision; + var vertices = geometry.vertices; -THREE.Skeleton.prototype.addBone = function( bone ) { + for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { - if ( bone === undefined ) { + var face = geometry.faces[ f ]; - bone = new THREE.Bone( this ); + var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material; - } + if ( material === undefined ) continue; - this.bones.push( bone ); + a = vertices[ face.a ]; + b = vertices[ face.b ]; + c = vertices[ face.c ]; - return bone; + if ( material.morphTargets === true ) { -}; + var morphTargets = geometry.morphTargets; + var morphInfluences = this.morphTargetInfluences; + vA.set( 0, 0, 0 ); + vB.set( 0, 0, 0 ); + vC.set( 0, 0, 0 ); -THREE.Skeleton.prototype.calculateInverses = function( bone ) { + for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { - this.boneInverses = []; + var influence = morphInfluences[ t ]; - for ( var b = 0, bl = this.bones.length; b < bl; ++b ) { + if ( influence === 0 ) continue; - var inverse = new THREE.Matrix4(); + var targets = morphTargets[ t ].vertices; - inverse.getInverse( this.bones[ b ].skinMatrix ); + vA.x += ( targets[ face.a ].x - a.x ) * influence; + vA.y += ( targets[ face.a ].y - a.y ) * influence; + vA.z += ( targets[ face.a ].z - a.z ) * influence; - this.boneInverses.push( inverse ); + vB.x += ( targets[ face.b ].x - b.x ) * influence; + vB.y += ( targets[ face.b ].y - b.y ) * influence; + vB.z += ( targets[ face.b ].z - b.z ) * influence; - } + vC.x += ( targets[ face.c ].x - c.x ) * influence; + vC.y += ( targets[ face.c ].y - c.y ) * influence; + vC.z += ( targets[ face.c ].z - c.z ) * influence; -}; + } -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + vA.add( a ); + vB.add( b ); + vC.add( c ); -THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { + a = vA; + b = vB; + c = vC; - THREE.Mesh.call( this, geometry, material ); + } - this.skeleton = new THREE.Skeleton( this.geometry && this.geometry.bones, useVertexTexture ); + if ( material.side === THREE.BackSide ) { - // Add root level bones as children of the mesh + var intersectionPoint = ray.intersectTriangle( c, b, a, true ); - for ( var b = 0; b < this.skeleton.bones.length; ++b ) { + } else { - var bone = this.skeleton.bones[ b ]; + var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide ); - if ( bone.parent === undefined ) { + } - this.add( bone ); + if ( intersectionPoint === null ) continue; - } + intersectionPoint.applyMatrix4( this.matrixWorld ); - } + var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - this.identityMatrix = new THREE.Matrix4(); + if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - this.pose(); + intersects.push( { -}; + distance: distance, + point: intersectionPoint, + face: face, + faceIndex: f, + object: this + } ); -THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype ); + } -THREE.SkinnedMesh.prototype.updateMatrixWorld = function () { + } - var offsetMatrix = new THREE.Matrix4(); + }; - return function ( force ) { +}() ); - this.matrixAutoUpdate && this.updateMatrix(); +THREE.Mesh.prototype.clone = function ( object, recursive ) { - // update matrixWorld + if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material ); - if ( this.matrixWorldNeedsUpdate || force ) { + THREE.Object3D.prototype.clone.call( this, object, recursive ); - if ( this.parent ) { + return object; - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); +}; - } else { +// File:src/objects/Bone.js - this.matrixWorld.copy( this.matrix ); +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - } +THREE.Bone = function ( belongsToSkin ) { - this.matrixWorldNeedsUpdate = false; + THREE.Object3D.call( this ); - force = true; + this.skin = belongsToSkin; - } + this.accumulatedRotWeight = 0; + this.accumulatedPosWeight = 0; + this.accumulatedSclWeight = 0; - // update children +}; - for ( var i = 0, l = this.children.length; i < l; i ++ ) { +THREE.Bone.prototype = Object.create( THREE.Object3D.prototype ); - var child = this.children[ i ]; +THREE.Bone.prototype.updateMatrixWorld = function ( force ) { - if ( child instanceof THREE.Bone ) { + THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); - child.update( this.identityMatrix, false ); + // Reset weights to be re-accumulated in the next frame - } else { + this.accumulatedRotWeight = 0; + this.accumulatedPosWeight = 0; + this.accumulatedSclWeight = 0; - child.updateMatrixWorld( true ); +}; - } - } +// File:src/objects/Skeleton.js - // make a snapshot of the bones' rest position +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author michael guerrero / http://realitymeltdown.com + * @author ikerr / http://verold.com + */ - if ( this.skeleton.boneInverses === undefined ) { +THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { - this.skeleton.calculateInverses(); + this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; - } + this.identityMatrix = new THREE.Matrix4(); - // flatten bone matrices to array + // copy the bone array - for ( var b = 0, bl = this.skeleton.bones.length; b < bl; b ++ ) { + bones = bones || []; - // compute the offset between the current and the original transform; + this.bones = bones.slice( 0 ); - // TODO: we could get rid of this multiplication step if the skinMatrix - // was already representing the offset; however, this requires some - // major changes to the animation system + // create a bone texture or an array of floats - offsetMatrix.multiplyMatrices( this.skeleton.bones[ b ].skinMatrix, this.skeleton.boneInverses[ b ] ); - offsetMatrix.flattenToArrayOffset( this.skeleton.boneMatrices, b * 16 ); + if ( this.useVertexTexture ) { - } + // layout (1 matrix = 4 pixels) + // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) + // with 8x8 pixel texture max 16 bones (8 * 8 / 4) + // 16x16 pixel texture max 64 bones (16 * 16 / 4) + // 32x32 pixel texture max 256 bones (32 * 32 / 4) + // 64x64 pixel texture max 1024 bones (64 * 64 / 4) - if ( this.skeleton.useVertexTexture ) { + var size; - this.skeleton.boneTexture.needsUpdate = true; + if ( this.bones.length > 256 ) + size = 64; + else if ( this.bones.length > 64 ) + size = 32; + else if ( this.bones.length > 16 ) + size = 16; + else + size = 8; - } + this.boneTextureWidth = size; + this.boneTextureHeight = size; - }; + this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel + this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType ); + this.boneTexture.minFilter = THREE.NearestFilter; + this.boneTexture.magFilter = THREE.NearestFilter; + this.boneTexture.generateMipmaps = false; + this.boneTexture.flipY = false; -}(); + } else { -THREE.SkinnedMesh.prototype.pose = function () { + this.boneMatrices = new Float32Array( 16 * this.bones.length ); - this.updateMatrixWorld( true ); + } - this.normalizeSkinWeights(); + // use the supplied bone inverses or calculate the inverses -}; + if ( boneInverses === undefined ) { -THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () { + this.calculateInverses(); - if ( this.geometry instanceof THREE.Geometry ) { + } else { - for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) { + if ( this.bones.length === boneInverses.length ) { - var sw = this.geometry.skinWeights[ i ]; + this.boneInverses = boneInverses.slice( 0 ); - var scale = 1.0 / sw.lengthManhattan(); + } else { - if ( scale !== Infinity ) { + console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); - sw.multiplyScalar( scale ); + this.boneInverses = []; - } else { + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - sw.set( 1 ); // this will be normalized by the shader anyway + this.boneInverses.push( new THREE.Matrix4() ); } } - } else { - - // skinning weights assumed to be normalized for THREE.BufferGeometry - } }; -THREE.SkinnedMesh.prototype.clone = function ( object ) { +THREE.Skeleton.prototype.calculateInverses = function () { - if ( object === undefined ) { + this.boneInverses = []; - object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture ); + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - } + var inverse = new THREE.Matrix4(); - THREE.Mesh.prototype.clone.call( this, object ); + if ( this.bones[ b ] ) { - return object; + inverse.getInverse( this.bones[ b ].matrixWorld ); -}; + } -/** - * @author alteredq / http://alteredqualia.com/ - */ + this.boneInverses.push( inverse ); -THREE.MorphAnimMesh = function ( geometry, material ) { + } - THREE.Mesh.call( this, geometry, material ); +}; - // API +THREE.Skeleton.prototype.pose = function () { - this.duration = 1000; // milliseconds - this.mirroredLoop = false; - this.time = 0; + var bone; - // internals + // recover the bind-time world matrices - this.lastKeyframe = 0; - this.currentKeyframe = 0; + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - this.direction = 1; - this.directionBackwards = false; + bone = this.bones[ b ]; - this.setFrameRange( 0, this.geometry.morphTargets.length - 1 ); + if ( bone ) { -}; + bone.matrixWorld.getInverse( this.boneInverses[ b ] ); -THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype ); + } -THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) { + } - this.startKeyframe = start; - this.endKeyframe = end; + // compute the local matrices, positions, rotations and scales - this.length = this.endKeyframe - this.startKeyframe + 1; + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { -}; + bone = this.bones[ b ]; -THREE.MorphAnimMesh.prototype.setDirectionForward = function () { + if ( bone ) { - this.direction = 1; - this.directionBackwards = false; + if ( bone.parent ) { -}; + bone.matrix.getInverse( bone.parent.matrixWorld ); + bone.matrix.multiply( bone.matrixWorld ); -THREE.MorphAnimMesh.prototype.setDirectionBackward = function () { + } + else { - this.direction = -1; - this.directionBackwards = true; + bone.matrix.copy( bone.matrixWorld ); -}; + } -THREE.MorphAnimMesh.prototype.parseAnimations = function () { + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); - var geometry = this.geometry; + } - if ( ! geometry.animations ) geometry.animations = {}; + } - var firstAnimation, animations = geometry.animations; +}; - var pattern = /([a-z]+)(\d+)/; +THREE.Skeleton.prototype.update = function () { - for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { + var offsetMatrix = new THREE.Matrix4(); - var morph = geometry.morphTargets[ i ]; - var parts = morph.name.match( pattern ); + // flatten bone matrices to array - if ( parts && parts.length > 1 ) { + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - var label = parts[ 1 ]; - var num = parts[ 2 ]; + // compute the offset between the current and the original transform - if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity }; + var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; - var animation = animations[ label ]; + offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); + offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 ); - if ( i < animation.start ) animation.start = i; - if ( i > animation.end ) animation.end = i; + } - if ( ! firstAnimation ) firstAnimation = label; + if ( this.useVertexTexture ) { - } + this.boneTexture.needsUpdate = true; } - geometry.firstAnimation = firstAnimation; - }; -THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) { - - if ( ! this.geometry.animations ) this.geometry.animations = {}; - this.geometry.animations[ label ] = { start: start, end: end }; +// File:src/objects/SkinnedMesh.js -}; +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ -THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) { +THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { - var animation = this.geometry.animations[ label ]; + THREE.Mesh.call( this, geometry, material ); - if ( animation ) { + this.bindMode = "attached"; + this.bindMatrix = new THREE.Matrix4(); + this.bindMatrixInverse = new THREE.Matrix4(); - this.setFrameRange( animation.start, animation.end ); - this.duration = 1000 * ( ( animation.end - animation.start ) / fps ); - this.time = 0; + // init bones - } else { + // TODO: remove bone creation as there is no reason (other than + // convenience) for THREE.SkinnedMesh to do this. - console.warn( "animation[" + label + "] undefined" ); + var bones = []; - } + if ( this.geometry && this.geometry.bones !== undefined ) { -}; + var bone, gbone, p, q, s; -THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) { + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++b ) { - var frameTime = this.duration / this.length; + gbone = this.geometry.bones[ b ]; + + p = gbone.pos; + q = gbone.rotq; + s = gbone.scl; + + bone = new THREE.Bone( this ); + bones.push( bone ); + + bone.name = gbone.name; + bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] ); + bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] ); + + if ( s !== undefined ) { + + bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] ); + + } else { + + bone.scale.set( 1, 1, 1 ); + + } + + } + + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++b ) { + + gbone = this.geometry.bones[ b ]; + + if ( gbone.parent !== - 1 ) { + + bones[ gbone.parent ].add( bones[ b ] ); + + } else { + + this.add( bones[ b ] ); + + } + + } + + } + + this.normalizeSkinWeights(); + + this.updateMatrixWorld( true ); + this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ) ); + +}; + + +THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype ); + +THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) { + + this.skeleton = skeleton; + + if ( bindMatrix === undefined ) { + + this.updateMatrixWorld( true ); + + bindMatrix = this.matrixWorld; + + } + + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.getInverse( bindMatrix ); + +}; + +THREE.SkinnedMesh.prototype.pose = function () { + + this.skeleton.pose(); + +}; + +THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () { + + if ( this.geometry instanceof THREE.Geometry ) { + + for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) { + + var sw = this.geometry.skinWeights[ i ]; + + var scale = 1.0 / sw.lengthManhattan(); + + if ( scale !== Infinity ) { + + sw.multiplyScalar( scale ); + + } else { + + sw.set( 1 ); // this will be normalized by the shader anyway + + } + + } + + } else { + + // skinning weights assumed to be normalized for THREE.BufferGeometry + + } + +}; + +THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) { + + THREE.Mesh.prototype.updateMatrixWorld.call( this, true ); + + if ( this.bindMode === "attached" ) { + + this.bindMatrixInverse.getInverse( this.matrixWorld ); + + } else if ( this.bindMode === "detached" ) { + + this.bindMatrixInverse.getInverse( this.bindMatrix ); + + } else { + + console.warn( 'THREE.SkinnedMesh unreckognized bindMode: ' + this.bindMode ); + + } + +}; + +THREE.SkinnedMesh.prototype.clone = function( object ) { + + if ( object === undefined ) { + + object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture ); + + } + + THREE.Mesh.prototype.clone.call( this, object ); + + return object; + +}; + + +// File:src/objects/MorphAnimMesh.js + +/** + * @author alteredq / http://alteredqualia.com/ + */ + +THREE.MorphAnimMesh = function ( geometry, material ) { + + THREE.Mesh.call( this, geometry, material ); + + // API + + this.duration = 1000; // milliseconds + this.mirroredLoop = false; + this.time = 0; + + // internals + + this.lastKeyframe = 0; + this.currentKeyframe = 0; + + this.direction = 1; + this.directionBackwards = false; + + this.setFrameRange( 0, this.geometry.morphTargets.length - 1 ); + +}; + +THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype ); + +THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) { + + this.startKeyframe = start; + this.endKeyframe = end; + + this.length = this.endKeyframe - this.startKeyframe + 1; + +}; + +THREE.MorphAnimMesh.prototype.setDirectionForward = function () { + + this.direction = 1; + this.directionBackwards = false; + +}; + +THREE.MorphAnimMesh.prototype.setDirectionBackward = function () { + + this.direction = - 1; + this.directionBackwards = true; + +}; + +THREE.MorphAnimMesh.prototype.parseAnimations = function () { + + var geometry = this.geometry; + + if ( ! geometry.animations ) geometry.animations = {}; + + var firstAnimation, animations = geometry.animations; + + var pattern = /([a-z]+)_?(\d+)/; + + for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { + + var morph = geometry.morphTargets[ i ]; + var parts = morph.name.match( pattern ); + + if ( parts && parts.length > 1 ) { + + var label = parts[ 1 ]; + var num = parts[ 2 ]; + + if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity }; + + var animation = animations[ label ]; + + if ( i < animation.start ) animation.start = i; + if ( i > animation.end ) animation.end = i; + + if ( ! firstAnimation ) firstAnimation = label; + + } + + } + + geometry.firstAnimation = firstAnimation; + +}; + +THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) { + + if ( ! this.geometry.animations ) this.geometry.animations = {}; + + this.geometry.animations[ label ] = { start: start, end: end }; + +}; + +THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) { + + var animation = this.geometry.animations[ label ]; + + if ( animation ) { + + this.setFrameRange( animation.start, animation.end ); + this.duration = 1000 * ( ( animation.end - animation.start ) / fps ); + this.time = 0; + + } else { + + console.warn( 'animation[' + label + '] undefined' ); + + } + +}; + +THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) { + + var frameTime = this.duration / this.length; this.time += this.direction * delta; @@ -16107,7 +15479,7 @@ THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) { if ( this.time > this.duration || this.time < 0 ) { - this.direction *= -1; + this.direction *= - 1; if ( this.time > this.duration ) { @@ -16160,6 +15532,21 @@ THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) { }; +THREE.MorphAnimMesh.prototype.interpolateTargets = function ( a, b, t ) { + + var influences = this.morphTargetInfluences; + + for ( var i = 0, l = influences.length; i < l; i ++ ) { + + influences[ i ] = 0; + + } + + if ( a > -1 ) influences[ a ] = 1 - t; + if ( b > -1 ) influences[ b ] = t; + +}; + THREE.MorphAnimMesh.prototype.clone = function ( object ) { if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material ); @@ -16180,6 +15567,8 @@ THREE.MorphAnimMesh.prototype.clone = function ( object ) { }; +// File:src/objects/LOD.js + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ @@ -16234,6 +15623,22 @@ THREE.LOD.prototype.getObjectForDistance = function ( distance ) { }; +THREE.LOD.prototype.raycast = ( function () { + + var matrixPosition = new THREE.Vector3(); + + return function ( raycaster, intersects ) { + + matrixPosition.setFromMatrixPosition( this.matrixWorld ); + + var distance = raycaster.ray.origin.distanceTo( matrixPosition ); + + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + + }; + +}() ); + THREE.LOD.prototype.update = function () { var v1 = new THREE.Vector3(); @@ -16265,7 +15670,7 @@ THREE.LOD.prototype.update = function () { } - for( ; i < l; i ++ ) { + for ( ; i < l; i ++ ) { this.objects[ i ].object.visible = false; @@ -16284,15 +15689,17 @@ THREE.LOD.prototype.clone = function ( object ) { THREE.Object3D.prototype.clone.call( this, object ); for ( var i = 0, l = this.objects.length; i < l; i ++ ) { - var x = this.objects[i].object.clone(); + var x = this.objects[ i ].object.clone(); x.visible = i === 0; - object.addLevel( x, this.objects[i].distance ); + object.addLevel( x, this.objects[ i ].distance ); } return object; }; +// File:src/objects/Sprite.js + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ @@ -16300,11 +15707,10 @@ THREE.LOD.prototype.clone = function ( object ) { THREE.Sprite = ( function () { - var vertices = new THREE.Float32Attribute( 3, 3 ); - vertices.set( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] ); + var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] ); var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', vertices ); + geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); return function ( material ) { @@ -16319,15 +15725,40 @@ THREE.Sprite = ( function () { THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype ); -/* - * Custom update matrix - */ +THREE.Sprite.prototype.raycast = ( function () { -THREE.Sprite.prototype.updateMatrix = function () { + var matrixPosition = new THREE.Vector3(); - this.matrix.compose( this.position, this.quaternion, this.scale ); + return function ( raycaster, intersects ) { - this.matrixWorldNeedsUpdate = true; + matrixPosition.setFromMatrixPosition( this.matrixWorld ); + + var distance = raycaster.ray.distanceToPoint( matrixPosition ); + + if ( distance > this.scale.x ) { + + return; + + } + + intersects.push( { + + distance: distance, + point: this.position, + face: null, + object: this + + } ); + + }; + +}() ); + +THREE.Sprite.prototype.updateMatrix = function () { + + this.matrix.compose( this.position, this.quaternion, this.scale ); + + this.matrixWorldNeedsUpdate = true; }; @@ -16344,6 +15775,9 @@ THREE.Sprite.prototype.clone = function ( object ) { // Backwards compatibility THREE.Particle = THREE.Sprite; + +// File:src/scenes/Scene.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -16383,7 +15817,7 @@ THREE.Scene.prototype.__addObject = function ( object ) { } - } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) { + } else if ( ! ( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) { this.__objectsAdded.push( object ); @@ -16391,7 +15825,7 @@ THREE.Scene.prototype.__addObject = function ( object ) { var i = this.__objectsRemoved.indexOf( object ); - if ( i !== -1 ) { + if ( i !== - 1 ) { this.__objectsRemoved.splice( i, 1 ); @@ -16416,7 +15850,7 @@ THREE.Scene.prototype.__removeObject = function ( object ) { var i = this.__lights.indexOf( object ); - if ( i !== -1 ) { + if ( i !== - 1 ) { this.__lights.splice( i, 1 ); @@ -16432,7 +15866,7 @@ THREE.Scene.prototype.__removeObject = function ( object ) { } - } else if ( !( object instanceof THREE.Camera ) ) { + } else if ( ! ( object instanceof THREE.Camera ) ) { this.__objectsRemoved.push( object ); @@ -16440,7 +15874,7 @@ THREE.Scene.prototype.__removeObject = function ( object ) { var i = this.__objectsAdded.indexOf( object ); - if ( i !== -1 ) { + if ( i !== - 1 ) { this.__objectsAdded.splice( i, 1 ); @@ -16463,7 +15897,7 @@ THREE.Scene.prototype.clone = function ( object ) { if ( object === undefined ) object = new THREE.Scene(); - THREE.Object3D.prototype.clone.call(this, object); + THREE.Object3D.prototype.clone.call( this, object ); if ( this.fog !== null ) object.fog = this.fog.clone(); if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone(); @@ -16475,6 +15909,8 @@ THREE.Scene.prototype.clone = function ( object ) { }; +// File:src/scenes/Fog.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -16497,6 +15933,8 @@ THREE.Fog.prototype.clone = function () { }; +// File:src/scenes/FogExp2.js + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -16517,6 +15955,8 @@ THREE.FogExp2.prototype.clone = function () { }; +// File:src/renderers/CanvasRenderer.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -16534,14 +15974,19 @@ THREE.CanvasRenderer = function ( parameters ) { _projector = new THREE.Projector(), _canvas = parameters.canvas !== undefined - ? parameters.canvas - : document.createElement( 'canvas' ), + ? parameters.canvas + : document.createElement( 'canvas' ), _canvasWidth = _canvas.width, _canvasHeight = _canvas.height, _canvasWidthHalf = Math.floor( _canvasWidth / 2 ), _canvasHeightHalf = Math.floor( _canvasHeight / 2 ), - + + _viewportX = 0, + _viewportY = 0, + _viewportWidth = _canvasWidth, + _viewportHeight = _canvasHeight, + _context = _canvas.getContext( '2d', { alpha: parameters.alpha === true } ), @@ -16556,8 +16001,7 @@ THREE.CanvasRenderer = function ( parameters ) { _contextLineWidth = null, _contextLineCap = null, _contextLineJoin = null, - _contextDashSize = null, - _contextGapSize = 0, + _contextLineDash = [], _camera, @@ -16608,10 +16052,10 @@ THREE.CanvasRenderer = function ( parameters ) { this.domElement = _canvas; this.devicePixelRatio = parameters.devicePixelRatio !== undefined - ? parameters.devicePixelRatio - : self.devicePixelRatio !== undefined - ? self.devicePixelRatio - : 1; + ? parameters.devicePixelRatio + : self.devicePixelRatio !== undefined + ? self.devicePixelRatio + : 1; this.autoClear = true; this.sortObjects = true; @@ -16651,7 +16095,7 @@ THREE.CanvasRenderer = function ( parameters ) { } - _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ), + _clipBox.min.set( -_canvasWidthHalf, -_canvasHeightHalf ), _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf ); _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ); @@ -16671,14 +16115,11 @@ THREE.CanvasRenderer = function ( parameters ) { this.setViewport = function ( x, y, width, height ) { - var viewportX = x * this.devicePixelRatio; - var viewportY = y * this.devicePixelRatio; - - var viewportWidth = width * this.devicePixelRatio; - var viewportHeight = height * this.devicePixelRatio; + _viewportX = x * this.devicePixelRatio; + _viewportY = y * this.devicePixelRatio; - _context.setTransform( viewportWidth / _canvasWidth, 0, 0, - viewportHeight / _canvasHeight, viewportX, _canvasHeight - viewportY ); - _context.translate( _canvasWidthHalf, _canvasHeightHalf ); + _viewportWidth = width * this.devicePixelRatio; + _viewportHeight = height * this.devicePixelRatio; }; @@ -16697,10 +16138,22 @@ THREE.CanvasRenderer = function ( parameters ) { this.setClearColorHex = function ( hex, alpha ) { - console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' ); + console.warn( 'THREE.CanvasRenderer: .setClearColorHex() is being removed. Use .setClearColor() instead.' ); this.setClearColor( hex, alpha ); }; + + this.getClearColor = function () { + + return _clearColor; + + }; + + this.getClearAlpha = function () { + + return _clearAlpha; + + }; this.getMaxAnisotropy = function () { @@ -16715,6 +16168,11 @@ THREE.CanvasRenderer = function ( parameters ) { _clearBox.intersect( _clipBox ); _clearBox.expandByScalar( 2 ); + _clearBox.min.x = _clearBox.min.x + _canvasWidthHalf; + _clearBox.min.y = - _clearBox.min.y + _canvasHeightHalf; + _clearBox.max.x = _clearBox.max.x + _canvasWidthHalf; + _clearBox.max.y = - _clearBox.max.y + _canvasHeightHalf; + if ( _clearAlpha < 1 ) { _context.clearRect( @@ -16768,6 +16226,9 @@ THREE.CanvasRenderer = function ( parameters ) { _this.info.render.vertices = 0; _this.info.render.faces = 0; + _context.setTransform( _viewportWidth / _canvasWidth, 0, 0, - _viewportHeight / _canvasHeight, _viewportX, _canvasHeight - _viewportY ); + _context.translate( _canvasWidthHalf, _canvasHeightHalf ); + _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements ); _elements = _renderData.elements; _lights = _renderData.lights; @@ -16821,9 +16282,9 @@ THREE.CanvasRenderer = function ( parameters ) { _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; - if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue; - if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue; - if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue; + if ( _v1.positionScreen.z < - 1 || _v1.positionScreen.z > 1 ) continue; + if ( _v2.positionScreen.z < - 1 || _v2.positionScreen.z > 1 ) continue; + if ( _v3.positionScreen.z < - 1 || _v3.positionScreen.z > 1 ) continue; _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf; _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf; @@ -16867,7 +16328,7 @@ THREE.CanvasRenderer = function ( parameters ) { _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y ); */ - // _context.setTransform( 1, 0, 0, 1, 0, 0 ); + _context.setTransform( 1, 0, 0, 1, 0, 0 ); }; @@ -16960,16 +16421,15 @@ THREE.CanvasRenderer = function ( parameters ) { _elemBox.min.set( v1.x - dist, v1.y - dist ); _elemBox.max.set( v1.x + dist, v1.y + dist ); - if ( material instanceof THREE.SpriteMaterial || - material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility + if ( material instanceof THREE.SpriteMaterial ) { var texture = material.map; - if ( texture !== null ) { + if ( texture !== null && texture.image !== undefined ) { if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) { - if ( texture.image !== undefined && texture.image.width > 0 ) { + if ( texture.image.width > 0 ) { textureToPattern( texture ); @@ -17013,7 +16473,9 @@ THREE.CanvasRenderer = function ( parameters ) { _context.fillRect( ox, oy, sx, sy ); _context.restore(); - } else { // no texture + } else { + + // no texture setFillStyle( material.color.getStyle() ); @@ -17075,8 +16537,8 @@ THREE.CanvasRenderer = function ( parameters ) { } else { - var colorStyle1 = element.vertexColors[0].getStyle(); - var colorStyle2 = element.vertexColors[1].getStyle(); + var colorStyle1 = element.vertexColors[ 0 ].getStyle(); + var colorStyle2 = element.vertexColors[ 1 ].getStyle(); if ( colorStyle1 === colorStyle2 ) { @@ -17116,13 +16578,13 @@ THREE.CanvasRenderer = function ( parameters ) { setLineCap( material.linecap ); setLineJoin( material.linejoin ); setStrokeStyle( material.color.getStyle() ); - setDashAndGap( material.dashSize, material.gapSize ); + setLineDash( [ material.dashSize, material.gapSize ] ); _context.stroke(); _elemBox.expandByScalar( material.linewidth * 2 ); - setDashAndGap( null, null ); + setLineDash( [] ); } @@ -17162,10 +16624,12 @@ THREE.CanvasRenderer = function ( parameters ) { _color.multiply( _diffuseColor ).add( _emissiveColor ); material.wireframe === true - ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) - : fillPath( _color ); + ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) + : fillPath( _color ); - } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) { + } else if ( material instanceof THREE.MeshBasicMaterial || + material instanceof THREE.MeshLambertMaterial || + material instanceof THREE.MeshPhongMaterial ) { if ( material.map !== null ) { @@ -17224,8 +16688,8 @@ THREE.CanvasRenderer = function ( parameters ) { } material.wireframe === true - ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) - : fillPath( _color ); + ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) + : fillPath( _color ); } @@ -17234,8 +16698,8 @@ THREE.CanvasRenderer = function ( parameters ) { _color.r = _color.g = _color.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _camera.near, _camera.far ); material.wireframe === true - ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) - : fillPath( _color ); + ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) + : fillPath( _color ); } else if ( material instanceof THREE.MeshNormalMaterial ) { @@ -17244,16 +16708,16 @@ THREE.CanvasRenderer = function ( parameters ) { _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 ); material.wireframe === true - ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) - : fillPath( _color ); + ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) + : fillPath( _color ); } else { _color.setRGB( 1, 1, 1 ); material.wireframe === true - ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) - : fillPath( _color ); + ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) + : fillPath( _color ); } @@ -17299,6 +16763,8 @@ THREE.CanvasRenderer = function ( parameters ) { function textureToPattern( texture ) { + if ( texture instanceof THREE.CompressedTexture ) return; + var repeatX = texture.wrapS === THREE.RepeatWrapping; var repeatY = texture.wrapT === THREE.RepeatWrapping; @@ -17314,12 +16780,12 @@ THREE.CanvasRenderer = function ( parameters ) { _patterns[ texture.id ] = _context.createPattern( canvas, repeatX === true && repeatY === true - ? 'repeat' - : repeatX === true && repeatY === false - ? 'repeat-x' - : repeatX === false && repeatY === true - ? 'repeat-y' - : 'no-repeat' + ? 'repeat' + : repeatX === true && repeatY === false + ? 'repeat-x' + : repeatX === false && repeatY === true + ? 'repeat-y' + : 'no-repeat' ); } @@ -17353,7 +16819,7 @@ THREE.CanvasRenderer = function ( parameters ) { return; - } + } // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120 @@ -17551,13 +17017,12 @@ THREE.CanvasRenderer = function ( parameters ) { } - function setDashAndGap( dashSizeValue, gapSizeValue ) { + function setLineDash( value ) { - if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) { + if ( _contextLineDash.length !== value.length ) { - _context.setLineDash( [ dashSizeValue, gapSizeValue ] ); - _contextDashSize = dashSizeValue; - _contextGapSize = gapSizeValue; + _context.setLineDash( value ); + _contextLineDash = value; } @@ -17565,13013 +17030,11114 @@ THREE.CanvasRenderer = function ( parameters ) { }; -/** - * Shader chunks for WebLG Shader library - * - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ - -THREE.ShaderChunk = { - - // FOG - - fog_pars_fragment: [ +// File:src/renderers/shaders/ShaderChunk.js - "#ifdef USE_FOG", +THREE.ShaderChunk = {}; - " uniform vec3 fogColor;", +// File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl - " #ifdef FOG_EXP2", +THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n\n if ( gl_FragColor.a < ALPHATEST ) discard;\n\n#endif\n"; - " uniform float fogDensity;", +// File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl - " #else", +THREE.ShaderChunk[ 'lights_lambert_vertex'] = "vLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\n vLightBack = vec3( 0.0 );\n\n#endif\n\ntransformedNormal = normalize( transformedNormal );\n\n#if MAX_DIR_LIGHTS > 0\n\nfor( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );\n vec3 dirVector = normalize( lDirection.xyz );\n\n float dotProduct = dot( transformedNormal, dirVector );\n vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += directionalLightColor[ i ] * directionalLightWeighting;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;\n\n #endif\n\n}\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float lDistance = 1.0;\n if ( pointLightDistance[ i ] > 0.0 )\n lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );\n\n lVector = normalize( lVector );\n float dotProduct = dot( transformedNormal, lVector );\n\n vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;\n\n #endif\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n float lDistance = 1.0;\n if ( spotLightDistance[ i ] > 0.0 )\n lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );\n\n lVector = normalize( lVector );\n\n float dotProduct = dot( transformedNormal, lVector );\n vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;\n\n #endif\n\n }\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );\n vec3 lVector = normalize( lDirection.xyz );\n\n float dotProduct = dot( transformedNormal, lVector );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;\n\n vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );\n\n #endif\n\n }\n\n#endif\n\nvLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;\n\n#ifdef DOUBLE_SIDED\n\n vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;\n\n#endif"; - " uniform float fogNear;", - " uniform float fogFar;", +// File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl - " #endif", +THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif"; - "#endif" +// File:src/renderers/shaders/ShaderChunk/default_vertex.glsl - ].join("\n"), +THREE.ShaderChunk[ 'default_vertex'] = "vec4 mvPosition;\n\n#ifdef USE_SKINNING\n\n mvPosition = modelViewMatrix * skinned;\n\n#endif\n\n#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )\n\n mvPosition = modelViewMatrix * vec4( morphed, 1.0 );\n\n#endif\n\n#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )\n\n mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;"; - fog_fragment: [ +// File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl - "#ifdef USE_FOG", +THREE.ShaderChunk[ 'map_pars_fragment'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n\n#endif\n\n#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif"; - " #ifdef USE_LOGDEPTHBUF_EXT", +// File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl - " float depth = gl_FragDepthEXT / gl_FragCoord.w;", +THREE.ShaderChunk[ 'skinnormal_vertex'] = "#ifdef USE_SKINNING\n\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n #ifdef USE_MORPHNORMALS\n\n vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );\n\n #else\n\n vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );\n\n #endif\n\n#endif\n"; - " #else", +// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl - " float depth = gl_FragCoord.z / gl_FragCoord.w;", +THREE.ShaderChunk[ 'logdepthbuf_pars_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n varying float vFragDepth;\n\n #endif\n\n uniform float logDepthBufFC;\n\n#endif"; - " #endif", +// File:src/renderers/shaders/ShaderChunk/lightmap_pars_vertex.glsl - " #ifdef FOG_EXP2", +THREE.ShaderChunk[ 'lightmap_pars_vertex'] = "#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n\n#endif"; - " const float LOG2 = 1.442695;", - " float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );", - " fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );", +// File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl - " #else", +THREE.ShaderChunk[ 'lights_phong_fragment'] = "vec3 normal = normalize( vNormal );\nvec3 viewPosition = normalize( vViewPosition );\n\n#ifdef DOUBLE_SIDED\n\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n\n#endif\n\n#ifdef USE_NORMALMAP\n\n normal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n vec3 pointDiffuse = vec3( 0.0 );\n vec3 pointSpecular = vec3( 0.0 );\n\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float lDistance = 1.0;\n if ( pointLightDistance[ i ] > 0.0 )\n lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );\n\n lVector = normalize( lVector );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float pointDiffuseWeightFull = max( dotProduct, 0.0 );\n float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float pointDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;\n\n // specular\n\n vec3 pointHalfVector = normalize( lVector + viewPosition );\n float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );\n float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );\n pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n vec3 spotDiffuse = vec3( 0.0 );\n vec3 spotSpecular = vec3( 0.0 );\n\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float lDistance = 1.0;\n if ( spotLightDistance[ i ] > 0.0 )\n lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );\n\n lVector = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float spotDiffuseWeightFull = max( dotProduct, 0.0 );\n float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float spotDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;\n\n // specular\n\n vec3 spotHalfVector = normalize( lVector + viewPosition );\n float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );\n float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );\n spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n vec3 dirDiffuse = vec3( 0.0 );\n vec3 dirSpecular = vec3( 0.0 );\n\n for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );\n vec3 dirVector = normalize( lDirection.xyz );\n\n // diffuse\n\n float dotProduct = dot( normal, dirVector );\n\n #ifdef WRAP_AROUND\n\n float dirDiffuseWeightFull = max( dotProduct, 0.0 );\n float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float dirDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;\n\n // specular\n\n vec3 dirHalfVector = normalize( dirVector + viewPosition );\n float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );\n float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );\n\n /*\n // fresnel term from skin shader\n const float F0 = 0.128;\n\n float base = 1.0 - dot( viewPosition, dirHalfVector );\n float exponential = pow( base, 5.0 );\n\n float fresnel = exponential + F0 * ( 1.0 - exponential );\n */\n\n /*\n // fresnel term from fresnel shader\n const float mFresnelBias = 0.08;\n const float mFresnelScale = 0.3;\n const float mFresnelPower = 5.0;\n\n float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );\n */\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n // dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );\n dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;\n\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n vec3 hemiDiffuse = vec3( 0.0 );\n vec3 hemiSpecular = vec3( 0.0 );\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );\n vec3 lVector = normalize( lDirection.xyz );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n hemiDiffuse += diffuse * hemiColor;\n\n // specular (sky light)\n\n vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );\n float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;\n float hemiSpecularWeightSky = specularStrength * max( pow( max( hemiDotNormalHalfSky, 0.0 ), shininess ), 0.0 );\n\n // specular (ground light)\n\n vec3 lVectorGround = -lVector;\n\n vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );\n float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;\n float hemiSpecularWeightGround = specularStrength * max( pow( max( hemiDotNormalHalfGround, 0.0 ), shininess ), 0.0 );\n\n float dotProductGround = dot( normal, lVectorGround );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );\n vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );\n hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );\n\n }\n\n#endif\n\nvec3 totalDiffuse = vec3( 0.0 );\nvec3 totalSpecular = vec3( 0.0 );\n\n#if MAX_DIR_LIGHTS > 0\n\n totalDiffuse += dirDiffuse;\n totalSpecular += dirSpecular;\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n totalDiffuse += hemiDiffuse;\n totalSpecular += hemiSpecular;\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n totalDiffuse += pointDiffuse;\n totalSpecular += pointSpecular;\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n totalDiffuse += spotDiffuse;\n totalSpecular += spotSpecular;\n\n#endif\n\n#ifdef METAL\n\n gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );\n\n#else\n\n gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;\n\n#endif"; - " float fogFactor = smoothstep( fogNear, fogFar, depth );", +// File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl - " #endif", +THREE.ShaderChunk[ 'fog_pars_fragment'] = "#ifdef USE_FOG\n\n uniform vec3 fogColor;\n\n #ifdef FOG_EXP2\n\n uniform float fogDensity;\n\n #else\n\n uniform float fogNear;\n uniform float fogFar;\n #endif\n\n#endif"; - " gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );", +// File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl - "#endif" +THREE.ShaderChunk[ 'morphnormal_vertex'] = "#ifdef USE_MORPHNORMALS\n\n vec3 morphedNormal = vec3( 0.0 );\n\n morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n morphedNormal += normal;\n\n#endif"; - ].join("\n"), +// File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl - // ENVIRONMENT MAP +THREE.ShaderChunk[ 'envmap_pars_fragment'] = "#ifdef USE_ENVMAP\n\n uniform float reflectivity;\n uniform samplerCube envMap;\n uniform float flipEnvMap;\n uniform int combine;\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\n uniform bool useRefract;\n uniform float refractionRatio;\n\n #else\n\n varying vec3 vReflect;\n\n #endif\n\n#endif"; - envmap_pars_fragment: [ +// File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl - "#ifdef USE_ENVMAP", +THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif"; - " uniform float reflectivity;", - " uniform samplerCube envMap;", - " uniform float flipEnvMap;", - " uniform int combine;", +// File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl - " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )", +THREE.ShaderChunk[ 'normalmap_pars_fragment'] = "#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n#endif\n"; - " uniform bool useRefract;", - " uniform float refractionRatio;", +// File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl - " #else", +THREE.ShaderChunk[ 'lights_phong_pars_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n"; - " varying vec3 vReflect;", +// File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl - " #endif", +THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n uniform sampler2D lightMap;\n\n#endif"; - "#endif" +// File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl - ].join("\n"), +THREE.ShaderChunk[ 'shadowmap_vertex'] = "#ifdef USE_SHADOWMAP\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n\n }\n\n#endif"; - envmap_fragment: [ +// File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl - "#ifdef USE_ENVMAP", +THREE.ShaderChunk[ 'lights_phong_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n vWorldPosition = worldPosition.xyz;\n\n#endif"; - " vec3 reflectVec;", +// File:src/renderers/shaders/ShaderChunk/map_fragment.glsl - " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )", +THREE.ShaderChunk[ 'map_fragment'] = "#ifdef USE_MAP\n\n vec4 texelColor = texture2D( map, vUv );\n\n #ifdef GAMMA_INPUT\n\n texelColor.xyz *= texelColor.xyz;\n\n #endif\n\n gl_FragColor = gl_FragColor * texelColor;\n\n#endif"; - " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );", +// File:src/renderers/shaders/ShaderChunk/lightmap_vertex.glsl - // http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations - // "Transforming Normal Vectors with the Inverse Transformation" +THREE.ShaderChunk[ 'lightmap_vertex'] = "#ifdef USE_LIGHTMAP\n\n vUv2 = uv2;\n\n#endif"; - " vec3 worldNormal = normalize( vec3( vec4( normal, 0.0 ) * viewMatrix ) );", +// File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl - " if ( useRefract ) {", +THREE.ShaderChunk[ 'map_particle_fragment'] = "#ifdef USE_MAP\n\n gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );\n\n#endif"; - " reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );", +// File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl - " } else { ", +THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif\n"; - " reflectVec = reflect( cameraToVertex, worldNormal );", +// File:src/renderers/shaders/ShaderChunk/color_vertex.glsl - " }", +THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n\n #ifdef GAMMA_INPUT\n\n vColor = color * color;\n\n #else\n\n vColor = color;\n\n #endif\n\n#endif"; - " #else", +// File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl - " reflectVec = vReflect;", +THREE.ShaderChunk[ 'skinning_vertex'] = "#ifdef USE_SKINNING\n\n #ifdef USE_MORPHTARGETS\n\n vec4 skinVertex = bindMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 skinVertex = bindMatrix * vec4( position, 1.0 );\n\n #endif\n\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n\n#endif\n"; - " #endif", +// File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl - " #ifdef DOUBLE_SIDED", +THREE.ShaderChunk[ 'envmap_pars_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )\n\n varying vec3 vReflect;\n\n uniform float refractionRatio;\n uniform bool useRefract;\n\n#endif\n"; - " float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );", - " vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );", +// File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl - " #else", +THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "#ifdef GAMMA_OUTPUT\n\n gl_FragColor.xyz = sqrt( gl_FragColor.xyz );\n\n#endif"; - " vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );", +// File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl - " #endif", +THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif"; - " #ifdef GAMMA_INPUT", +// File:src/renderers/shaders/ShaderChunk/lights_lambert_pars_vertex.glsl - " cubeColor.xyz *= cubeColor.xyz;", +THREE.ShaderChunk[ 'lights_lambert_pars_vertex'] = "uniform vec3 ambient;\nuniform vec3 diffuse;\nuniform vec3 emissive;\n\nuniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n"; - " #endif", +// File:src/renderers/shaders/ShaderChunk/map_pars_vertex.glsl - " if ( combine == 1 ) {", +THREE.ShaderChunk[ 'map_pars_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n\n#endif\n"; - " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );", +// File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl - " } else if ( combine == 2 ) {", +THREE.ShaderChunk[ 'envmap_fragment'] = "#ifdef USE_ENVMAP\n\n vec3 reflectVec;\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n // http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\n // Transforming Normal Vectors with the Inverse Transformation\n\n vec3 worldNormal = normalize( vec3( vec4( normal, 0.0 ) * viewMatrix ) );\n\n if ( useRefract ) {\n\n reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n } else { \n\n reflectVec = reflect( cameraToVertex, worldNormal );\n\n }\n\n #else\n\n reflectVec = vReflect;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n\n float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n #else\n\n vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n #endif\n\n #ifdef GAMMA_INPUT\n\n cubeColor.xyz *= cubeColor.xyz;\n\n #endif\n\n if ( combine == 1 ) {\n\n gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );\n\n } else if ( combine == 2 ) {\n\n gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;\n\n } else {\n\n gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );\n\n }\n\n#endif"; - " gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;", +// File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl - " } else {", +THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n\n uniform sampler2D specularMap;\n\n#endif"; - " gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );", +// File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl - " }", +THREE.ShaderChunk[ 'logdepthbuf_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n gl_Position.z = log2(max(1e-6, gl_Position.w + 1.0)) * logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n vFragDepth = 1.0 + gl_Position.w;\n\n#else\n\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n #endif\n\n#endif"; - "#endif" +// File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl - ].join("\n"), +THREE.ShaderChunk[ 'morphtarget_pars_vertex'] = "#ifdef USE_MORPHTARGETS\n\n #ifndef USE_MORPHNORMALS\n\n uniform float morphTargetInfluences[ 8 ];\n\n #else\n\n uniform float morphTargetInfluences[ 4 ];\n\n #endif\n\n#endif"; - envmap_pars_vertex: [ +// File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl - "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )", +THREE.ShaderChunk[ 'specularmap_fragment'] = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n\n#else\n\n specularStrength = 1.0;\n\n#endif"; - " varying vec3 vReflect;", +// File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl - " uniform float refractionRatio;", - " uniform bool useRefract;", +THREE.ShaderChunk[ 'fog_fragment'] = "#ifdef USE_FOG\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n #else\n\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n\n #endif\n\n #ifdef FOG_EXP2\n\n const float LOG2 = 1.442695;\n float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );\n fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n\n #else\n\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n\n #endif\n \n gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );\n\n#endif"; - "#endif" +// File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl - ].join("\n"), +THREE.ShaderChunk[ 'bumpmap_pars_fragment'] = "#ifdef USE_BUMPMAP\n\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n\n // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n vec2 dHdxy_fwd() {\n\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n return vec2( dBx, dBy );\n\n }\n\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm; // normalized\n\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n\n float fDet = dot( vSigmaX, R1 );\n\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n\n }\n\n#endif"; - worldpos_vertex : [ +// File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl - "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )", +THREE.ShaderChunk[ 'defaultnormal_vertex'] = "vec3 objectNormal;\n\n#ifdef USE_SKINNING\n\n objectNormal = skinnedNormal.xyz;\n\n#endif\n\n#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )\n\n objectNormal = morphedNormal;\n\n#endif\n\n#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )\n\n objectNormal = normal;\n\n#endif\n\n#ifdef FLIP_SIDED\n\n objectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;"; - " #ifdef USE_SKINNING", +// File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl - " vec4 worldPosition = modelMatrix * skinned;", +THREE.ShaderChunk[ 'lights_phong_pars_fragment'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n\nvarying vec3 vViewPosition;\nvarying vec3 vNormal;"; - " #endif", +// File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl - " #if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )", +THREE.ShaderChunk[ 'skinbase_vertex'] = "#ifdef USE_SKINNING\n\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif"; - " vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );", +// File:src/renderers/shaders/ShaderChunk/map_vertex.glsl - " #endif", +THREE.ShaderChunk[ 'map_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif"; - " #if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )", +// File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl - " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );", +THREE.ShaderChunk[ 'lightmap_fragment'] = "#ifdef USE_LIGHTMAP\n\n gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );\n\n#endif"; - " #endif", +// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl - "#endif" +THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n\n#endif"; - ].join("\n"), +// File:src/renderers/shaders/ShaderChunk/color_fragment.glsl - envmap_vertex : [ +THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n\n gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );\n\n#endif"; - "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )", +// File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl - " vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;", - " worldNormal = normalize( worldNormal );", +THREE.ShaderChunk[ 'morphtarget_vertex'] = "#ifdef USE_MORPHTARGETS\n\n vec3 morphed = vec3( 0.0 );\n morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n #ifndef USE_MORPHNORMALS\n\n morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n #endif\n\n morphed += position;\n\n#endif"; - " vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );", +// File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl - " if ( useRefract ) {", +THREE.ShaderChunk[ 'envmap_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )\n\n vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;\n worldNormal = normalize( worldNormal );\n\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n if ( useRefract ) {\n\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n } else {\n\n vReflect = reflect( cameraToVertex, worldNormal );\n\n }\n\n#endif"; - " vReflect = refract( cameraToVertex, worldNormal, refractionRatio );", +// File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl - " } else {", +THREE.ShaderChunk[ 'shadowmap_fragment'] = "#ifdef USE_SHADOWMAP\n\n #ifdef SHADOWMAP_DEBUG\n\n vec3 frustumColors[3];\n frustumColors[0] = vec3( 1.0, 0.5, 0.0 );\n frustumColors[1] = vec3( 0.0, 1.0, 0.8 );\n frustumColors[2] = vec3( 0.0, 0.5, 1.0 );\n\n #endif\n\n #ifdef SHADOWMAP_CASCADE\n\n int inFrustumCount = 0;\n\n #endif\n\n float fDepth;\n vec3 shadowColor = vec3( 1.0 );\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\n\n // if ( something && something ) breaks ATI OpenGL shader compiler\n // if ( all( something, something ) ) using this instead\n\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n\n // don't shadow pixels outside of light frustum\n // use just first frustum (for cascades)\n // don't shadow pixels behind far plane of light frustum\n\n #ifdef SHADOWMAP_CASCADE\n\n inFrustumCount += int( inFrustum );\n bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );\n\n #else\n\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n #endif\n\n bool frustumTest = all( frustumTestVec );\n\n if ( frustumTest ) {\n\n shadowCoord.z += shadowBias[ i ];\n\n #if defined( SHADOWMAP_TYPE_PCF )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n /*\n // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL\n // must enroll loop manually\n\n for ( float y = -1.25; y <= 1.25; y += 1.25 )\n for ( float x = -1.25; x <= 1.25; x += 1.25 ) {\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );\n\n // doesn't seem to produce any noticeable visual difference compared to simple texture2D lookup\n //vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );\n\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n shadow += 1.0;\n\n }\n\n shadow /= 9.0;\n\n */\n\n const float shadowDelta = 1.0 / 9.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.25 * xPixelOffset;\n float dy0 = -1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.0 * xPixelOffset;\n float dy0 = -1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n\n mat3 shadowKernel;\n mat3 depthKernel;\n\n depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));\n shadowKernel[0] *= vec3(0.25);\n\n shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));\n shadowKernel[1] *= vec3(0.25);\n\n shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));\n shadowKernel[2] *= vec3(0.25);\n\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );\n\n shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );\n shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );\n\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );\n\n shadow = dot( shadowValues, vec4( 1.0 ) );\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #else\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n\n // spot with multiple shadows is darker\n\n shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );\n\n // spot with multiple shadows has the same color as single shadow spot\n\n // shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );\n\n #endif\n\n }\n\n\n #ifdef SHADOWMAP_DEBUG\n\n #ifdef SHADOWMAP_CASCADE\n\n if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];\n\n #else\n\n if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];\n\n #endif\n\n #endif\n\n }\n\n #ifdef GAMMA_OUTPUT\n\n shadowColor *= shadowColor;\n\n #endif\n\n gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;\n\n#endif\n"; - " vReflect = reflect( cameraToVertex, worldNormal );", +// File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl - " }", +THREE.ShaderChunk[ 'worldpos_vertex'] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n #ifdef USE_SKINNING\n\n vec4 worldPosition = modelMatrix * skinned;\n\n #endif\n\n #if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )\n\n vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );\n\n #endif\n\n #if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )\n\n vec4 worldPosition = modelMatrix * vec4( position, 1.0 );\n\n #endif\n\n#endif"; - "#endif" +// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl - ].join("\n"), +THREE.ShaderChunk[ 'shadowmap_pars_fragment'] = "#ifdef USE_SHADOWMAP\n\n uniform sampler2D shadowMap[ MAX_SHADOWS ];\n uniform vec2 shadowMapSize[ MAX_SHADOWS ];\n\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform float shadowBias[ MAX_SHADOWS ];\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n\n float unpackDepth( const in vec4 rgba_depth ) {\n\n const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n float depth = dot( rgba_depth, bit_shift );\n return depth;\n\n }\n\n#endif"; - // COLOR MAP (particles) +// File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl - map_particle_pars_fragment: [ +THREE.ShaderChunk[ 'skinning_pars_vertex'] = "#ifdef USE_SKINNING\n\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n\n #ifdef BONE_TEXTURE\n\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n\n mat4 getBoneMatrix( const in float i ) {\n\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n\n y = dy * ( y + 0.5 );\n\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n mat4 bone = mat4( v1, v2, v3, v4 );\n\n return bone;\n\n }\n\n #else\n\n uniform mat4 boneGlobalMatrices[ MAX_BONES ];\n\n mat4 getBoneMatrix( const in float i ) {\n\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n\n }\n\n #endif\n\n#endif\n"; - "#ifdef USE_MAP", +// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl - " uniform sampler2D map;", +THREE.ShaderChunk[ 'logdepthbuf_pars_fragment'] = "#ifdef USE_LOGDEPTHBUF\n\n uniform float logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n #extension GL_EXT_frag_depth : enable\n varying float vFragDepth;\n\n #endif\n\n#endif"; - "#endif" +// File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl - ].join("\n"), +THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n\n gl_FragColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n"; +// File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl - map_particle_fragment: [ +THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n\n uniform sampler2D alphaMap;\n\n#endif\n"; - "#ifdef USE_MAP", +// File:src/renderers/shaders/UniformsUtils.js - " gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );", - - "#endif" +/** + * Uniform Utilities + */ - ].join("\n"), +THREE.UniformsUtils = { - // COLOR MAP (triangles) + merge: function ( uniforms ) { - map_pars_vertex: [ + var u, p, tmp, merged = {}; - "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )", + for ( u = 0; u < uniforms.length; u ++ ) { - " varying vec2 vUv;", - " uniform vec4 offsetRepeat;", + tmp = this.clone( uniforms[ u ] ); - "#endif" + for ( p in tmp ) { - ].join("\n"), + merged[ p ] = tmp[ p ]; - map_pars_fragment: [ + } - "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )", + } - " varying vec2 vUv;", + return merged; - "#endif", + }, - "#ifdef USE_MAP", + clone: function ( uniforms_src ) { - " uniform sampler2D map;", + var u, p, parameter, parameter_src, uniforms_dst = {}; - "#endif" + for ( u in uniforms_src ) { - ].join("\n"), + uniforms_dst[ u ] = {}; - map_vertex: [ + for ( p in uniforms_src[ u ] ) { - "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )", + parameter_src = uniforms_src[ u ][ p ]; - " vUv = uv * offsetRepeat.zw + offsetRepeat.xy;", + if ( parameter_src instanceof THREE.Color || + parameter_src instanceof THREE.Vector2 || + parameter_src instanceof THREE.Vector3 || + parameter_src instanceof THREE.Vector4 || + parameter_src instanceof THREE.Matrix4 || + parameter_src instanceof THREE.Texture ) { - "#endif" + uniforms_dst[ u ][ p ] = parameter_src.clone(); - ].join("\n"), + } else if ( parameter_src instanceof Array ) { - map_fragment: [ + uniforms_dst[ u ][ p ] = parameter_src.slice(); - "#ifdef USE_MAP", + } else { - " vec4 texelColor = texture2D( map, vUv );", + uniforms_dst[ u ][ p ] = parameter_src; - " #ifdef GAMMA_INPUT", + } - " texelColor.xyz *= texelColor.xyz;", + } - " #endif", + } - " gl_FragColor = gl_FragColor * texelColor;", + return uniforms_dst; - "#endif" + } - ].join("\n"), +}; - // LIGHT MAP +// File:src/renderers/shaders/UniformsLib.js - lightmap_pars_fragment: [ +/** + * Uniforms library for shared webgl shaders + */ - "#ifdef USE_LIGHTMAP", +THREE.UniformsLib = { - " varying vec2 vUv2;", - " uniform sampler2D lightMap;", + common: { - "#endif" + "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, + "opacity" : { type: "f", value: 1.0 }, - ].join("\n"), + "map" : { type: "t", value: null }, + "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }, - lightmap_pars_vertex: [ + "lightMap" : { type: "t", value: null }, + "specularMap" : { type: "t", value: null }, + "alphaMap" : { type: "t", value: null }, - "#ifdef USE_LIGHTMAP", + "envMap" : { type: "t", value: null }, + "flipEnvMap" : { type: "f", value: - 1 }, + "useRefract" : { type: "i", value: 0 }, + "reflectivity" : { type: "f", value: 1.0 }, + "refractionRatio" : { type: "f", value: 0.98 }, + "combine" : { type: "i", value: 0 }, - " varying vec2 vUv2;", + "morphTargetInfluences" : { type: "f", value: 0 } - "#endif" + }, - ].join("\n"), + bump: { - lightmap_fragment: [ + "bumpMap" : { type: "t", value: null }, + "bumpScale" : { type: "f", value: 1 } - "#ifdef USE_LIGHTMAP", + }, - " gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );", + normalmap: { - "#endif" + "normalMap" : { type: "t", value: null }, + "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) } + }, - ].join("\n"), + fog : { - lightmap_vertex: [ + "fogDensity" : { type: "f", value: 0.00025 }, + "fogNear" : { type: "f", value: 1 }, + "fogFar" : { type: "f", value: 2000 }, + "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } - "#ifdef USE_LIGHTMAP", + }, - " vUv2 = uv2;", + lights: { - "#endif" + "ambientLightColor" : { type: "fv", value: [] }, - ].join("\n"), + "directionalLightDirection" : { type: "fv", value: [] }, + "directionalLightColor" : { type: "fv", value: [] }, - // BUMP MAP + "hemisphereLightDirection" : { type: "fv", value: [] }, + "hemisphereLightSkyColor" : { type: "fv", value: [] }, + "hemisphereLightGroundColor" : { type: "fv", value: [] }, - bumpmap_pars_fragment: [ + "pointLightColor" : { type: "fv", value: [] }, + "pointLightPosition" : { type: "fv", value: [] }, + "pointLightDistance" : { type: "fv1", value: [] }, - "#ifdef USE_BUMPMAP", + "spotLightColor" : { type: "fv", value: [] }, + "spotLightPosition" : { type: "fv", value: [] }, + "spotLightDirection" : { type: "fv", value: [] }, + "spotLightDistance" : { type: "fv1", value: [] }, + "spotLightAngleCos" : { type: "fv1", value: [] }, + "spotLightExponent" : { type: "fv1", value: [] } - " uniform sampler2D bumpMap;", - " uniform float bumpScale;", + }, - // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen - // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html + particle: { - // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2) + "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, + "opacity" : { type: "f", value: 1.0 }, + "size" : { type: "f", value: 1.0 }, + "scale" : { type: "f", value: 1.0 }, + "map" : { type: "t", value: null }, - " vec2 dHdxy_fwd() {", + "fogDensity" : { type: "f", value: 0.00025 }, + "fogNear" : { type: "f", value: 1 }, + "fogFar" : { type: "f", value: 2000 }, + "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } - " vec2 dSTdx = dFdx( vUv );", - " vec2 dSTdy = dFdy( vUv );", + }, - " float Hll = bumpScale * texture2D( bumpMap, vUv ).x;", - " float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;", - " float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;", + shadowmap: { - " return vec2( dBx, dBy );", + "shadowMap": { type: "tv", value: [] }, + "shadowMapSize": { type: "v2v", value: [] }, - " }", + "shadowBias" : { type: "fv1", value: [] }, + "shadowDarkness": { type: "fv1", value: [] }, - " vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {", + "shadowMatrix" : { type: "m4v", value: [] } - " vec3 vSigmaX = dFdx( surf_pos );", - " vec3 vSigmaY = dFdy( surf_pos );", - " vec3 vN = surf_norm;", // normalized + } - " vec3 R1 = cross( vSigmaY, vN );", - " vec3 R2 = cross( vN, vSigmaX );", +}; - " float fDet = dot( vSigmaX, R1 );", +// File:src/renderers/shaders/ShaderLib.js - " vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );", - " return normalize( abs( fDet ) * surf_norm - vGrad );", +/** + * Webgl Shader Library for three.js + * + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + */ - " }", - "#endif" +THREE.ShaderLib = { - ].join("\n"), + 'basic': { - // NORMAL MAP + uniforms: THREE.UniformsUtils.merge( [ - normalmap_pars_fragment: [ + THREE.UniformsLib[ "common" ], + THREE.UniformsLib[ "fog" ], + THREE.UniformsLib[ "shadowmap" ] - "#ifdef USE_NORMALMAP", + ] ), - " uniform sampler2D normalMap;", - " uniform vec2 normalScale;", + vertexShader: [ - // Per-Pixel Tangent Space Normal Mapping - // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html + THREE.ShaderChunk[ "map_pars_vertex" ], + THREE.ShaderChunk[ "lightmap_pars_vertex" ], + THREE.ShaderChunk[ "envmap_pars_vertex" ], + THREE.ShaderChunk[ "color_pars_vertex" ], + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "skinning_pars_vertex" ], + THREE.ShaderChunk[ "shadowmap_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - " vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {", + "void main() {", - " vec3 q0 = dFdx( eye_pos.xyz );", - " vec3 q1 = dFdy( eye_pos.xyz );", - " vec2 st0 = dFdx( vUv.st );", - " vec2 st1 = dFdy( vUv.st );", + THREE.ShaderChunk[ "map_vertex" ], + THREE.ShaderChunk[ "lightmap_vertex" ], + THREE.ShaderChunk[ "color_vertex" ], + THREE.ShaderChunk[ "skinbase_vertex" ], - " vec3 S = normalize( q0 * st1.t - q1 * st0.t );", - " vec3 T = normalize( -q0 * st1.s + q1 * st0.s );", - " vec3 N = normalize( surf_norm );", + " #ifdef USE_ENVMAP", - " vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;", - " mapN.xy = normalScale * mapN.xy;", - " mat3 tsn = mat3( S, T, N );", - " return normalize( tsn * mapN );", + THREE.ShaderChunk[ "morphnormal_vertex" ], + THREE.ShaderChunk[ "skinnormal_vertex" ], + THREE.ShaderChunk[ "defaultnormal_vertex" ], - " }", + " #endif", - "#endif" + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "skinning_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - ].join("\n"), + THREE.ShaderChunk[ "worldpos_vertex" ], + THREE.ShaderChunk[ "envmap_vertex" ], + THREE.ShaderChunk[ "shadowmap_vertex" ], - // SPECULAR MAP + "}" - specularmap_pars_fragment: [ + ].join("\n"), - "#ifdef USE_SPECULARMAP", + fragmentShader: [ - " uniform sampler2D specularMap;", + "uniform vec3 diffuse;", + "uniform float opacity;", - "#endif" + THREE.ShaderChunk[ "color_pars_fragment" ], + THREE.ShaderChunk[ "map_pars_fragment" ], + THREE.ShaderChunk[ "alphamap_pars_fragment" ], + THREE.ShaderChunk[ "lightmap_pars_fragment" ], + THREE.ShaderChunk[ "envmap_pars_fragment" ], + THREE.ShaderChunk[ "fog_pars_fragment" ], + THREE.ShaderChunk[ "shadowmap_pars_fragment" ], + THREE.ShaderChunk[ "specularmap_pars_fragment" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - ].join("\n"), + "void main() {", - specularmap_fragment: [ + " gl_FragColor = vec4( diffuse, opacity );", - "float specularStrength;", + THREE.ShaderChunk[ "logdepthbuf_fragment" ], + THREE.ShaderChunk[ "map_fragment" ], + THREE.ShaderChunk[ "alphamap_fragment" ], + THREE.ShaderChunk[ "alphatest_fragment" ], + THREE.ShaderChunk[ "specularmap_fragment" ], + THREE.ShaderChunk[ "lightmap_fragment" ], + THREE.ShaderChunk[ "color_fragment" ], + THREE.ShaderChunk[ "envmap_fragment" ], + THREE.ShaderChunk[ "shadowmap_fragment" ], - "#ifdef USE_SPECULARMAP", + THREE.ShaderChunk[ "linear_to_gamma_fragment" ], - " vec4 texelSpecular = texture2D( specularMap, vUv );", - " specularStrength = texelSpecular.r;", + THREE.ShaderChunk[ "fog_fragment" ], - "#else", + "}" - " specularStrength = 1.0;", + ].join("\n") - "#endif" + }, - ].join("\n"), + 'lambert': { - // LIGHTS LAMBERT + uniforms: THREE.UniformsUtils.merge( [ - lights_lambert_pars_vertex: [ + THREE.UniformsLib[ "common" ], + THREE.UniformsLib[ "fog" ], + THREE.UniformsLib[ "lights" ], + THREE.UniformsLib[ "shadowmap" ], - "uniform vec3 ambient;", - "uniform vec3 diffuse;", - "uniform vec3 emissive;", + { + "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) }, + "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }, + "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } + } - "uniform vec3 ambientLightColor;", + ] ), - "#if MAX_DIR_LIGHTS > 0", + vertexShader: [ - " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];", - " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];", + "#define LAMBERT", - "#endif", + "varying vec3 vLightFront;", - "#if MAX_HEMI_LIGHTS > 0", + "#ifdef DOUBLE_SIDED", - " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];", - " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];", - " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];", + " varying vec3 vLightBack;", - "#endif", + "#endif", - "#if MAX_POINT_LIGHTS > 0", + THREE.ShaderChunk[ "map_pars_vertex" ], + THREE.ShaderChunk[ "lightmap_pars_vertex" ], + THREE.ShaderChunk[ "envmap_pars_vertex" ], + THREE.ShaderChunk[ "lights_lambert_pars_vertex" ], + THREE.ShaderChunk[ "color_pars_vertex" ], + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "skinning_pars_vertex" ], + THREE.ShaderChunk[ "shadowmap_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];", - " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];", - " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];", + "void main() {", - "#endif", + THREE.ShaderChunk[ "map_vertex" ], + THREE.ShaderChunk[ "lightmap_vertex" ], + THREE.ShaderChunk[ "color_vertex" ], - "#if MAX_SPOT_LIGHTS > 0", + THREE.ShaderChunk[ "morphnormal_vertex" ], + THREE.ShaderChunk[ "skinbase_vertex" ], + THREE.ShaderChunk[ "skinnormal_vertex" ], + THREE.ShaderChunk[ "defaultnormal_vertex" ], - " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];", - " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];", - " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];", - " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];", - " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];", - " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];", + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "skinning_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - "#endif", + THREE.ShaderChunk[ "worldpos_vertex" ], + THREE.ShaderChunk[ "envmap_vertex" ], + THREE.ShaderChunk[ "lights_lambert_vertex" ], + THREE.ShaderChunk[ "shadowmap_vertex" ], - "#ifdef WRAP_AROUND", + "}" - " uniform vec3 wrapRGB;", + ].join("\n"), - "#endif" + fragmentShader: [ - ].join("\n"), + "uniform float opacity;", - lights_lambert_vertex: [ + "varying vec3 vLightFront;", - "vLightFront = vec3( 0.0 );", + "#ifdef DOUBLE_SIDED", - "#ifdef DOUBLE_SIDED", + " varying vec3 vLightBack;", - " vLightBack = vec3( 0.0 );", + "#endif", - "#endif", + THREE.ShaderChunk[ "color_pars_fragment" ], + THREE.ShaderChunk[ "map_pars_fragment" ], + THREE.ShaderChunk[ "alphamap_pars_fragment" ], + THREE.ShaderChunk[ "lightmap_pars_fragment" ], + THREE.ShaderChunk[ "envmap_pars_fragment" ], + THREE.ShaderChunk[ "fog_pars_fragment" ], + THREE.ShaderChunk[ "shadowmap_pars_fragment" ], + THREE.ShaderChunk[ "specularmap_pars_fragment" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - "transformedNormal = normalize( transformedNormal );", + "void main() {", - "#if MAX_DIR_LIGHTS > 0", + " gl_FragColor = vec4( vec3( 1.0 ), opacity );", - "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {", + THREE.ShaderChunk[ "logdepthbuf_fragment" ], + THREE.ShaderChunk[ "map_fragment" ], + THREE.ShaderChunk[ "alphamap_fragment" ], + THREE.ShaderChunk[ "alphatest_fragment" ], + THREE.ShaderChunk[ "specularmap_fragment" ], - " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );", - " vec3 dirVector = normalize( lDirection.xyz );", + " #ifdef DOUBLE_SIDED", - " float dotProduct = dot( transformedNormal, dirVector );", - " vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );", + //"float isFront = float( gl_FrontFacing );", + //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;", - " #ifdef DOUBLE_SIDED", + " if ( gl_FrontFacing )", + " gl_FragColor.xyz *= vLightFront;", + " else", + " gl_FragColor.xyz *= vLightBack;", - " vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );", + " #else", - " #ifdef WRAP_AROUND", + " gl_FragColor.xyz *= vLightFront;", - " vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );", + " #endif", - " #endif", + THREE.ShaderChunk[ "lightmap_fragment" ], + THREE.ShaderChunk[ "color_fragment" ], + THREE.ShaderChunk[ "envmap_fragment" ], + THREE.ShaderChunk[ "shadowmap_fragment" ], - " #endif", + THREE.ShaderChunk[ "linear_to_gamma_fragment" ], - " #ifdef WRAP_AROUND", + THREE.ShaderChunk[ "fog_fragment" ], - " vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );", - " directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );", + "}" - " #ifdef DOUBLE_SIDED", + ].join("\n") - " directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );", + }, - " #endif", + 'phong': { - " #endif", + uniforms: THREE.UniformsUtils.merge( [ - " vLightFront += directionalLightColor[ i ] * directionalLightWeighting;", + THREE.UniformsLib[ "common" ], + THREE.UniformsLib[ "bump" ], + THREE.UniformsLib[ "normalmap" ], + THREE.UniformsLib[ "fog" ], + THREE.UniformsLib[ "lights" ], + THREE.UniformsLib[ "shadowmap" ], - " #ifdef DOUBLE_SIDED", + { + "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) }, + "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }, + "specular" : { type: "c", value: new THREE.Color( 0x111111 ) }, + "shininess": { type: "f", value: 30 }, + "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } + } - " vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;", + ] ), - " #endif", + vertexShader: [ - "}", + "#define PHONG", - "#endif", + "varying vec3 vViewPosition;", + "varying vec3 vNormal;", - "#if MAX_POINT_LIGHTS > 0", + THREE.ShaderChunk[ "map_pars_vertex" ], + THREE.ShaderChunk[ "lightmap_pars_vertex" ], + THREE.ShaderChunk[ "envmap_pars_vertex" ], + THREE.ShaderChunk[ "lights_phong_pars_vertex" ], + THREE.ShaderChunk[ "color_pars_vertex" ], + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "skinning_pars_vertex" ], + THREE.ShaderChunk[ "shadowmap_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - " for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {", + "void main() {", - " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );", - " vec3 lVector = lPosition.xyz - mvPosition.xyz;", + THREE.ShaderChunk[ "map_vertex" ], + THREE.ShaderChunk[ "lightmap_vertex" ], + THREE.ShaderChunk[ "color_vertex" ], - " float lDistance = 1.0;", - " if ( pointLightDistance[ i ] > 0.0 )", - " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );", + THREE.ShaderChunk[ "morphnormal_vertex" ], + THREE.ShaderChunk[ "skinbase_vertex" ], + THREE.ShaderChunk[ "skinnormal_vertex" ], + THREE.ShaderChunk[ "defaultnormal_vertex" ], - " lVector = normalize( lVector );", - " float dotProduct = dot( transformedNormal, lVector );", + " vNormal = normalize( transformedNormal );", - " vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );", + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "skinning_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - " #ifdef DOUBLE_SIDED", + " vViewPosition = -mvPosition.xyz;", - " vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );", + THREE.ShaderChunk[ "worldpos_vertex" ], + THREE.ShaderChunk[ "envmap_vertex" ], + THREE.ShaderChunk[ "lights_phong_vertex" ], + THREE.ShaderChunk[ "shadowmap_vertex" ], - " #ifdef WRAP_AROUND", + "}" - " vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );", + ].join("\n"), - " #endif", + fragmentShader: [ - " #endif", + "uniform vec3 diffuse;", + "uniform float opacity;", - " #ifdef WRAP_AROUND", + "uniform vec3 ambient;", + "uniform vec3 emissive;", + "uniform vec3 specular;", + "uniform float shininess;", - " vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );", - " pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );", + THREE.ShaderChunk[ "color_pars_fragment" ], + THREE.ShaderChunk[ "map_pars_fragment" ], + THREE.ShaderChunk[ "alphamap_pars_fragment" ], + THREE.ShaderChunk[ "lightmap_pars_fragment" ], + THREE.ShaderChunk[ "envmap_pars_fragment" ], + THREE.ShaderChunk[ "fog_pars_fragment" ], + THREE.ShaderChunk[ "lights_phong_pars_fragment" ], + THREE.ShaderChunk[ "shadowmap_pars_fragment" ], + THREE.ShaderChunk[ "bumpmap_pars_fragment" ], + THREE.ShaderChunk[ "normalmap_pars_fragment" ], + THREE.ShaderChunk[ "specularmap_pars_fragment" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - " #ifdef DOUBLE_SIDED", + "void main() {", - " pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );", + " gl_FragColor = vec4( vec3( 1.0 ), opacity );", - " #endif", + THREE.ShaderChunk[ "logdepthbuf_fragment" ], + THREE.ShaderChunk[ "map_fragment" ], + THREE.ShaderChunk[ "alphamap_fragment" ], + THREE.ShaderChunk[ "alphatest_fragment" ], + THREE.ShaderChunk[ "specularmap_fragment" ], - " #endif", + THREE.ShaderChunk[ "lights_phong_fragment" ], - " vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;", + THREE.ShaderChunk[ "lightmap_fragment" ], + THREE.ShaderChunk[ "color_fragment" ], + THREE.ShaderChunk[ "envmap_fragment" ], + THREE.ShaderChunk[ "shadowmap_fragment" ], - " #ifdef DOUBLE_SIDED", + THREE.ShaderChunk[ "linear_to_gamma_fragment" ], - " vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;", + THREE.ShaderChunk[ "fog_fragment" ], - " #endif", + "}" - " }", + ].join("\n") - "#endif", + }, - "#if MAX_SPOT_LIGHTS > 0", + 'particle_basic': { - " for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {", + uniforms: THREE.UniformsUtils.merge( [ - " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );", - " vec3 lVector = lPosition.xyz - mvPosition.xyz;", + THREE.UniformsLib[ "particle" ], + THREE.UniformsLib[ "shadowmap" ] - " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );", + ] ), - " if ( spotEffect > spotLightAngleCos[ i ] ) {", + vertexShader: [ - " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );", + "uniform float size;", + "uniform float scale;", - " float lDistance = 1.0;", - " if ( spotLightDistance[ i ] > 0.0 )", - " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );", + THREE.ShaderChunk[ "color_pars_vertex" ], + THREE.ShaderChunk[ "shadowmap_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - " lVector = normalize( lVector );", + "void main() {", - " float dotProduct = dot( transformedNormal, lVector );", - " vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );", + THREE.ShaderChunk[ "color_vertex" ], - " #ifdef DOUBLE_SIDED", + " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", - " vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );", + " #ifdef USE_SIZEATTENUATION", + " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );", + " #else", + " gl_PointSize = size;", + " #endif", - " #ifdef WRAP_AROUND", + " gl_Position = projectionMatrix * mvPosition;", - " vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );", + THREE.ShaderChunk[ "logdepthbuf_vertex" ], + THREE.ShaderChunk[ "worldpos_vertex" ], + THREE.ShaderChunk[ "shadowmap_vertex" ], - " #endif", + "}" - " #endif", + ].join("\n"), - " #ifdef WRAP_AROUND", + fragmentShader: [ - " vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );", - " spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );", + "uniform vec3 psColor;", + "uniform float opacity;", - " #ifdef DOUBLE_SIDED", + THREE.ShaderChunk[ "color_pars_fragment" ], + THREE.ShaderChunk[ "map_particle_pars_fragment" ], + THREE.ShaderChunk[ "fog_pars_fragment" ], + THREE.ShaderChunk[ "shadowmap_pars_fragment" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - " spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );", + "void main() {", - " #endif", + " gl_FragColor = vec4( psColor, opacity );", - " #endif", + THREE.ShaderChunk[ "logdepthbuf_fragment" ], + THREE.ShaderChunk[ "map_particle_fragment" ], + THREE.ShaderChunk[ "alphatest_fragment" ], + THREE.ShaderChunk[ "color_fragment" ], + THREE.ShaderChunk[ "shadowmap_fragment" ], + THREE.ShaderChunk[ "fog_fragment" ], - " vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;", + "}" - " #ifdef DOUBLE_SIDED", + ].join("\n") - " vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;", + }, - " #endif", + 'dashed': { - " }", + uniforms: THREE.UniformsUtils.merge( [ - " }", + THREE.UniformsLib[ "common" ], + THREE.UniformsLib[ "fog" ], - "#endif", + { + "scale" : { type: "f", value: 1 }, + "dashSize" : { type: "f", value: 1 }, + "totalSize": { type: "f", value: 2 } + } - "#if MAX_HEMI_LIGHTS > 0", + ] ), - " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {", + vertexShader: [ - " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );", - " vec3 lVector = normalize( lDirection.xyz );", + "uniform float scale;", + "attribute float lineDistance;", - " float dotProduct = dot( transformedNormal, lVector );", + "varying float vLineDistance;", - " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;", - " float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;", + THREE.ShaderChunk[ "color_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - " vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );", + "void main() {", - " #ifdef DOUBLE_SIDED", + THREE.ShaderChunk[ "color_vertex" ], - " vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );", + " vLineDistance = scale * lineDistance;", - " #endif", + " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", + " gl_Position = projectionMatrix * mvPosition;", - " }", + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - "#endif", + "}" - "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;", + ].join("\n"), - "#ifdef DOUBLE_SIDED", + fragmentShader: [ - " vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;", + "uniform vec3 diffuse;", + "uniform float opacity;", - "#endif" + "uniform float dashSize;", + "uniform float totalSize;", - ].join("\n"), + "varying float vLineDistance;", - // LIGHTS PHONG + THREE.ShaderChunk[ "color_pars_fragment" ], + THREE.ShaderChunk[ "fog_pars_fragment" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - lights_phong_pars_vertex: [ + "void main() {", - "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )", + " if ( mod( vLineDistance, totalSize ) > dashSize ) {", - " varying vec3 vWorldPosition;", + " discard;", - "#endif" + " }", - ].join("\n"), + " gl_FragColor = vec4( diffuse, opacity );", + THREE.ShaderChunk[ "logdepthbuf_fragment" ], + THREE.ShaderChunk[ "color_fragment" ], + THREE.ShaderChunk[ "fog_fragment" ], - lights_phong_vertex: [ + "}" - "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )", + ].join("\n") - " vWorldPosition = worldPosition.xyz;", + }, - "#endif" + 'depth': { - ].join("\n"), + uniforms: { - lights_phong_pars_fragment: [ + "mNear": { type: "f", value: 1.0 }, + "mFar" : { type: "f", value: 2000.0 }, + "opacity" : { type: "f", value: 1.0 } - "uniform vec3 ambientLightColor;", + }, - "#if MAX_DIR_LIGHTS > 0", + vertexShader: [ - " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];", - " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];", + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - "#endif", + "void main() {", - "#if MAX_HEMI_LIGHTS > 0", + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];", - " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];", - " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];", + "}" - "#endif", + ].join("\n"), - "#if MAX_POINT_LIGHTS > 0", + fragmentShader: [ - " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];", + "uniform float mNear;", + "uniform float mFar;", + "uniform float opacity;", - " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];", - " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];", + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - "#endif", + "void main() {", - "#if MAX_SPOT_LIGHTS > 0", + THREE.ShaderChunk[ "logdepthbuf_fragment" ], - " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];", - " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];", - " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];", - " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];", - " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];", + " #ifdef USE_LOGDEPTHBUF_EXT", - " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];", + " float depth = gl_FragDepthEXT / gl_FragCoord.w;", - "#endif", + " #else", - "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )", + " float depth = gl_FragCoord.z / gl_FragCoord.w;", - " varying vec3 vWorldPosition;", + " #endif", - "#endif", + " float color = 1.0 - smoothstep( mNear, mFar, depth );", + " gl_FragColor = vec4( vec3( color ), opacity );", - "#ifdef WRAP_AROUND", + "}" - " uniform vec3 wrapRGB;", + ].join("\n") - "#endif", + }, - "varying vec3 vViewPosition;", - "varying vec3 vNormal;" + 'normal': { - ].join("\n"), + uniforms: { - lights_phong_fragment: [ + "opacity" : { type: "f", value: 1.0 } - "vec3 normal = normalize( vNormal );", - "vec3 viewPosition = normalize( vViewPosition );", + }, - "#ifdef DOUBLE_SIDED", + vertexShader: [ - " normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );", + "varying vec3 vNormal;", - "#endif", + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - "#ifdef USE_NORMALMAP", + "void main() {", - " normal = perturbNormal2Arb( -vViewPosition, normal );", + " vNormal = normalize( normalMatrix * normal );", - "#elif defined( USE_BUMPMAP )", + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - " normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );", + "}" - "#endif", + ].join("\n"), - "#if MAX_POINT_LIGHTS > 0", + fragmentShader: [ - " vec3 pointDiffuse = vec3( 0.0 );", - " vec3 pointSpecular = vec3( 0.0 );", + "uniform float opacity;", + "varying vec3 vNormal;", - " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {", + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );", - " vec3 lVector = lPosition.xyz + vViewPosition.xyz;", + "void main() {", - " float lDistance = 1.0;", - " if ( pointLightDistance[ i ] > 0.0 )", - " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );", + " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );", - " lVector = normalize( lVector );", + THREE.ShaderChunk[ "logdepthbuf_fragment" ], - // diffuse + "}" - " float dotProduct = dot( normal, lVector );", + ].join("\n") - " #ifdef WRAP_AROUND", + }, - " float pointDiffuseWeightFull = max( dotProduct, 0.0 );", - " float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );", + /* ------------------------------------------------------------------------- + // Normal map shader + // - Blinn-Phong + // - normal + diffuse + specular + AO + displacement + reflection + shadow maps + // - point and directional lights (use with "lights: true" material option) + ------------------------------------------------------------------------- */ - " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );", + 'normalmap' : { - " #else", + uniforms: THREE.UniformsUtils.merge( [ - " float pointDiffuseWeight = max( dotProduct, 0.0 );", + THREE.UniformsLib[ "fog" ], + THREE.UniformsLib[ "lights" ], + THREE.UniformsLib[ "shadowmap" ], - " #endif", + { - " pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;", + "enableAO" : { type: "i", value: 0 }, + "enableDiffuse" : { type: "i", value: 0 }, + "enableSpecular" : { type: "i", value: 0 }, + "enableReflection" : { type: "i", value: 0 }, + "enableDisplacement": { type: "i", value: 0 }, - // specular + "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture + "tDiffuse" : { type: "t", value: null }, + "tCube" : { type: "t", value: null }, + "tNormal" : { type: "t", value: null }, + "tSpecular" : { type: "t", value: null }, + "tAO" : { type: "t", value: null }, - " vec3 pointHalfVector = normalize( lVector + viewPosition );", - " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );", - " float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );", + "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) }, - // 2.0 => 2.0001 is hack to work around ANGLE bug + "uDisplacementBias": { type: "f", value: 0.0 }, + "uDisplacementScale": { type: "f", value: 1.0 }, - " float specularNormalization = ( shininess + 2.0001 ) / 8.0;", + "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) }, + "specular": { type: "c", value: new THREE.Color( 0x111111 ) }, + "ambient": { type: "c", value: new THREE.Color( 0xffffff ) }, + "shininess": { type: "f", value: 30 }, + "opacity": { type: "f", value: 1 }, - " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );", - " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;", + "useRefract": { type: "i", value: 0 }, + "refractionRatio": { type: "f", value: 0.98 }, + "reflectivity": { type: "f", value: 0.5 }, - " }", + "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) }, + "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }, - "#endif", + "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } - "#if MAX_SPOT_LIGHTS > 0", + } - " vec3 spotDiffuse = vec3( 0.0 );", - " vec3 spotSpecular = vec3( 0.0 );", + ] ), - " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {", + fragmentShader: [ - " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );", - " vec3 lVector = lPosition.xyz + vViewPosition.xyz;", + "uniform vec3 ambient;", + "uniform vec3 diffuse;", + "uniform vec3 specular;", + "uniform float shininess;", + "uniform float opacity;", - " float lDistance = 1.0;", - " if ( spotLightDistance[ i ] > 0.0 )", - " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );", + "uniform bool enableDiffuse;", + "uniform bool enableSpecular;", + "uniform bool enableAO;", + "uniform bool enableReflection;", - " lVector = normalize( lVector );", + "uniform sampler2D tDiffuse;", + "uniform sampler2D tNormal;", + "uniform sampler2D tSpecular;", + "uniform sampler2D tAO;", - " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );", + "uniform samplerCube tCube;", - " if ( spotEffect > spotLightAngleCos[ i ] ) {", + "uniform vec2 uNormalScale;", - " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );", + "uniform bool useRefract;", + "uniform float refractionRatio;", + "uniform float reflectivity;", - // diffuse + "varying vec3 vTangent;", + "varying vec3 vBinormal;", + "varying vec3 vNormal;", + "varying vec2 vUv;", - " float dotProduct = dot( normal, lVector );", + "uniform vec3 ambientLightColor;", - " #ifdef WRAP_AROUND", + "#if MAX_DIR_LIGHTS > 0", - " float spotDiffuseWeightFull = max( dotProduct, 0.0 );", - " float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );", + " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];", + " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];", - " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );", + "#endif", - " #else", + "#if MAX_HEMI_LIGHTS > 0", - " float spotDiffuseWeight = max( dotProduct, 0.0 );", + " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];", + " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];", + " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];", - " #endif", + "#endif", - " spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;", + "#if MAX_POINT_LIGHTS > 0", - // specular + " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];", + " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];", + " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];", - " vec3 spotHalfVector = normalize( lVector + viewPosition );", - " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );", - " float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );", + "#endif", - // 2.0 => 2.0001 is hack to work around ANGLE bug + "#if MAX_SPOT_LIGHTS > 0", - " float specularNormalization = ( shininess + 2.0001 ) / 8.0;", + " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];", + " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];", + " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];", + " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];", + " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];", + " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];", - " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );", - " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;", + "#endif", - " }", + "#ifdef WRAP_AROUND", - " }", + " uniform vec3 wrapRGB;", - "#endif", + "#endif", - "#if MAX_DIR_LIGHTS > 0", + "varying vec3 vWorldPosition;", + "varying vec3 vViewPosition;", - " vec3 dirDiffuse = vec3( 0.0 );", - " vec3 dirSpecular = vec3( 0.0 );" , + THREE.ShaderChunk[ "shadowmap_pars_fragment" ], + THREE.ShaderChunk[ "fog_pars_fragment" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - " for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {", + "void main() {", + THREE.ShaderChunk[ "logdepthbuf_fragment" ], - " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );", - " vec3 dirVector = normalize( lDirection.xyz );", + " gl_FragColor = vec4( vec3( 1.0 ), opacity );", - // diffuse + " vec3 specularTex = vec3( 1.0 );", - " float dotProduct = dot( normal, dirVector );", + " vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;", + " normalTex.xy *= uNormalScale;", + " normalTex = normalize( normalTex );", - " #ifdef WRAP_AROUND", + " if( enableDiffuse ) {", - " float dirDiffuseWeightFull = max( dotProduct, 0.0 );", - " float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );", + " #ifdef GAMMA_INPUT", - " vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );", + " vec4 texelColor = texture2D( tDiffuse, vUv );", + " texelColor.xyz *= texelColor.xyz;", - " #else", + " gl_FragColor = gl_FragColor * texelColor;", - " float dirDiffuseWeight = max( dotProduct, 0.0 );", + " #else", - " #endif", + " gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );", - " dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;", + " #endif", - // specular + " }", - " vec3 dirHalfVector = normalize( dirVector + viewPosition );", - " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );", - " float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );", + " if( enableAO ) {", - /* - // fresnel term from skin shader - " const float F0 = 0.128;", + " #ifdef GAMMA_INPUT", - " float base = 1.0 - dot( viewPosition, dirHalfVector );", - " float exponential = pow( base, 5.0 );", + " vec4 aoColor = texture2D( tAO, vUv );", + " aoColor.xyz *= aoColor.xyz;", - " float fresnel = exponential + F0 * ( 1.0 - exponential );", - */ + " gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;", - /* - // fresnel term from fresnel shader - " const float mFresnelBias = 0.08;", - " const float mFresnelScale = 0.3;", - " const float mFresnelPower = 5.0;", + " #else", - " float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );", - */ + " gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;", - // 2.0 => 2.0001 is hack to work around ANGLE bug + " #endif", - " float specularNormalization = ( shininess + 2.0001 ) / 8.0;", + " }", + + THREE.ShaderChunk[ "alphatest_fragment" ], - //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;", + " if( enableSpecular )", + " specularTex = texture2D( tSpecular, vUv ).xyz;", - " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );", - " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;", + " mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );", + " vec3 finalNormal = tsb * normalTex;", + " #ifdef FLIP_SIDED", - " }", + " finalNormal = -finalNormal;", - "#endif", + " #endif", - "#if MAX_HEMI_LIGHTS > 0", + " vec3 normal = normalize( finalNormal );", + " vec3 viewPosition = normalize( vViewPosition );", - " vec3 hemiDiffuse = vec3( 0.0 );", - " vec3 hemiSpecular = vec3( 0.0 );" , + // point lights - " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {", + " #if MAX_POINT_LIGHTS > 0", - " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );", - " vec3 lVector = normalize( lDirection.xyz );", + " vec3 pointDiffuse = vec3( 0.0 );", + " vec3 pointSpecular = vec3( 0.0 );", - // diffuse + " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {", - " float dotProduct = dot( normal, lVector );", - " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;", + " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );", + " vec3 pointVector = lPosition.xyz + vViewPosition.xyz;", - " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );", + " float pointDistance = 1.0;", + " if ( pointLightDistance[ i ] > 0.0 )", + " pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );", - " hemiDiffuse += diffuse * hemiColor;", + " pointVector = normalize( pointVector );", - // specular (sky light) + // diffuse - " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );", - " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;", - " float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );", + " #ifdef WRAP_AROUND", - // specular (ground light) + " float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );", + " float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );", - " vec3 lVectorGround = -lVector;", + " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );", - " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );", - " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;", - " float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );", + " #else", - " float dotProductGround = dot( normal, lVectorGround );", + " float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );", - // 2.0 => 2.0001 is hack to work around ANGLE bug + " #endif", - " float specularNormalization = ( shininess + 2.0001 ) / 8.0;", + " pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;", - " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );", - " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );", - " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );", + // specular - " }", + " vec3 pointHalfVector = normalize( pointVector + viewPosition );", + " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );", + " float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );", - "#endif", + " float specularNormalization = ( shininess + 2.0 ) / 8.0;", - "vec3 totalDiffuse = vec3( 0.0 );", - "vec3 totalSpecular = vec3( 0.0 );", + " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( pointVector, pointHalfVector ), 0.0 ), 5.0 );", + " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;", - "#if MAX_DIR_LIGHTS > 0", + " }", - " totalDiffuse += dirDiffuse;", - " totalSpecular += dirSpecular;", + " #endif", - "#endif", + // spot lights - "#if MAX_HEMI_LIGHTS > 0", + " #if MAX_SPOT_LIGHTS > 0", - " totalDiffuse += hemiDiffuse;", - " totalSpecular += hemiSpecular;", + " vec3 spotDiffuse = vec3( 0.0 );", + " vec3 spotSpecular = vec3( 0.0 );", - "#endif", + " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {", - "#if MAX_POINT_LIGHTS > 0", + " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );", + " vec3 spotVector = lPosition.xyz + vViewPosition.xyz;", - " totalDiffuse += pointDiffuse;", - " totalSpecular += pointSpecular;", + " float spotDistance = 1.0;", + " if ( spotLightDistance[ i ] > 0.0 )", + " spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );", - "#endif", + " spotVector = normalize( spotVector );", - "#if MAX_SPOT_LIGHTS > 0", + " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );", - " totalDiffuse += spotDiffuse;", - " totalSpecular += spotSpecular;", + " if ( spotEffect > spotLightAngleCos[ i ] ) {", - "#endif", + " spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );", - "#ifdef METAL", + // diffuse - " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );", + " #ifdef WRAP_AROUND", - "#else", + " float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );", + " float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );", - " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;", + " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );", - "#endif" + " #else", - ].join("\n"), + " float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );", - // VERTEX COLORS + " #endif", - color_pars_fragment: [ + " spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;", - "#ifdef USE_COLOR", + // specular - " varying vec3 vColor;", + " vec3 spotHalfVector = normalize( spotVector + viewPosition );", + " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );", + " float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );", - "#endif" + " float specularNormalization = ( shininess + 2.0 ) / 8.0;", - ].join("\n"), + " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( spotVector, spotHalfVector ), 0.0 ), 5.0 );", + " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;", + " }", - color_fragment: [ + " }", - "#ifdef USE_COLOR", + " #endif", - " gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );", + // directional lights - "#endif" + " #if MAX_DIR_LIGHTS > 0", - ].join("\n"), + " vec3 dirDiffuse = vec3( 0.0 );", + " vec3 dirSpecular = vec3( 0.0 );", - color_pars_vertex: [ + " for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {", - "#ifdef USE_COLOR", + " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );", + " vec3 dirVector = normalize( lDirection.xyz );", - " varying vec3 vColor;", + // diffuse - "#endif" + " #ifdef WRAP_AROUND", - ].join("\n"), + " float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );", + " float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );", + " vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );", - color_vertex: [ + " #else", - "#ifdef USE_COLOR", + " float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );", - " #ifdef GAMMA_INPUT", + " #endif", - " vColor = color * color;", + " dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;", - " #else", + // specular - " vColor = color;", + " vec3 dirHalfVector = normalize( dirVector + viewPosition );", + " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );", + " float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );", - " #endif", + " float specularNormalization = ( shininess + 2.0 ) / 8.0;", - "#endif" + " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );", + " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;", - ].join("\n"), + " }", - // SKINNING + " #endif", - skinning_pars_vertex: [ + // hemisphere lights - "#ifdef USE_SKINNING", + " #if MAX_HEMI_LIGHTS > 0", - " #ifdef BONE_TEXTURE", + " vec3 hemiDiffuse = vec3( 0.0 );", + " vec3 hemiSpecular = vec3( 0.0 );" , - " uniform sampler2D boneTexture;", - " uniform int boneTextureWidth;", - " uniform int boneTextureHeight;", + " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {", - " mat4 getBoneMatrix( const in float i ) {", + " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );", + " vec3 lVector = normalize( lDirection.xyz );", - " float j = i * 4.0;", - " float x = mod( j, float( boneTextureWidth ) );", - " float y = floor( j / float( boneTextureWidth ) );", + // diffuse - " float dx = 1.0 / float( boneTextureWidth );", - " float dy = 1.0 / float( boneTextureHeight );", + " float dotProduct = dot( normal, lVector );", + " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;", - " y = dy * ( y + 0.5 );", + " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );", - " vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );", - " vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );", - " vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );", - " vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );", + " hemiDiffuse += diffuse * hemiColor;", - " mat4 bone = mat4( v1, v2, v3, v4 );", + // specular (sky light) - " return bone;", - " }", + " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );", + " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;", + " float hemiSpecularWeightSky = specularTex.r * max( pow( max( hemiDotNormalHalfSky, 0.0 ), shininess ), 0.0 );", - " #else", + // specular (ground light) - " uniform mat4 boneGlobalMatrices[ MAX_BONES ];", + " vec3 lVectorGround = -lVector;", - " mat4 getBoneMatrix( const in float i ) {", + " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );", + " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;", + " float hemiSpecularWeightGround = specularTex.r * max( pow( max( hemiDotNormalHalfGround, 0.0 ), shininess ), 0.0 );", - " mat4 bone = boneGlobalMatrices[ int(i) ];", - " return bone;", + " float dotProductGround = dot( normal, lVectorGround );", - " }", + " float specularNormalization = ( shininess + 2.0 ) / 8.0;", - " #endif", + " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );", + " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );", + " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );", - "#endif" + " }", - ].join("\n"), - - skinbase_vertex: [ + " #endif", - "#ifdef USE_SKINNING", + // all lights contribution summation - " mat4 boneMatX = getBoneMatrix( skinIndex.x );", - " mat4 boneMatY = getBoneMatrix( skinIndex.y );", - " mat4 boneMatZ = getBoneMatrix( skinIndex.z );", - " mat4 boneMatW = getBoneMatrix( skinIndex.w );", + " vec3 totalDiffuse = vec3( 0.0 );", + " vec3 totalSpecular = vec3( 0.0 );", - "#endif" + " #if MAX_DIR_LIGHTS > 0", - ].join("\n"), + " totalDiffuse += dirDiffuse;", + " totalSpecular += dirSpecular;", - skinning_vertex: [ + " #endif", - "#ifdef USE_SKINNING", + " #if MAX_HEMI_LIGHTS > 0", - " #ifdef USE_MORPHTARGETS", + " totalDiffuse += hemiDiffuse;", + " totalSpecular += hemiSpecular;", - " vec4 skinVertex = vec4( morphed, 1.0 );", + " #endif", - " #else", + " #if MAX_POINT_LIGHTS > 0", - " vec4 skinVertex = vec4( position, 1.0 );", + " totalDiffuse += pointDiffuse;", + " totalSpecular += pointSpecular;", - " #endif", + " #endif", - " vec4 skinned = boneMatX * skinVertex * skinWeight.x;", - " skinned += boneMatY * skinVertex * skinWeight.y;", - " skinned += boneMatZ * skinVertex * skinWeight.z;", - " skinned += boneMatW * skinVertex * skinWeight.w;", + " #if MAX_SPOT_LIGHTS > 0", - "#endif" + " totalDiffuse += spotDiffuse;", + " totalSpecular += spotSpecular;", - ].join("\n"), + " #endif", - // MORPHING + " #ifdef METAL", - morphtarget_pars_vertex: [ + " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );", - "#ifdef USE_MORPHTARGETS", + " #else", - " #ifndef USE_MORPHNORMALS", + " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;", - " uniform float morphTargetInfluences[ 8 ];", + " #endif", - " #else", + " if ( enableReflection ) {", - " uniform float morphTargetInfluences[ 4 ];", + " vec3 vReflect;", + " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );", - " #endif", + " if ( useRefract ) {", - "#endif" + " vReflect = refract( cameraToVertex, normal, refractionRatio );", - ].join("\n"), + " } else {", - morphtarget_vertex: [ + " vReflect = reflect( cameraToVertex, normal );", - "#ifdef USE_MORPHTARGETS", + " }", - " vec3 morphed = vec3( 0.0 );", - " morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];", - " morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];", - " morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];", - " morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];", + " vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );", - " #ifndef USE_MORPHNORMALS", + " #ifdef GAMMA_INPUT", - " morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];", - " morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];", - " morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];", - " morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];", + " cubeColor.xyz *= cubeColor.xyz;", - " #endif", + " #endif", - " morphed += position;", + " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );", - "#endif" + " }", - ].join("\n"), + THREE.ShaderChunk[ "shadowmap_fragment" ], + THREE.ShaderChunk[ "linear_to_gamma_fragment" ], + THREE.ShaderChunk[ "fog_fragment" ], - default_vertex : [ + "}" - "vec4 mvPosition;", + ].join("\n"), - "#ifdef USE_SKINNING", + vertexShader: [ - " mvPosition = modelViewMatrix * skinned;", + "attribute vec4 tangent;", - "#endif", + "uniform vec2 uOffset;", + "uniform vec2 uRepeat;", - "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )", + "uniform bool enableDisplacement;", - " mvPosition = modelViewMatrix * vec4( morphed, 1.0 );", + "#ifdef VERTEX_TEXTURES", - "#endif", + " uniform sampler2D tDisplacement;", + " uniform float uDisplacementScale;", + " uniform float uDisplacementBias;", - "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )", + "#endif", - " mvPosition = modelViewMatrix * vec4( position, 1.0 );", + "varying vec3 vTangent;", + "varying vec3 vBinormal;", + "varying vec3 vNormal;", + "varying vec2 vUv;", - "#endif", + "varying vec3 vWorldPosition;", + "varying vec3 vViewPosition;", - "gl_Position = projectionMatrix * mvPosition;" + THREE.ShaderChunk[ "skinning_pars_vertex" ], + THREE.ShaderChunk[ "shadowmap_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - ].join("\n"), + "void main() {", - morphnormal_vertex: [ + THREE.ShaderChunk[ "skinbase_vertex" ], + THREE.ShaderChunk[ "skinnormal_vertex" ], - "#ifdef USE_MORPHNORMALS", + // normal, tangent and binormal vectors - " vec3 morphedNormal = vec3( 0.0 );", + " #ifdef USE_SKINNING", - " morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];", - " morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];", - " morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];", - " morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];", + " vNormal = normalize( normalMatrix * skinnedNormal.xyz );", - " morphedNormal += normal;", + " vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );", + " vTangent = normalize( normalMatrix * skinnedTangent.xyz );", - "#endif" + " #else", - ].join("\n"), + " vNormal = normalize( normalMatrix * normal );", + " vTangent = normalize( normalMatrix * tangent.xyz );", - skinnormal_vertex: [ + " #endif", - "#ifdef USE_SKINNING", + " vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );", - " mat4 skinMatrix = skinWeight.x * boneMatX;", - " skinMatrix += skinWeight.y * boneMatY;", - " skinMatrix += skinWeight.z * boneMatZ;", - " skinMatrix += skinWeight.w * boneMatW;", + " vUv = uv * uRepeat + uOffset;", - " #ifdef USE_MORPHNORMALS", + // displacement mapping - " vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );", + " vec3 displacedPosition;", - " #else", + " #ifdef VERTEX_TEXTURES", - " vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );", + " if ( enableDisplacement ) {", - " #endif", + " vec3 dv = texture2D( tDisplacement, uv ).xyz;", + " float df = uDisplacementScale * dv.x + uDisplacementBias;", + " displacedPosition = position + normalize( normal ) * df;", - "#endif" + " } else {", - ].join("\n"), + " #ifdef USE_SKINNING", - defaultnormal_vertex: [ + " vec4 skinVertex = bindMatrix * vec4( position, 1.0 );", - "vec3 objectNormal;", + " vec4 skinned = vec4( 0.0 );", + " skinned += boneMatX * skinVertex * skinWeight.x;", + " skinned += boneMatY * skinVertex * skinWeight.y;", + " skinned += boneMatZ * skinVertex * skinWeight.z;", + " skinned += boneMatW * skinVertex * skinWeight.w;", + " skinned = bindMatrixInverse * skinned;", - "#ifdef USE_SKINNING", + " displacedPosition = skinned.xyz;", - " objectNormal = skinnedNormal.xyz;", + " #else", - "#endif", + " displacedPosition = position;", - "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )", + " #endif", - " objectNormal = morphedNormal;", + " }", - "#endif", + " #else", - "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )", + " #ifdef USE_SKINNING", - " objectNormal = normal;", + " vec4 skinVertex = bindMatrix * vec4( position, 1.0 );", - "#endif", + " vec4 skinned = vec4( 0.0 );", + " skinned += boneMatX * skinVertex * skinWeight.x;", + " skinned += boneMatY * skinVertex * skinWeight.y;", + " skinned += boneMatZ * skinVertex * skinWeight.z;", + " skinned += boneMatW * skinVertex * skinWeight.w;", + " skinned = bindMatrixInverse * skinned;", - "#ifdef FLIP_SIDED", + " displacedPosition = skinned.xyz;", - " objectNormal = -objectNormal;", + " #else", - "#endif", + " displacedPosition = position;", - "vec3 transformedNormal = normalMatrix * objectNormal;" + " #endif", - ].join("\n"), + " #endif", - // SHADOW MAP + // - // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples - // http://spidergl.org/example.php?id=6 - // http://fabiensanglard.net/shadowmapping + " vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );", + " vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );", - shadowmap_pars_fragment: [ + " gl_Position = projectionMatrix * mvPosition;", - "#ifdef USE_SHADOWMAP", + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - " uniform sampler2D shadowMap[ MAX_SHADOWS ];", - " uniform vec2 shadowMapSize[ MAX_SHADOWS ];", + // - " uniform float shadowDarkness[ MAX_SHADOWS ];", - " uniform float shadowBias[ MAX_SHADOWS ];", + " vWorldPosition = worldPosition.xyz;", + " vViewPosition = -mvPosition.xyz;", - " varying vec4 vShadowCoord[ MAX_SHADOWS ];", + // shadows - " float unpackDepth( const in vec4 rgba_depth ) {", + " #ifdef USE_SHADOWMAP", - " const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );", - " float depth = dot( rgba_depth, bit_shift );", - " return depth;", + " for( int i = 0; i < MAX_SHADOWS; i ++ ) {", - " }", + " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;", - "#endif" + " }", - ].join("\n"), + " #endif", - shadowmap_fragment: [ + "}" - "#ifdef USE_SHADOWMAP", + ].join("\n") - " #ifdef SHADOWMAP_DEBUG", + }, - " vec3 frustumColors[3];", - " frustumColors[0] = vec3( 1.0, 0.5, 0.0 );", - " frustumColors[1] = vec3( 0.0, 1.0, 0.8 );", - " frustumColors[2] = vec3( 0.0, 0.5, 1.0 );", + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - " #endif", + 'cube': { - " #ifdef SHADOWMAP_CASCADE", + uniforms: { "tCube": { type: "t", value: null }, + "tFlip": { type: "f", value: - 1 } }, - " int inFrustumCount = 0;", + vertexShader: [ - " #endif", + "varying vec3 vWorldPosition;", - " float fDepth;", - " vec3 shadowColor = vec3( 1.0 );", + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - " for( int i = 0; i < MAX_SHADOWS; i ++ ) {", + "void main() {", - " vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;", + " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );", + " vWorldPosition = worldPosition.xyz;", - // "if ( something && something )" breaks ATI OpenGL shader compiler - // "if ( all( something, something ) )" using this instead + " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", - " bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );", - " bool inFrustum = all( inFrustumVec );", + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - // don't shadow pixels outside of light frustum - // use just first frustum (for cascades) - // don't shadow pixels behind far plane of light frustum + "}" - " #ifdef SHADOWMAP_CASCADE", + ].join("\n"), - " inFrustumCount += int( inFrustum );", - " bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );", + fragmentShader: [ - " #else", + "uniform samplerCube tCube;", + "uniform float tFlip;", - " bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );", + "varying vec3 vWorldPosition;", - " #endif", + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - " bool frustumTest = all( frustumTestVec );", + "void main() {", - " if ( frustumTest ) {", + " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );", - " shadowCoord.z += shadowBias[ i ];", + THREE.ShaderChunk[ "logdepthbuf_fragment" ], - " #if defined( SHADOWMAP_TYPE_PCF )", + "}" - // Percentage-close filtering - // (9 pixel kernel) - // http://fabiensanglard.net/shadowmappingPCF/ + ].join("\n") - " float shadow = 0.0;", + }, - /* - // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL - // must enroll loop manually + /* Depth encoding into RGBA texture + * + * based on SpiderGL shadow map example + * http://spidergl.org/example.php?id=6 + * + * originally from + * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD + * + * see also + * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/ + */ - " for ( float y = -1.25; y <= 1.25; y += 1.25 )", - " for ( float x = -1.25; x <= 1.25; x += 1.25 ) {", + 'depthRGBA': { - " vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );", + uniforms: {}, - // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup - //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );", + vertexShader: [ - " float fDepth = unpackDepth( rgbaDepth );", + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "skinning_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - " if ( fDepth < shadowCoord.z )", - " shadow += 1.0;", + "void main() {", - " }", + THREE.ShaderChunk[ "skinbase_vertex" ], + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "skinning_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - " shadow /= 9.0;", + "}" - */ + ].join("\n"), - " const float shadowDelta = 1.0 / 9.0;", + fragmentShader: [ - " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;", - " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;", + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - " float dx0 = -1.25 * xPixelOffset;", - " float dy0 = -1.25 * yPixelOffset;", - " float dx1 = 1.25 * xPixelOffset;", - " float dy1 = 1.25 * yPixelOffset;", + "vec4 pack_depth( const in float depth ) {", - " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );", - " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", + " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );", + " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );", + " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );", + " res -= res.xxyz * bit_mask;", + " return res;", - " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );", - " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", + "}", - " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );", - " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", + "void main() {", - " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );", - " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", + THREE.ShaderChunk[ "logdepthbuf_fragment" ], - " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );", - " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", + " #ifdef USE_LOGDEPTHBUF_EXT", - " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );", - " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", + " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );", - " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );", - " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", + " #else", - " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );", - " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", + " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );", - " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );", - " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", + " #endif", - " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );", + //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );", + //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );", + //"gl_FragData[ 0 ] = pack_depth( z );", + //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );", - " #elif defined( SHADOWMAP_TYPE_PCF_SOFT )", + "}" - // Percentage-close filtering - // (9 pixel kernel) - // http://fabiensanglard.net/shadowmappingPCF/ + ].join("\n") - " float shadow = 0.0;", + } - " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;", - " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;", +}; - " float dx0 = -1.0 * xPixelOffset;", - " float dy0 = -1.0 * yPixelOffset;", - " float dx1 = 1.0 * xPixelOffset;", - " float dy1 = 1.0 * yPixelOffset;", +// File:src/renderers/WebGLRenderer.js - " mat3 shadowKernel;", - " mat3 depthKernel;", +/** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + */ - " depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );", - " depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );", - " depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );", - " depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );", - " depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );", - " depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );", - " depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );", - " depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );", - " depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );", +THREE.WebGLRenderer = function ( parameters ) { - " vec3 shadowZ = vec3( shadowCoord.z );", - " shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));", - " shadowKernel[0] *= vec3(0.25);", - - " shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));", - " shadowKernel[1] *= vec3(0.25);", + console.log( 'THREE.WebGLRenderer', THREE.REVISION ); - " shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));", - " shadowKernel[2] *= vec3(0.25);", + parameters = parameters || {}; - " vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );", + var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ), + _context = parameters.context !== undefined ? parameters.context : null, - " shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );", - " shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );", + _precision = parameters.precision !== undefined ? parameters.precision : 'highp', - " vec4 shadowValues;", - " shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );", - " shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );", - " shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );", - " shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );", + _alpha = parameters.alpha !== undefined ? parameters.alpha : false, + _depth = parameters.depth !== undefined ? parameters.depth : true, + _stencil = parameters.stencil !== undefined ? parameters.stencil : true, + _antialias = parameters.antialias !== undefined ? parameters.antialias : false, + _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, + _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, + _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false, - " shadow = dot( shadowValues, vec4( 1.0 ) );", + _clearColor = new THREE.Color( 0x000000 ), + _clearAlpha = 0; + + var opaqueObjects = []; + var transparentObjects = []; - " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );", + // public properties - " #else", + this.domElement = _canvas; + this.context = null; + this.devicePixelRatio = parameters.devicePixelRatio !== undefined + ? parameters.devicePixelRatio + : self.devicePixelRatio !== undefined + ? self.devicePixelRatio + : 1; - " vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );", - " float fDepth = unpackDepth( rgbaDepth );", + // clearing - " if ( fDepth < shadowCoord.z )", + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; - // spot with multiple shadows is darker + // scene graph - " shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );", + this.sortObjects = true; - // spot with multiple shadows has the same color as single shadow spot + // physically based shading - //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );", + this.gammaInput = false; + this.gammaOutput = false; - " #endif", + // shadow map - " }", + this.shadowMapEnabled = false; + this.shadowMapAutoUpdate = true; + this.shadowMapType = THREE.PCFShadowMap; + this.shadowMapCullFace = THREE.CullFaceFront; + this.shadowMapDebug = false; + this.shadowMapCascade = false; + // morphs - " #ifdef SHADOWMAP_DEBUG", + this.maxMorphTargets = 8; + this.maxMorphNormals = 4; - " #ifdef SHADOWMAP_CASCADE", + // flags - " if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];", + this.autoScaleCubemaps = true; - " #else", + // custom render plugins - " if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];", + this.renderPluginsPre = []; + this.renderPluginsPost = []; - " #endif", + // info - " #endif", + this.info = { - " }", + memory: { - " #ifdef GAMMA_OUTPUT", + programs: 0, + geometries: 0, + textures: 0 - " shadowColor *= shadowColor;", + }, - " #endif", + render: { - " gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;", + calls: 0, + vertices: 0, + faces: 0, + points: 0 - "#endif" + } - ].join("\n"), + }; - shadowmap_pars_vertex: [ + // internal properties - "#ifdef USE_SHADOWMAP", + var _this = this, - " varying vec4 vShadowCoord[ MAX_SHADOWS ];", - " uniform mat4 shadowMatrix[ MAX_SHADOWS ];", + _programs = [], - "#endif" + // internal state cache - ].join("\n"), + _currentProgram = null, + _currentFramebuffer = null, + _currentMaterialId = - 1, + _currentGeometryGroupHash = null, + _currentCamera = null, - shadowmap_vertex: [ + _usedTextureUnits = 0, - "#ifdef USE_SHADOWMAP", + // GL state cache - " for( int i = 0; i < MAX_SHADOWS; i ++ ) {", + _oldDoubleSided = - 1, + _oldFlipSided = - 1, - " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;", + _oldBlending = - 1, - " }", + _oldBlendEquation = - 1, + _oldBlendSrc = - 1, + _oldBlendDst = - 1, - "#endif" + _oldDepthTest = - 1, + _oldDepthWrite = - 1, - ].join("\n"), + _oldPolygonOffset = null, + _oldPolygonOffsetFactor = null, + _oldPolygonOffsetUnits = null, - // ALPHATEST + _oldLineWidth = null, - alphatest_fragment: [ + _viewportX = 0, + _viewportY = 0, + _viewportWidth = _canvas.width, + _viewportHeight = _canvas.height, + _currentWidth = 0, + _currentHeight = 0, - "#ifdef ALPHATEST", + _newAttributes = new Uint8Array( 16 ), + _enabledAttributes = new Uint8Array( 16 ), - " if ( gl_FragColor.a < ALPHATEST ) discard;", + // frustum - "#endif" + _frustum = new THREE.Frustum(), - ].join("\n"), + // camera matrices cache - // LINEAR SPACE + _projScreenMatrix = new THREE.Matrix4(), + _projScreenMatrixPS = new THREE.Matrix4(), - linear_to_gamma_fragment: [ + _vector3 = new THREE.Vector3(), - "#ifdef GAMMA_OUTPUT", + // light arrays cache - " gl_FragColor.xyz = sqrt( gl_FragColor.xyz );", + _direction = new THREE.Vector3(), - "#endif" + _lightsNeedUpdate = true, - ].join("\n"), + _lights = { - // LOGARITHMIC DEPTH BUFFER - // http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html + ambient: [ 0, 0, 0 ], + directional: { length: 0, colors:[], positions: [] }, + point: { length: 0, colors: [], positions: [], distances: [] }, + spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [] }, + hemi: { length: 0, skyColors: [], groundColors: [], positions: [] } - // WebGL doesn't support gl_FragDepth out of the box, unless the EXT_frag_depth extension is available. On platforms - // without EXT_frag_depth, we have to fall back on linear z-buffer in the fragment shader, which means that some long - // faces close to the camera may have issues. This can be worked around by tesselating the model more finely when - // the camera is near the surface. + }; - logdepthbuf_pars_vertex: [ + // initialize - "#ifdef USE_LOGDEPTHBUF", + var _gl; - " #ifdef USE_LOGDEPTHBUF_EXT", + var _glExtensionTextureFloat; + var _glExtensionTextureFloatLinear; + var _glExtensionStandardDerivatives; + var _glExtensionTextureFilterAnisotropic; + var _glExtensionCompressedTextureS3TC; + var _glExtensionElementIndexUint; + var _glExtensionFragDepth; - " varying float vFragDepth;", - " #endif", + initGL(); - " uniform float logDepthBufFC;", + setDefaultGLState(); - "#endif", + this.context = _gl; - ].join('\n'), + // GPU capabilities - logdepthbuf_vertex: [ + var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS ); + var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ); + var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE ); - "#ifdef USE_LOGDEPTHBUF", + var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0; - " gl_Position.z = log2(max(1e-6, gl_Position.w + 1.0)) * logDepthBufFC;", + var _supportsVertexTextures = ( _maxVertexTextures > 0 ); + var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat; - " #ifdef USE_LOGDEPTHBUF_EXT", + var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : []; - " vFragDepth = 1.0 + gl_Position.w;", + // - "#else", + var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT ); + var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT ); + var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT ); - " gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;", + var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT ); + var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT ); + var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT ); - " #endif", + // clamp precision to maximum available - "#endif" + var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0; + var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0; - ].join("\n"), + if ( _precision === 'highp' && ! highpAvailable ) { - logdepthbuf_pars_fragment: [ + if ( mediumpAvailable ) { - "#ifdef USE_LOGDEPTHBUF", + _precision = 'mediump'; + console.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' ); - " uniform float logDepthBufFC;", + } else { - " #ifdef USE_LOGDEPTHBUF_EXT", + _precision = 'lowp'; + console.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' ); - " #extension GL_EXT_frag_depth : enable", - " varying float vFragDepth;", + } - " #endif", + } - "#endif" + if ( _precision === 'mediump' && ! mediumpAvailable ) { - ].join('\n'), + _precision = 'lowp'; + console.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' ); - logdepthbuf_fragment: [ - "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)", + } - " gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;", + // API - "#endif" + this.getContext = function () { - ].join("\n") + return _gl; -}; + }; -/** - * Uniform Utilities - */ + this.supportsVertexTextures = function () { -THREE.UniformsUtils = { + return _supportsVertexTextures; - merge: function ( uniforms ) { + }; - var u, p, tmp, merged = {}; + this.supportsFloatTextures = function () { - for ( u = 0; u < uniforms.length; u ++ ) { + return _glExtensionTextureFloat; - tmp = this.clone( uniforms[ u ] ); + }; - for ( p in tmp ) { + this.supportsStandardDerivatives = function () { - merged[ p ] = tmp[ p ]; + return _glExtensionStandardDerivatives; - } + }; - } + this.supportsCompressedTextureS3TC = function () { - return merged; + return _glExtensionCompressedTextureS3TC; - }, + }; - clone: function ( uniforms_src ) { + this.getMaxAnisotropy = function () { - var u, p, parameter, parameter_src, uniforms_dst = {}; + return _maxAnisotropy; - for ( u in uniforms_src ) { + }; - uniforms_dst[ u ] = {}; + this.getPrecision = function () { - for ( p in uniforms_src[ u ] ) { + return _precision; - parameter_src = uniforms_src[ u ][ p ]; + }; - if ( parameter_src instanceof THREE.Color || - parameter_src instanceof THREE.Vector2 || - parameter_src instanceof THREE.Vector3 || - parameter_src instanceof THREE.Vector4 || - parameter_src instanceof THREE.Matrix4 || - parameter_src instanceof THREE.Texture ) { + this.setSize = function ( width, height, updateStyle ) { - uniforms_dst[ u ][ p ] = parameter_src.clone(); + _canvas.width = width * this.devicePixelRatio; + _canvas.height = height * this.devicePixelRatio; - } else if ( parameter_src instanceof Array ) { + if ( updateStyle !== false ) { - uniforms_dst[ u ][ p ] = parameter_src.slice(); + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; - } else { + } - uniforms_dst[ u ][ p ] = parameter_src; + this.setViewport( 0, 0, width, height ); - } + }; - } + this.setViewport = function ( x, y, width, height ) { - } + _viewportX = x * this.devicePixelRatio; + _viewportY = y * this.devicePixelRatio; - return uniforms_dst; + _viewportWidth = width * this.devicePixelRatio; + _viewportHeight = height * this.devicePixelRatio; - } + _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); -}; -/** - * Uniforms library for shared webgl shaders - */ + }; -THREE.UniformsLib = { + this.setScissor = function ( x, y, width, height ) { - common: { + _gl.scissor( + x * this.devicePixelRatio, + y * this.devicePixelRatio, + width * this.devicePixelRatio, + height * this.devicePixelRatio + ); - "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, - "opacity" : { type: "f", value: 1.0 }, + }; - "map" : { type: "t", value: null }, - "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }, + this.enableScissorTest = function ( enable ) { - "lightMap" : { type: "t", value: null }, - "specularMap" : { type: "t", value: null }, + enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST ); - "envMap" : { type: "t", value: null }, - "flipEnvMap" : { type: "f", value: -1 }, - "useRefract" : { type: "i", value: 0 }, - "reflectivity" : { type: "f", value: 1.0 }, - "refractionRatio" : { type: "f", value: 0.98 }, - "combine" : { type: "i", value: 0 }, + }; - "morphTargetInfluences" : { type: "f", value: 0 } + // Clearing - }, + this.setClearColor = function ( color, alpha ) { - bump: { + _clearColor.set( color ); + _clearAlpha = alpha !== undefined ? alpha : 1; - "bumpMap" : { type: "t", value: null }, - "bumpScale" : { type: "f", value: 1 } + _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - }, + }; - normalmap: { + this.setClearColorHex = function ( hex, alpha ) { - "normalMap" : { type: "t", value: null }, - "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) } - }, + console.warn( 'THREE.WebGLRenderer: .setClearColorHex() is being removed. Use .setClearColor() instead.' ); + this.setClearColor( hex, alpha ); - fog : { + }; - "fogDensity" : { type: "f", value: 0.00025 }, - "fogNear" : { type: "f", value: 1 }, - "fogFar" : { type: "f", value: 2000 }, - "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } + this.getClearColor = function () { - }, + return _clearColor; - lights: { + }; - "ambientLightColor" : { type: "fv", value: [] }, + this.getClearAlpha = function () { - "directionalLightDirection" : { type: "fv", value: [] }, - "directionalLightColor" : { type: "fv", value: [] }, + return _clearAlpha; - "hemisphereLightDirection" : { type: "fv", value: [] }, - "hemisphereLightSkyColor" : { type: "fv", value: [] }, - "hemisphereLightGroundColor" : { type: "fv", value: [] }, + }; - "pointLightColor" : { type: "fv", value: [] }, - "pointLightPosition" : { type: "fv", value: [] }, - "pointLightDistance" : { type: "fv1", value: [] }, + this.clear = function ( color, depth, stencil ) { - "spotLightColor" : { type: "fv", value: [] }, - "spotLightPosition" : { type: "fv", value: [] }, - "spotLightDirection" : { type: "fv", value: [] }, - "spotLightDistance" : { type: "fv1", value: [] }, - "spotLightAngleCos" : { type: "fv1", value: [] }, - "spotLightExponent" : { type: "fv1", value: [] } + var bits = 0; - }, + if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; + if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; + if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; - particle: { + _gl.clear( bits ); - "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, - "opacity" : { type: "f", value: 1.0 }, - "size" : { type: "f", value: 1.0 }, - "scale" : { type: "f", value: 1.0 }, - "map" : { type: "t", value: null }, + }; - "fogDensity" : { type: "f", value: 0.00025 }, - "fogNear" : { type: "f", value: 1 }, - "fogFar" : { type: "f", value: 2000 }, - "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } + this.clearColor = function () { - }, + _gl.clear( _gl.COLOR_BUFFER_BIT ); - shadowmap: { + }; - "shadowMap": { type: "tv", value: [] }, - "shadowMapSize": { type: "v2v", value: [] }, + this.clearDepth = function () { - "shadowBias" : { type: "fv1", value: [] }, - "shadowDarkness": { type: "fv1", value: [] }, + _gl.clear( _gl.DEPTH_BUFFER_BIT ); - "shadowMatrix" : { type: "m4v", value: [] } + }; - } + this.clearStencil = function () { -}; -/** - * Webgl Shader Library for three.js - * - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ + _gl.clear( _gl.STENCIL_BUFFER_BIT ); + }; -THREE.ShaderLib = { + this.clearTarget = function ( renderTarget, color, depth, stencil ) { - 'basic': { + this.setRenderTarget( renderTarget ); + this.clear( color, depth, stencil ); - uniforms: THREE.UniformsUtils.merge( [ + }; - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "shadowmap" ] + // Plugins - ] ), + this.addPostPlugin = function ( plugin ) { - vertexShader: [ + plugin.init( this ); + this.renderPluginsPost.push( plugin ); - THREE.ShaderChunk[ "map_pars_vertex" ], - THREE.ShaderChunk[ "lightmap_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + }; - "void main() {", + this.addPrePlugin = function ( plugin ) { - THREE.ShaderChunk[ "map_vertex" ], - THREE.ShaderChunk[ "lightmap_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], + plugin.init( this ); + this.renderPluginsPre.push( plugin ); - " #ifdef USE_ENVMAP", + }; - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], + // Rendering - " #endif", + this.updateShadowMap = function ( scene, camera ) { - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + _currentProgram = null; + _oldBlending = - 1; + _oldDepthTest = - 1; + _oldDepthWrite = - 1; + _currentGeometryGroupHash = - 1; + _currentMaterialId = - 1; + _lightsNeedUpdate = true; + _oldDoubleSided = - 1; + _oldFlipSided = - 1; - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], + initObjects( scene ); - "}" + this.shadowMapPlugin.update( scene, camera ); - ].join("\n"), + }; - fragmentShader: [ + // Internal functions - "uniform vec3 diffuse;", - "uniform float opacity;", + // Buffer allocation - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "lightmap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + function createParticleBuffers ( geometry ) { - "void main() {", + geometry.__webglVertexBuffer = _gl.createBuffer(); + geometry.__webglColorBuffer = _gl.createBuffer(); - " gl_FragColor = vec4( diffuse, opacity );", + _this.info.memory.geometries ++; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], - THREE.ShaderChunk[ "lightmap_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], + }; - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], + function createLineBuffers ( geometry ) { - THREE.ShaderChunk[ "fog_fragment" ], + geometry.__webglVertexBuffer = _gl.createBuffer(); + geometry.__webglColorBuffer = _gl.createBuffer(); + geometry.__webglLineDistanceBuffer = _gl.createBuffer(); - "}" + _this.info.memory.geometries ++; - ].join("\n") + }; - }, + function createMeshBuffers ( geometryGroup ) { - 'lambert': { + geometryGroup.__webglVertexBuffer = _gl.createBuffer(); + geometryGroup.__webglNormalBuffer = _gl.createBuffer(); + geometryGroup.__webglTangentBuffer = _gl.createBuffer(); + geometryGroup.__webglColorBuffer = _gl.createBuffer(); + geometryGroup.__webglUVBuffer = _gl.createBuffer(); + geometryGroup.__webglUV2Buffer = _gl.createBuffer(); - uniforms: THREE.UniformsUtils.merge( [ + geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer(); + geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer(); - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - THREE.UniformsLib[ "shadowmap" ], + geometryGroup.__webglFaceBuffer = _gl.createBuffer(); + geometryGroup.__webglLineBuffer = _gl.createBuffer(); - { - "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) }, - "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }, - "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } - } + var m, ml; - ] ), + if ( geometryGroup.numMorphTargets ) { - vertexShader: [ + geometryGroup.__webglMorphTargetsBuffers = []; - "#define LAMBERT", + for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { - "varying vec3 vLightFront;", + geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() ); - "#ifdef DOUBLE_SIDED", + } - " varying vec3 vLightBack;", + } - "#endif", + if ( geometryGroup.numMorphNormals ) { - THREE.ShaderChunk[ "map_pars_vertex" ], - THREE.ShaderChunk[ "lightmap_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "lights_lambert_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + geometryGroup.__webglMorphNormalsBuffers = []; - "void main() {", + for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { - THREE.ShaderChunk[ "map_vertex" ], - THREE.ShaderChunk[ "lightmap_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], + geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() ); - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], + } - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + } - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "lights_lambert_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], + _this.info.memory.geometries ++; - "}" + }; - ].join("\n"), + // Events - fragmentShader: [ + var onGeometryDispose = function ( event ) { - "uniform float opacity;", + var geometry = event.target; - "varying vec3 vLightFront;", + geometry.removeEventListener( 'dispose', onGeometryDispose ); - "#ifdef DOUBLE_SIDED", + deallocateGeometry( geometry ); - " varying vec3 vLightBack;", + }; - "#endif", + var onTextureDispose = function ( event ) { - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "lightmap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + var texture = event.target; - "void main() {", + texture.removeEventListener( 'dispose', onTextureDispose ); - " gl_FragColor = vec4( vec3( 1.0 ), opacity );", + deallocateTexture( texture ); - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], + _this.info.memory.textures --; - " #ifdef DOUBLE_SIDED", - //"float isFront = float( gl_FrontFacing );", - //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;", + }; - " if ( gl_FrontFacing )", - " gl_FragColor.xyz *= vLightFront;", - " else", - " gl_FragColor.xyz *= vLightBack;", + var onRenderTargetDispose = function ( event ) { - " #else", + var renderTarget = event.target; - " gl_FragColor.xyz *= vLightFront;", + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); - " #endif", + deallocateRenderTarget( renderTarget ); - THREE.ShaderChunk[ "lightmap_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], + _this.info.memory.textures --; - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], + }; - THREE.ShaderChunk[ "fog_fragment" ], + var onMaterialDispose = function ( event ) { - "}" + var material = event.target; - ].join("\n") + material.removeEventListener( 'dispose', onMaterialDispose ); - }, + deallocateMaterial( material ); - 'phong': { + }; - uniforms: THREE.UniformsUtils.merge( [ + // Buffer deallocation - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "bump" ], - THREE.UniformsLib[ "normalmap" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - THREE.UniformsLib[ "shadowmap" ], + var deleteBuffers = function ( geometry ) { - { - "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) }, - "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }, - "specular" : { type: "c", value: new THREE.Color( 0x111111 ) }, - "shininess": { type: "f", value: 30 }, - "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } - } + if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer ); + if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer ); + if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer ); + if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer ); + if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer ); + if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer ); - ] ), + if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer ); + if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer ); - vertexShader: [ + if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer ); + if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer ); - "#define PHONG", + if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer ); + // custom attributes - "varying vec3 vViewPosition;", - "varying vec3 vNormal;", + if ( geometry.__webglCustomAttributesList !== undefined ) { - THREE.ShaderChunk[ "map_pars_vertex" ], - THREE.ShaderChunk[ "lightmap_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "lights_phong_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + for ( var id in geometry.__webglCustomAttributesList ) { - "void main() {", + _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer ); - THREE.ShaderChunk[ "map_vertex" ], - THREE.ShaderChunk[ "lightmap_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], + } - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], + } - " vNormal = normalize( transformedNormal );", + _this.info.memory.geometries --; - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + }; - " vViewPosition = -mvPosition.xyz;", + var deallocateGeometry = function ( geometry ) { - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "lights_phong_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], + geometry.__webglInit = undefined; - "}" + if ( geometry instanceof THREE.BufferGeometry ) { - ].join("\n"), + var attributes = geometry.attributes; - fragmentShader: [ + for ( var key in attributes ) { - "uniform vec3 diffuse;", - "uniform float opacity;", + if ( attributes[ key ].buffer !== undefined ) { - "uniform vec3 ambient;", - "uniform vec3 emissive;", - "uniform vec3 specular;", - "uniform float shininess;", + _gl.deleteBuffer( attributes[ key ].buffer ); - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "lightmap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "lights_phong_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "bumpmap_pars_fragment" ], - THREE.ShaderChunk[ "normalmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + } - "void main() {", + } - " gl_FragColor = vec4( vec3( 1.0 ), opacity );", + _this.info.memory.geometries --; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], + } else { - THREE.ShaderChunk[ "lights_phong_fragment" ], + if ( geometry.geometryGroups !== undefined ) { - THREE.ShaderChunk[ "lightmap_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], + for ( var i = 0,l = geometry.geometryGroupsList.length; i dashSize ) {", + } - " discard;", + break; - " }", + } - " gl_FragColor = vec4( diffuse, opacity );", + } - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "fog_fragment" ], + if ( deleteProgram === true ) { - "}" + // avoid using array.splice, this is costlier than creating new array from scratch - ].join("\n") + var newPrograms = []; - }, + for ( i = 0, il = _programs.length; i < il; i ++ ) { - 'depth': { + programInfo = _programs[ i ]; - uniforms: { + if ( programInfo.program !== program ) { - "mNear": { type: "f", value: 1.0 }, - "mFar" : { type: "f", value: 2000.0 }, - "opacity" : { type: "f", value: 1.0 } + newPrograms.push( programInfo ); - }, + } - vertexShader: [ + } - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + _programs = newPrograms; - "void main() {", + _gl.deleteProgram( program ); - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + _this.info.memory.programs --; - "}" + } - ].join("\n"), + }; - fragmentShader: [ + // Buffer initialization - "uniform float mNear;", - "uniform float mFar;", - "uniform float opacity;", - - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + function initCustomAttributes ( geometry, object ) { - "void main() {", + var nvertices = geometry.vertices.length; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + var material = object.material; - " #ifdef USE_LOGDEPTHBUF_EXT", + if ( material.attributes ) { - " float depth = gl_FragDepthEXT / gl_FragCoord.w;", + if ( geometry.__webglCustomAttributesList === undefined ) { - " #else", + geometry.__webglCustomAttributesList = []; - " float depth = gl_FragCoord.z / gl_FragCoord.w;", + } - " #endif", + for ( var a in material.attributes ) { - " float color = 1.0 - smoothstep( mNear, mFar, depth );", - " gl_FragColor = vec4( vec3( color ), opacity );", + var attribute = material.attributes[ a ]; - "}" + if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) { - ].join("\n") + attribute.__webglInitialized = true; - }, + var size = 1; // "f" and "i" - 'normal': { + if ( attribute.type === 'v2' ) size = 2; + else if ( attribute.type === 'v3' ) size = 3; + else if ( attribute.type === 'v4' ) size = 4; + else if ( attribute.type === 'c' ) size = 3; - uniforms: { + attribute.size = size; - "opacity" : { type: "f", value: 1.0 } + attribute.array = new Float32Array( nvertices * size ); - }, + attribute.buffer = _gl.createBuffer(); + attribute.buffer.belongsToAttribute = a; - vertexShader: [ + attribute.needsUpdate = true; - "varying vec3 vNormal;", + } - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + geometry.__webglCustomAttributesList.push( attribute ); - "void main() {", + } - " vNormal = normalize( normalMatrix * normal );", + } - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + }; - "}" + function initParticleBuffers ( geometry, object ) { - ].join("\n"), + var nvertices = geometry.vertices.length; - fragmentShader: [ + geometry.__vertexArray = new Float32Array( nvertices * 3 ); + geometry.__colorArray = new Float32Array( nvertices * 3 ); - "uniform float opacity;", - "varying vec3 vNormal;", + geometry.__sortArray = []; - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + geometry.__webglParticleCount = nvertices; - "void main() {", + initCustomAttributes ( geometry, object ); - " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );", + }; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + function initLineBuffers ( geometry, object ) { - "}" + var nvertices = geometry.vertices.length; - ].join("\n") + geometry.__vertexArray = new Float32Array( nvertices * 3 ); + geometry.__colorArray = new Float32Array( nvertices * 3 ); + geometry.__lineDistanceArray = new Float32Array( nvertices * 1 ); - }, + geometry.__webglLineCount = nvertices; - /* ------------------------------------------------------------------------- - // Normal map shader - // - Blinn-Phong - // - normal + diffuse + specular + AO + displacement + reflection + shadow maps - // - point and directional lights (use with "lights: true" material option) - ------------------------------------------------------------------------- */ + initCustomAttributes ( geometry, object ); - 'normalmap' : { + }; - uniforms: THREE.UniformsUtils.merge( [ + function initMeshBuffers ( geometryGroup, object ) { - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - THREE.UniformsLib[ "shadowmap" ], + var geometry = object.geometry, + faces3 = geometryGroup.faces3, - { + nvertices = faces3.length * 3, + ntris = faces3.length * 1, + nlines = faces3.length * 3, - "enableAO" : { type: "i", value: 0 }, - "enableDiffuse" : { type: "i", value: 0 }, - "enableSpecular" : { type: "i", value: 0 }, - "enableReflection": { type: "i", value: 0 }, - "enableDisplacement": { type: "i", value: 0 }, + material = getBufferMaterial( object, geometryGroup ), - "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture - "tDiffuse" : { type: "t", value: null }, - "tCube" : { type: "t", value: null }, - "tNormal" : { type: "t", value: null }, - "tSpecular" : { type: "t", value: null }, - "tAO" : { type: "t", value: null }, + uvType = bufferGuessUVType( material ), + normalType = bufferGuessNormalType( material ), + vertexColorType = bufferGuessVertexColorType( material ); - "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) }, + // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material ); - "uDisplacementBias": { type: "f", value: 0.0 }, - "uDisplacementScale": { type: "f", value: 1.0 }, + geometryGroup.__vertexArray = new Float32Array( nvertices * 3 ); - "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) }, - "specular": { type: "c", value: new THREE.Color( 0x111111 ) }, - "ambient": { type: "c", value: new THREE.Color( 0xffffff ) }, - "shininess": { type: "f", value: 30 }, - "opacity": { type: "f", value: 1 }, + if ( normalType ) { - "useRefract": { type: "i", value: 0 }, - "refractionRatio": { type: "f", value: 0.98 }, - "reflectivity": { type: "f", value: 0.5 }, + geometryGroup.__normalArray = new Float32Array( nvertices * 3 ); - "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) }, - "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }, + } - "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } + if ( geometry.hasTangents ) { - } + geometryGroup.__tangentArray = new Float32Array( nvertices * 4 ); - ] ), + } - fragmentShader: [ + if ( vertexColorType ) { - "uniform vec3 ambient;", - "uniform vec3 diffuse;", - "uniform vec3 specular;", - "uniform float shininess;", - "uniform float opacity;", + geometryGroup.__colorArray = new Float32Array( nvertices * 3 ); - "uniform bool enableDiffuse;", - "uniform bool enableSpecular;", - "uniform bool enableAO;", - "uniform bool enableReflection;", + } - "uniform sampler2D tDiffuse;", - "uniform sampler2D tNormal;", - "uniform sampler2D tSpecular;", - "uniform sampler2D tAO;", + if ( uvType ) { - "uniform samplerCube tCube;", + if ( geometry.faceVertexUvs.length > 0 ) { - "uniform vec2 uNormalScale;", + geometryGroup.__uvArray = new Float32Array( nvertices * 2 ); - "uniform bool useRefract;", - "uniform float refractionRatio;", - "uniform float reflectivity;", + } - "varying vec3 vTangent;", - "varying vec3 vBinormal;", - "varying vec3 vNormal;", - "varying vec2 vUv;", + if ( geometry.faceVertexUvs.length > 1 ) { - "uniform vec3 ambientLightColor;", + geometryGroup.__uv2Array = new Float32Array( nvertices * 2 ); - "#if MAX_DIR_LIGHTS > 0", + } - " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];", - " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];", + } - "#endif", + if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) { - "#if MAX_HEMI_LIGHTS > 0", + geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 ); + geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 ); - " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];", - " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];", - " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];", + } - "#endif", + var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3 - "#if MAX_POINT_LIGHTS > 0", + geometryGroup.__typeArray = UintArray; + geometryGroup.__faceArray = new UintArray( ntris * 3 ); + geometryGroup.__lineArray = new UintArray( nlines * 2 ); - " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];", - " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];", - " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];", + var m, ml; - "#endif", + if ( geometryGroup.numMorphTargets ) { - "#if MAX_SPOT_LIGHTS > 0", + geometryGroup.__morphTargetsArrays = []; - " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];", - " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];", - " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];", - " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];", - " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];", - " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];", + for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { - "#endif", + geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) ); - "#ifdef WRAP_AROUND", + } - " uniform vec3 wrapRGB;", + } - "#endif", + if ( geometryGroup.numMorphNormals ) { - "varying vec3 vWorldPosition;", - "varying vec3 vViewPosition;", + geometryGroup.__morphNormalsArrays = []; - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { - "void main() {", - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) ); - " gl_FragColor = vec4( vec3( 1.0 ), opacity );", + } - " vec3 specularTex = vec3( 1.0 );", + } - " vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;", - " normalTex.xy *= uNormalScale;", - " normalTex = normalize( normalTex );", + geometryGroup.__webglFaceCount = ntris * 3; + geometryGroup.__webglLineCount = nlines * 2; - " if( enableDiffuse ) {", - " #ifdef GAMMA_INPUT", + // custom attributes - " vec4 texelColor = texture2D( tDiffuse, vUv );", - " texelColor.xyz *= texelColor.xyz;", + if ( material.attributes ) { - " gl_FragColor = gl_FragColor * texelColor;", + if ( geometryGroup.__webglCustomAttributesList === undefined ) { - " #else", + geometryGroup.__webglCustomAttributesList = []; - " gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );", + } - " #endif", + for ( var a in material.attributes ) { - " }", + // Do a shallow copy of the attribute object so different geometryGroup chunks use different + // attribute buffers which are correctly indexed in the setMeshBuffers function - " if( enableAO ) {", + var originalAttribute = material.attributes[ a ]; - " #ifdef GAMMA_INPUT", + var attribute = {}; - " vec4 aoColor = texture2D( tAO, vUv );", - " aoColor.xyz *= aoColor.xyz;", + for ( var property in originalAttribute ) { - " gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;", + attribute[ property ] = originalAttribute[ property ]; - " #else", + } - " gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;", + if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) { - " #endif", + attribute.__webglInitialized = true; - " }", + var size = 1; // "f" and "i" - " if( enableSpecular )", - " specularTex = texture2D( tSpecular, vUv ).xyz;", + if ( attribute.type === 'v2' ) size = 2; + else if ( attribute.type === 'v3' ) size = 3; + else if ( attribute.type === 'v4' ) size = 4; + else if ( attribute.type === 'c' ) size = 3; - " mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );", - " vec3 finalNormal = tsb * normalTex;", + attribute.size = size; - " #ifdef FLIP_SIDED", + attribute.array = new Float32Array( nvertices * size ); - " finalNormal = -finalNormal;", + attribute.buffer = _gl.createBuffer(); + attribute.buffer.belongsToAttribute = a; - " #endif", + originalAttribute.needsUpdate = true; + attribute.__original = originalAttribute; - " vec3 normal = normalize( finalNormal );", - " vec3 viewPosition = normalize( vViewPosition );", + } - // point lights + geometryGroup.__webglCustomAttributesList.push( attribute ); - " #if MAX_POINT_LIGHTS > 0", + } - " vec3 pointDiffuse = vec3( 0.0 );", - " vec3 pointSpecular = vec3( 0.0 );", + } - " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {", + geometryGroup.__inittedArrays = true; - " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );", - " vec3 pointVector = lPosition.xyz + vViewPosition.xyz;", + }; - " float pointDistance = 1.0;", - " if ( pointLightDistance[ i ] > 0.0 )", - " pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );", + function getBufferMaterial( object, geometryGroup ) { - " pointVector = normalize( pointVector );", + return object.material instanceof THREE.MeshFaceMaterial + ? object.material.materials[ geometryGroup.materialIndex ] + : object.material; - // diffuse + }; - " #ifdef WRAP_AROUND", + function materialNeedsSmoothNormals ( material ) { - " float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );", - " float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );", + return material && material.shading !== undefined && material.shading === THREE.SmoothShading; - " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );", + }; - " #else", + function bufferGuessNormalType ( material ) { - " float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );", + // only MeshBasicMaterial and MeshDepthMaterial don't need normals - " #endif", + if ( ( material instanceof THREE.MeshBasicMaterial && ! material.envMap ) || material instanceof THREE.MeshDepthMaterial ) { - " pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;", + return false; - // specular + } - " vec3 pointHalfVector = normalize( pointVector + viewPosition );", - " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );", - " float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );", + if ( materialNeedsSmoothNormals( material ) ) { - // 2.0 => 2.0001 is hack to work around ANGLE bug + return THREE.SmoothShading; - " float specularNormalization = ( shininess + 2.0001 ) / 8.0;", + } else { - " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );", - " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;", + return THREE.FlatShading; - " }", + } - " #endif", + }; - // spot lights + function bufferGuessVertexColorType( material ) { - " #if MAX_SPOT_LIGHTS > 0", + if ( material.vertexColors ) { - " vec3 spotDiffuse = vec3( 0.0 );", - " vec3 spotSpecular = vec3( 0.0 );", + return material.vertexColors; - " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {", + } - " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );", - " vec3 spotVector = lPosition.xyz + vViewPosition.xyz;", + return false; - " float spotDistance = 1.0;", - " if ( spotLightDistance[ i ] > 0.0 )", - " spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );", + }; - " spotVector = normalize( spotVector );", + function bufferGuessUVType( material ) { - " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );", + // material must use some texture to require uvs - " if ( spotEffect > spotLightAngleCos[ i ] ) {", + if ( material.map || + material.lightMap || + material.bumpMap || + material.normalMap || + material.specularMap || + material.alphaMap || + material instanceof THREE.ShaderMaterial ) { - " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );", + return true; - // diffuse + } - " #ifdef WRAP_AROUND", + return false; - " float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );", - " float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );", + }; - " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );", + // - " #else", + function initDirectBuffers( geometry ) { - " float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );", + for ( var name in geometry.attributes ) { - " #endif", + var bufferType = ( name === 'index' ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER; - " spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;", + var attribute = geometry.attributes[ name ]; + attribute.buffer = _gl.createBuffer(); - // specular + _gl.bindBuffer( bufferType, attribute.buffer ); + _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW ); - " vec3 spotHalfVector = normalize( spotVector + viewPosition );", - " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );", - " float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );", + } - // 2.0 => 2.0001 is hack to work around ANGLE bug + } - " float specularNormalization = ( shininess + 2.0001 ) / 8.0;", + // Buffer setting - " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );", - " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;", + function setParticleBuffers ( geometry, hint, object ) { - " }", + var v, c, vertex, offset, index, color, - " }", + vertices = geometry.vertices, + vl = vertices.length, - " #endif", + colors = geometry.colors, + cl = colors.length, - // directional lights + vertexArray = geometry.__vertexArray, + colorArray = geometry.__colorArray, - " #if MAX_DIR_LIGHTS > 0", + sortArray = geometry.__sortArray, - " vec3 dirDiffuse = vec3( 0.0 );", - " vec3 dirSpecular = vec3( 0.0 );", + dirtyVertices = geometry.verticesNeedUpdate, + dirtyElements = geometry.elementsNeedUpdate, + dirtyColors = geometry.colorsNeedUpdate, - " for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {", + customAttributes = geometry.__webglCustomAttributesList, + i, il, + a, ca, cal, value, + customAttribute; - " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );", - " vec3 dirVector = normalize( lDirection.xyz );", + if ( object.sortParticles ) { - // diffuse + _projScreenMatrixPS.copy( _projScreenMatrix ); + _projScreenMatrixPS.multiply( object.matrixWorld ); - " #ifdef WRAP_AROUND", + for ( v = 0; v < vl; v ++ ) { - " float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );", - " float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );", + vertex = vertices[ v ]; - " vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );", + _vector3.copy( vertex ); + _vector3.applyProjection( _projScreenMatrixPS ); - " #else", + sortArray[ v ] = [ _vector3.z, v ]; - " float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );", + } - " #endif", + sortArray.sort( numericalSort ); - " dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;", + for ( v = 0; v < vl; v ++ ) { - // specular + vertex = vertices[ sortArray[ v ][ 1 ] ]; - " vec3 dirHalfVector = normalize( dirVector + viewPosition );", - " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );", - " float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );", + offset = v * 3; - // 2.0 => 2.0001 is hack to work around ANGLE bug + vertexArray[ offset ] = vertex.x; + vertexArray[ offset + 1 ] = vertex.y; + vertexArray[ offset + 2 ] = vertex.z; - " float specularNormalization = ( shininess + 2.0001 ) / 8.0;", + } - " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );", - " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;", + for ( c = 0; c < cl; c ++ ) { - " }", + offset = c * 3; - " #endif", + color = colors[ sortArray[ c ][ 1 ] ]; - // hemisphere lights + colorArray[ offset ] = color.r; + colorArray[ offset + 1 ] = color.g; + colorArray[ offset + 2 ] = color.b; - " #if MAX_HEMI_LIGHTS > 0", + } - " vec3 hemiDiffuse = vec3( 0.0 );", - " vec3 hemiSpecular = vec3( 0.0 );" , + if ( customAttributes ) { - " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {", + for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );", - " vec3 lVector = normalize( lDirection.xyz );", + customAttribute = customAttributes[ i ]; - // diffuse + if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) continue; - " float dotProduct = dot( normal, lVector );", - " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;", + offset = 0; - " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );", + cal = customAttribute.value.length; - " hemiDiffuse += diffuse * hemiColor;", + if ( customAttribute.size === 1 ) { - // specular (sky light) + for ( ca = 0; ca < cal; ca ++ ) { + index = sortArray[ ca ][ 1 ]; - " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );", - " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;", - " float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );", + customAttribute.array[ ca ] = customAttribute.value[ index ]; - // specular (ground light) + } - " vec3 lVectorGround = -lVector;", + } else if ( customAttribute.size === 2 ) { - " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );", - " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;", - " float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );", + for ( ca = 0; ca < cal; ca ++ ) { - " float dotProductGround = dot( normal, lVectorGround );", + index = sortArray[ ca ][ 1 ]; - // 2.0 => 2.0001 is hack to work around ANGLE bug + value = customAttribute.value[ index ]; - " float specularNormalization = ( shininess + 2.0001 ) / 8.0;", + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; - " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );", - " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );", - " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );", + offset += 2; - " }", + } - " #endif", + } else if ( customAttribute.size === 3 ) { - // all lights contribution summation + if ( customAttribute.type === 'c' ) { - " vec3 totalDiffuse = vec3( 0.0 );", - " vec3 totalSpecular = vec3( 0.0 );", + for ( ca = 0; ca < cal; ca ++ ) { - " #if MAX_DIR_LIGHTS > 0", + index = sortArray[ ca ][ 1 ]; - " totalDiffuse += dirDiffuse;", - " totalSpecular += dirSpecular;", + value = customAttribute.value[ index ]; - " #endif", + customAttribute.array[ offset ] = value.r; + customAttribute.array[ offset + 1 ] = value.g; + customAttribute.array[ offset + 2 ] = value.b; - " #if MAX_HEMI_LIGHTS > 0", + offset += 3; - " totalDiffuse += hemiDiffuse;", - " totalSpecular += hemiSpecular;", + } - " #endif", + } else { - " #if MAX_POINT_LIGHTS > 0", + for ( ca = 0; ca < cal; ca ++ ) { - " totalDiffuse += pointDiffuse;", - " totalSpecular += pointSpecular;", + index = sortArray[ ca ][ 1 ]; - " #endif", + value = customAttribute.value[ index ]; - " #if MAX_SPOT_LIGHTS > 0", + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; + customAttribute.array[ offset + 2 ] = value.z; - " totalDiffuse += spotDiffuse;", - " totalSpecular += spotSpecular;", - - " #endif", + offset += 3; - " #ifdef METAL", + } - " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );", + } - " #else", + } else if ( customAttribute.size === 4 ) { - " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;", + for ( ca = 0; ca < cal; ca ++ ) { - " #endif", + index = sortArray[ ca ][ 1 ]; - " if ( enableReflection ) {", + value = customAttribute.value[ index ]; - " vec3 vReflect;", - " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );", + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; + customAttribute.array[ offset + 2 ] = value.z; + customAttribute.array[ offset + 3 ] = value.w; - " if ( useRefract ) {", + offset += 4; - " vReflect = refract( cameraToVertex, normal, refractionRatio );", + } - " } else {", + } - " vReflect = reflect( cameraToVertex, normal );", + } - " }", + } - " vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );", + } else { - " #ifdef GAMMA_INPUT", + if ( dirtyVertices ) { - " cubeColor.xyz *= cubeColor.xyz;", + for ( v = 0; v < vl; v ++ ) { - " #endif", + vertex = vertices[ v ]; - " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );", + offset = v * 3; - " }", + vertexArray[ offset ] = vertex.x; + vertexArray[ offset + 1 ] = vertex.y; + vertexArray[ offset + 2 ] = vertex.z; - THREE.ShaderChunk[ "shadowmap_fragment" ], - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], - THREE.ShaderChunk[ "fog_fragment" ], + } - "}" + } - ].join("\n"), + if ( dirtyColors ) { - vertexShader: [ + for ( c = 0; c < cl; c ++ ) { - "attribute vec4 tangent;", + color = colors[ c ]; - "uniform vec2 uOffset;", - "uniform vec2 uRepeat;", + offset = c * 3; - "uniform bool enableDisplacement;", + colorArray[ offset ] = color.r; + colorArray[ offset + 1 ] = color.g; + colorArray[ offset + 2 ] = color.b; - "#ifdef VERTEX_TEXTURES", + } - " uniform sampler2D tDisplacement;", - " uniform float uDisplacementScale;", - " uniform float uDisplacementBias;", + } - "#endif", + if ( customAttributes ) { - "varying vec3 vTangent;", - "varying vec3 vBinormal;", - "varying vec3 vNormal;", - "varying vec2 vUv;", + for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - "varying vec3 vWorldPosition;", - "varying vec3 vViewPosition;", + customAttribute = customAttributes[ i ]; - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + if ( customAttribute.needsUpdate && + ( customAttribute.boundTo === undefined || + customAttribute.boundTo === 'vertices' ) ) { - "void main() {", + cal = customAttribute.value.length; - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], + offset = 0; - // normal, tangent and binormal vectors + if ( customAttribute.size === 1 ) { - " #ifdef USE_SKINNING", + for ( ca = 0; ca < cal; ca ++ ) { - " vNormal = normalize( normalMatrix * skinnedNormal.xyz );", + customAttribute.array[ ca ] = customAttribute.value[ ca ]; - " vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );", - " vTangent = normalize( normalMatrix * skinnedTangent.xyz );", + } - " #else", + } else if ( customAttribute.size === 2 ) { - " vNormal = normalize( normalMatrix * normal );", - " vTangent = normalize( normalMatrix * tangent.xyz );", + for ( ca = 0; ca < cal; ca ++ ) { - " #endif", + value = customAttribute.value[ ca ]; - " vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );", + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; - " vUv = uv * uRepeat + uOffset;", + offset += 2; - // displacement mapping + } - " vec3 displacedPosition;", + } else if ( customAttribute.size === 3 ) { - " #ifdef VERTEX_TEXTURES", + if ( customAttribute.type === 'c' ) { - " if ( enableDisplacement ) {", + for ( ca = 0; ca < cal; ca ++ ) { - " vec3 dv = texture2D( tDisplacement, uv ).xyz;", - " float df = uDisplacementScale * dv.x + uDisplacementBias;", - " displacedPosition = position + normalize( normal ) * df;", + value = customAttribute.value[ ca ]; - " } else {", + customAttribute.array[ offset ] = value.r; + customAttribute.array[ offset + 1 ] = value.g; + customAttribute.array[ offset + 2 ] = value.b; - " #ifdef USE_SKINNING", + offset += 3; - " vec4 skinVertex = vec4( position, 1.0 );", + } - " vec4 skinned = boneMatX * skinVertex * skinWeight.x;", - " skinned += boneMatY * skinVertex * skinWeight.y;", - " skinned += boneMatZ * skinVertex * skinWeight.z;", - " skinned += boneMatW * skinVertex * skinWeight.w;", + } else { - " displacedPosition = skinned.xyz;", + for ( ca = 0; ca < cal; ca ++ ) { - " #else", + value = customAttribute.value[ ca ]; - " displacedPosition = position;", + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; + customAttribute.array[ offset + 2 ] = value.z; - " #endif", + offset += 3; - " }", + } - " #else", + } - " #ifdef USE_SKINNING", + } else if ( customAttribute.size === 4 ) { - " vec4 skinVertex = vec4( position, 1.0 );", + for ( ca = 0; ca < cal; ca ++ ) { - " vec4 skinned = boneMatX * skinVertex * skinWeight.x;", - " skinned += boneMatY * skinVertex * skinWeight.y;", - " skinned += boneMatZ * skinVertex * skinWeight.z;", - " skinned += boneMatW * skinVertex * skinWeight.w;", + value = customAttribute.value[ ca ]; - " displacedPosition = skinned.xyz;", + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; + customAttribute.array[ offset + 2 ] = value.z; + customAttribute.array[ offset + 3 ] = value.w; - " #else", + offset += 4; - " displacedPosition = position;", + } - " #endif", + } - " #endif", + } - // + } - " vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );", - " vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );", + } - " gl_Position = projectionMatrix * mvPosition;", + } - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + if ( dirtyVertices || object.sortParticles ) { - // + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); - " vWorldPosition = worldPosition.xyz;", - " vViewPosition = -mvPosition.xyz;", + } - // shadows + if ( dirtyColors || object.sortParticles ) { - " #ifdef USE_SHADOWMAP", + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); - " for( int i = 0; i < MAX_SHADOWS; i ++ ) {", + } - " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;", + if ( customAttributes ) { - " }", + for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - " #endif", + customAttribute = customAttributes[ i ]; - "}" + if ( customAttribute.needsUpdate || object.sortParticles ) { - ].join("\n") + _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); - }, + } - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + } - 'cube': { + } - uniforms: { "tCube": { type: "t", value: null }, - "tFlip": { type: "f", value: -1 } }, + } - vertexShader: [ + function setLineBuffers ( geometry, hint ) { - "varying vec3 vWorldPosition;", + var v, c, d, vertex, offset, color, - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + vertices = geometry.vertices, + colors = geometry.colors, + lineDistances = geometry.lineDistances, - "void main() {", + vl = vertices.length, + cl = colors.length, + dl = lineDistances.length, - " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );", - " vWorldPosition = worldPosition.xyz;", + vertexArray = geometry.__vertexArray, + colorArray = geometry.__colorArray, + lineDistanceArray = geometry.__lineDistanceArray, - " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", + dirtyVertices = geometry.verticesNeedUpdate, + dirtyColors = geometry.colorsNeedUpdate, + dirtyLineDistances = geometry.lineDistancesNeedUpdate, - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + customAttributes = geometry.__webglCustomAttributesList, - "}" + i, il, + a, ca, cal, value, + customAttribute; - ].join("\n"), + if ( dirtyVertices ) { - fragmentShader: [ + for ( v = 0; v < vl; v ++ ) { - "uniform samplerCube tCube;", - "uniform float tFlip;", + vertex = vertices[ v ]; - "varying vec3 vWorldPosition;", + offset = v * 3; - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + vertexArray[ offset ] = vertex.x; + vertexArray[ offset + 1 ] = vertex.y; + vertexArray[ offset + 2 ] = vertex.z; - "void main() {", + } - " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );", + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + } - "}" + if ( dirtyColors ) { - ].join("\n") + for ( c = 0; c < cl; c ++ ) { - }, + color = colors[ c ]; - // Depth encoding into RGBA texture - // based on SpiderGL shadow map example - // http://spidergl.org/example.php?id=6 - // originally from - // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD - // see also here: - // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/ + offset = c * 3; - 'depthRGBA': { - - uniforms: {}, - - vertexShader: [ + colorArray[ offset ] = color.r; + colorArray[ offset + 1 ] = color.g; + colorArray[ offset + 2 ] = color.b; - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + } - "void main() {", + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + } - "}" + if ( dirtyLineDistances ) { - ].join("\n"), + for ( d = 0; d < dl; d ++ ) { - fragmentShader: [ + lineDistanceArray[ d ] = lineDistances[ d ]; - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + } - "vec4 pack_depth( const in float depth ) {", + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint ); - " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );", - " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );", - " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );", - " res -= res.xxyz * bit_mask;", - " return res;", + } - "}", + if ( customAttributes ) { - "void main() {", + for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + customAttribute = customAttributes[ i ]; - " #ifdef USE_LOGDEPTHBUF_EXT", + if ( customAttribute.needsUpdate && + ( customAttribute.boundTo === undefined || + customAttribute.boundTo === 'vertices' ) ) { - " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );", + offset = 0; - " #else", + cal = customAttribute.value.length; - " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );", + if ( customAttribute.size === 1 ) { - " #endif", + for ( ca = 0; ca < cal; ca ++ ) { - //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );", - //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );", - //"gl_FragData[ 0 ] = pack_depth( z );", - //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );", + customAttribute.array[ ca ] = customAttribute.value[ ca ]; - "}" + } - ].join("\n") + } else if ( customAttribute.size === 2 ) { - } + for ( ca = 0; ca < cal; ca ++ ) { -}; + value = customAttribute.value[ ca ]; -/** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; -THREE.WebGLRenderer = function ( parameters ) { + offset += 2; - console.log( 'THREE.WebGLRenderer', THREE.REVISION ); + } - parameters = parameters || {}; + } else if ( customAttribute.size === 3 ) { - var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ), - _context = parameters.context !== undefined ? parameters.context : null, + if ( customAttribute.type === 'c' ) { - _precision = parameters.precision !== undefined ? parameters.precision : 'highp', + for ( ca = 0; ca < cal; ca ++ ) { - _buffers = {}, + value = customAttribute.value[ ca ]; - _alpha = parameters.alpha !== undefined ? parameters.alpha : false, - _depth = parameters.depth !== undefined ? parameters.depth : true, - _stencil = parameters.stencil !== undefined ? parameters.stencil : true, - _antialias = parameters.antialias !== undefined ? parameters.antialias : false, - _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, - _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, - _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false, + customAttribute.array[ offset ] = value.r; + customAttribute.array[ offset + 1 ] = value.g; + customAttribute.array[ offset + 2 ] = value.b; - _clearColor = new THREE.Color( 0x000000 ), - _clearAlpha = 0; + offset += 3; - // public properties + } - this.domElement = _canvas; - this.context = null; - this.devicePixelRatio = parameters.devicePixelRatio !== undefined - ? parameters.devicePixelRatio - : self.devicePixelRatio !== undefined - ? self.devicePixelRatio - : 1; + } else { - // clearing + for ( ca = 0; ca < cal; ca ++ ) { - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; + value = customAttribute.value[ ca ]; - // scene graph + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; + customAttribute.array[ offset + 2 ] = value.z; - this.sortObjects = true; - this.autoUpdateObjects = true; + offset += 3; - // physically based shading + } - this.gammaInput = false; - this.gammaOutput = false; + } - // shadow map + } else if ( customAttribute.size === 4 ) { - this.shadowMapEnabled = false; - this.shadowMapAutoUpdate = true; - this.shadowMapType = THREE.PCFShadowMap; - this.shadowMapCullFace = THREE.CullFaceFront; - this.shadowMapDebug = false; - this.shadowMapCascade = false; + for ( ca = 0; ca < cal; ca ++ ) { - // morphs + value = customAttribute.value[ ca ]; - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; + customAttribute.array[ offset + 2 ] = value.z; + customAttribute.array[ offset + 3 ] = value.w; - // flags + offset += 4; - this.autoScaleCubemaps = true; + } - // custom render plugins + } - this.renderPluginsPre = []; - this.renderPluginsPost = []; + _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); - // info + } - this.info = { + } - memory: { + } - programs: 0, - geometries: 0, - textures: 0 + } - }, + function setMeshBuffers( geometryGroup, object, hint, dispose, material ) { - render: { + if ( ! geometryGroup.__inittedArrays ) { - calls: 0, - vertices: 0, - faces: 0, - points: 0 + return; } - }; + var normalType = bufferGuessNormalType( material ), + vertexColorType = bufferGuessVertexColorType( material ), + uvType = bufferGuessUVType( material ), - // internal properties + needsSmoothNormals = ( normalType === THREE.SmoothShading ); - var _this = this, + var f, fl, fi, face, + vertexNormals, faceNormal, normal, + vertexColors, faceColor, + vertexTangents, + uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4, + c1, c2, c3, + sw1, sw2, sw3, sw4, + si1, si2, si3, si4, + sa1, sa2, sa3, sa4, + sb1, sb2, sb3, sb4, + m, ml, i, il, + vn, uvi, uv2i, + vk, vkl, vka, + nka, chf, faceVertexNormals, + a, - _programs = [], + vertexIndex = 0, - // internal state cache + offset = 0, + offset_uv = 0, + offset_uv2 = 0, + offset_face = 0, + offset_normal = 0, + offset_tangent = 0, + offset_line = 0, + offset_color = 0, + offset_skin = 0, + offset_morphTarget = 0, + offset_custom = 0, + offset_customSrc = 0, - _currentProgram = null, - _currentFramebuffer = null, - _currentMaterialId = -1, - _currentGeometryGroupHash = null, - _currentCamera = null, + value, - _usedTextureUnits = 0, + vertexArray = geometryGroup.__vertexArray, + uvArray = geometryGroup.__uvArray, + uv2Array = geometryGroup.__uv2Array, + normalArray = geometryGroup.__normalArray, + tangentArray = geometryGroup.__tangentArray, + colorArray = geometryGroup.__colorArray, - // GL state cache + skinIndexArray = geometryGroup.__skinIndexArray, + skinWeightArray = geometryGroup.__skinWeightArray, - _oldDoubleSided = -1, - _oldFlipSided = -1, + morphTargetsArrays = geometryGroup.__morphTargetsArrays, + morphNormalsArrays = geometryGroup.__morphNormalsArrays, - _oldBlending = -1, + customAttributes = geometryGroup.__webglCustomAttributesList, + customAttribute, - _oldBlendEquation = -1, - _oldBlendSrc = -1, - _oldBlendDst = -1, + faceArray = geometryGroup.__faceArray, + lineArray = geometryGroup.__lineArray, - _oldDepthTest = -1, - _oldDepthWrite = -1, + geometry = object.geometry, // this is shared for all chunks - _oldPolygonOffset = null, - _oldPolygonOffsetFactor = null, - _oldPolygonOffsetUnits = null, + dirtyVertices = geometry.verticesNeedUpdate, + dirtyElements = geometry.elementsNeedUpdate, + dirtyUvs = geometry.uvsNeedUpdate, + dirtyNormals = geometry.normalsNeedUpdate, + dirtyTangents = geometry.tangentsNeedUpdate, + dirtyColors = geometry.colorsNeedUpdate, + dirtyMorphTargets = geometry.morphTargetsNeedUpdate, - _oldLineWidth = null, + vertices = geometry.vertices, + chunk_faces3 = geometryGroup.faces3, + obj_faces = geometry.faces, - _viewportX = 0, - _viewportY = 0, - _viewportWidth = _canvas.width, - _viewportHeight = _canvas.height, - _currentWidth = 0, - _currentHeight = 0, + obj_uvs = geometry.faceVertexUvs[ 0 ], + obj_uvs2 = geometry.faceVertexUvs[ 1 ], - _newAttributes = new Uint8Array( 16 ), - _enabledAttributes = new Uint8Array( 16 ), + obj_colors = geometry.colors, - // frustum + obj_skinIndices = geometry.skinIndices, + obj_skinWeights = geometry.skinWeights, - _frustum = new THREE.Frustum(), - - // camera matrices cache + morphTargets = geometry.morphTargets, + morphNormals = geometry.morphNormals; - _projScreenMatrix = new THREE.Matrix4(), - _projScreenMatrixPS = new THREE.Matrix4(), + if ( dirtyVertices ) { - _vector3 = new THREE.Vector3(), + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - // light arrays cache + face = obj_faces[ chunk_faces3[ f ] ]; - _direction = new THREE.Vector3(), + v1 = vertices[ face.a ]; + v2 = vertices[ face.b ]; + v3 = vertices[ face.c ]; - _lightsNeedUpdate = true, + vertexArray[ offset ] = v1.x; + vertexArray[ offset + 1 ] = v1.y; + vertexArray[ offset + 2 ] = v1.z; - _lights = { + vertexArray[ offset + 3 ] = v2.x; + vertexArray[ offset + 4 ] = v2.y; + vertexArray[ offset + 5 ] = v2.z; - ambient: [ 0, 0, 0 ], - directional: { length: 0, colors: new Array(), positions: new Array() }, - point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() }, - spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() }, - hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() } + vertexArray[ offset + 6 ] = v3.x; + vertexArray[ offset + 7 ] = v3.y; + vertexArray[ offset + 8 ] = v3.z; - }; + offset += 9; - // initialize + } - var _gl; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); - var _glExtensionTextureFloat; - var _glExtensionTextureFloatLinear; - var _glExtensionStandardDerivatives; - var _glExtensionTextureFilterAnisotropic; - var _glExtensionCompressedTextureS3TC; - var _glExtensionElementIndexUint; - var _glExtensionFragDepth; + } + if ( dirtyMorphTargets ) { - initGL(); + for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) { - setDefaultGLState(); + offset_morphTarget = 0; - this.context = _gl; + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - // GPU capabilities + chf = chunk_faces3[ f ]; + face = obj_faces[ chf ]; - var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS ); - var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); - var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ); - var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE ); + // morph positions - var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0; + v1 = morphTargets[ vk ].vertices[ face.a ]; + v2 = morphTargets[ vk ].vertices[ face.b ]; + v3 = morphTargets[ vk ].vertices[ face.c ]; - var _supportsVertexTextures = ( _maxVertexTextures > 0 ); - var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat; + vka = morphTargetsArrays[ vk ]; - var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : []; + vka[ offset_morphTarget ] = v1.x; + vka[ offset_morphTarget + 1 ] = v1.y; + vka[ offset_morphTarget + 2 ] = v1.z; - // + vka[ offset_morphTarget + 3 ] = v2.x; + vka[ offset_morphTarget + 4 ] = v2.y; + vka[ offset_morphTarget + 5 ] = v2.z; - var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT ); - var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT ); - var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT ); + vka[ offset_morphTarget + 6 ] = v3.x; + vka[ offset_morphTarget + 7 ] = v3.y; + vka[ offset_morphTarget + 8 ] = v3.z; - var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT ); - var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT ); - var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT ); + // morph normals - /* - var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT ); - var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT ); - var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT ); + if ( material.morphNormals ) { - var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT ); - var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT ); - var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT ); - */ + if ( needsSmoothNormals ) { - // clamp precision to maximum available + faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ]; - var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0; - var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0; + n1 = faceVertexNormals.a; + n2 = faceVertexNormals.b; + n3 = faceVertexNormals.c; - if ( _precision === "highp" && ! highpAvailable ) { + } else { - if ( mediumpAvailable ) { + n1 = morphNormals[ vk ].faceNormals[ chf ]; + n2 = n1; + n3 = n1; - _precision = "mediump"; - console.warn( "WebGLRenderer: highp not supported, using mediump" ); + } - } else { + nka = morphNormalsArrays[ vk ]; - _precision = "lowp"; - console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" ); + nka[ offset_morphTarget ] = n1.x; + nka[ offset_morphTarget + 1 ] = n1.y; + nka[ offset_morphTarget + 2 ] = n1.z; - } + nka[ offset_morphTarget + 3 ] = n2.x; + nka[ offset_morphTarget + 4 ] = n2.y; + nka[ offset_morphTarget + 5 ] = n2.z; - } + nka[ offset_morphTarget + 6 ] = n3.x; + nka[ offset_morphTarget + 7 ] = n3.y; + nka[ offset_morphTarget + 8 ] = n3.z; - if ( _precision === "mediump" && ! mediumpAvailable ) { + } - _precision = "lowp"; - console.warn( "WebGLRenderer: mediump not supported, using lowp" ); + // - } + offset_morphTarget += 9; - // API + } - this.getContext = function () { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] ); + _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint ); - return _gl; + if ( material.morphNormals ) { - }; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] ); + _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint ); - this.supportsVertexTextures = function () { + } - return _supportsVertexTextures; + } - }; + } - this.supportsFloatTextures = function () { + if ( obj_skinWeights.length ) { - return _glExtensionTextureFloat; + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - }; + face = obj_faces[ chunk_faces3[ f ] ]; - this.supportsStandardDerivatives = function () { + // weights - return _glExtensionStandardDerivatives; + sw1 = obj_skinWeights[ face.a ]; + sw2 = obj_skinWeights[ face.b ]; + sw3 = obj_skinWeights[ face.c ]; - }; + skinWeightArray[ offset_skin ] = sw1.x; + skinWeightArray[ offset_skin + 1 ] = sw1.y; + skinWeightArray[ offset_skin + 2 ] = sw1.z; + skinWeightArray[ offset_skin + 3 ] = sw1.w; - this.supportsCompressedTextureS3TC = function () { + skinWeightArray[ offset_skin + 4 ] = sw2.x; + skinWeightArray[ offset_skin + 5 ] = sw2.y; + skinWeightArray[ offset_skin + 6 ] = sw2.z; + skinWeightArray[ offset_skin + 7 ] = sw2.w; - return _glExtensionCompressedTextureS3TC; + skinWeightArray[ offset_skin + 8 ] = sw3.x; + skinWeightArray[ offset_skin + 9 ] = sw3.y; + skinWeightArray[ offset_skin + 10 ] = sw3.z; + skinWeightArray[ offset_skin + 11 ] = sw3.w; - }; + // indices - this.getMaxAnisotropy = function () { + si1 = obj_skinIndices[ face.a ]; + si2 = obj_skinIndices[ face.b ]; + si3 = obj_skinIndices[ face.c ]; - return _maxAnisotropy; + skinIndexArray[ offset_skin ] = si1.x; + skinIndexArray[ offset_skin + 1 ] = si1.y; + skinIndexArray[ offset_skin + 2 ] = si1.z; + skinIndexArray[ offset_skin + 3 ] = si1.w; - }; + skinIndexArray[ offset_skin + 4 ] = si2.x; + skinIndexArray[ offset_skin + 5 ] = si2.y; + skinIndexArray[ offset_skin + 6 ] = si2.z; + skinIndexArray[ offset_skin + 7 ] = si2.w; - this.getPrecision = function () { + skinIndexArray[ offset_skin + 8 ] = si3.x; + skinIndexArray[ offset_skin + 9 ] = si3.y; + skinIndexArray[ offset_skin + 10 ] = si3.z; + skinIndexArray[ offset_skin + 11 ] = si3.w; - return _precision; + offset_skin += 12; - }; + } - this.setSize = function ( width, height, updateStyle ) { + if ( offset_skin > 0 ) { - _canvas.width = width * this.devicePixelRatio; - _canvas.height = height * this.devicePixelRatio; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint ); - if ( updateStyle !== false ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint ); - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; + } } - this.setViewport( 0, 0, width, height ); + if ( dirtyColors && vertexColorType ) { - }; + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - this.setViewport = function ( x, y, width, height ) { + face = obj_faces[ chunk_faces3[ f ] ]; - _viewportX = x * this.devicePixelRatio; - _viewportY = y * this.devicePixelRatio; + vertexColors = face.vertexColors; + faceColor = face.color; - _viewportWidth = width * this.devicePixelRatio; - _viewportHeight = height * this.devicePixelRatio; + if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) { - _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); + c1 = vertexColors[ 0 ]; + c2 = vertexColors[ 1 ]; + c3 = vertexColors[ 2 ]; - }; + } else { - this.setScissor = function ( x, y, width, height ) { + c1 = faceColor; + c2 = faceColor; + c3 = faceColor; - _gl.scissor( - x * this.devicePixelRatio, - y * this.devicePixelRatio, - width * this.devicePixelRatio, - height * this.devicePixelRatio - ); + } - }; + colorArray[ offset_color ] = c1.r; + colorArray[ offset_color + 1 ] = c1.g; + colorArray[ offset_color + 2 ] = c1.b; - this.enableScissorTest = function ( enable ) { + colorArray[ offset_color + 3 ] = c2.r; + colorArray[ offset_color + 4 ] = c2.g; + colorArray[ offset_color + 5 ] = c2.b; - enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST ); + colorArray[ offset_color + 6 ] = c3.r; + colorArray[ offset_color + 7 ] = c3.g; + colorArray[ offset_color + 8 ] = c3.b; - }; + offset_color += 9; - // Clearing + } - this.setClearColor = function ( color, alpha ) { + if ( offset_color > 0 ) { - _clearColor.set( color ); - _clearAlpha = alpha !== undefined ? alpha : 1; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); - _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + } - }; + } - this.setClearColorHex = function ( hex, alpha ) { + if ( dirtyTangents && geometry.hasTangents ) { - console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' ); - this.setClearColor( hex, alpha ); + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - }; - - this.getClearColor = function () { + face = obj_faces[ chunk_faces3[ f ] ]; - return _clearColor; + vertexTangents = face.vertexTangents; - }; + t1 = vertexTangents[ 0 ]; + t2 = vertexTangents[ 1 ]; + t3 = vertexTangents[ 2 ]; - this.getClearAlpha = function () { + tangentArray[ offset_tangent ] = t1.x; + tangentArray[ offset_tangent + 1 ] = t1.y; + tangentArray[ offset_tangent + 2 ] = t1.z; + tangentArray[ offset_tangent + 3 ] = t1.w; - return _clearAlpha; + tangentArray[ offset_tangent + 4 ] = t2.x; + tangentArray[ offset_tangent + 5 ] = t2.y; + tangentArray[ offset_tangent + 6 ] = t2.z; + tangentArray[ offset_tangent + 7 ] = t2.w; - }; + tangentArray[ offset_tangent + 8 ] = t3.x; + tangentArray[ offset_tangent + 9 ] = t3.y; + tangentArray[ offset_tangent + 10 ] = t3.z; + tangentArray[ offset_tangent + 11 ] = t3.w; - this.clear = function ( color, depth, stencil ) { + offset_tangent += 12; - var bits = 0; + } - if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; - if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; - if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint ); - _gl.clear( bits ); + } - }; + if ( dirtyNormals && normalType ) { - this.clearColor = function () { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - _gl.clear( _gl.COLOR_BUFFER_BIT ); + face = obj_faces[ chunk_faces3[ f ] ]; - }; + vertexNormals = face.vertexNormals; + faceNormal = face.normal; - this.clearDepth = function () { + if ( vertexNormals.length === 3 && needsSmoothNormals ) { - _gl.clear( _gl.DEPTH_BUFFER_BIT ); + for ( i = 0; i < 3; i ++ ) { - }; + vn = vertexNormals[ i ]; - this.clearStencil = function () { + normalArray[ offset_normal ] = vn.x; + normalArray[ offset_normal + 1 ] = vn.y; + normalArray[ offset_normal + 2 ] = vn.z; - _gl.clear( _gl.STENCIL_BUFFER_BIT ); + offset_normal += 3; - }; + } - this.clearTarget = function ( renderTarget, color, depth, stencil ) { + } else { - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); + for ( i = 0; i < 3; i ++ ) { - }; + normalArray[ offset_normal ] = faceNormal.x; + normalArray[ offset_normal + 1 ] = faceNormal.y; + normalArray[ offset_normal + 2 ] = faceNormal.z; - // Plugins + offset_normal += 3; - this.addPostPlugin = function ( plugin ) { + } - plugin.init( this ); - this.renderPluginsPost.push( plugin ); + } - }; + } - this.addPrePlugin = function ( plugin ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint ); - plugin.init( this ); - this.renderPluginsPre.push( plugin ); + } - }; + if ( dirtyUvs && obj_uvs && uvType ) { - // Rendering + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - this.updateShadowMap = function ( scene, camera ) { + fi = chunk_faces3[ f ]; - _currentProgram = null; - _oldBlending = -1; - _oldDepthTest = -1; - _oldDepthWrite = -1; - _currentGeometryGroupHash = -1; - _currentMaterialId = -1; - _lightsNeedUpdate = true; - _oldDoubleSided = -1; - _oldFlipSided = -1; + uv = obj_uvs[ fi ]; - this.shadowMapPlugin.update( scene, camera ); + if ( uv === undefined ) continue; - }; + for ( i = 0; i < 3; i ++ ) { - // Internal functions + uvi = uv[ i ]; - // Buffer allocation + uvArray[ offset_uv ] = uvi.x; + uvArray[ offset_uv + 1 ] = uvi.y; - function createParticleBuffers ( geometry ) { + offset_uv += 2; - geometry.__webglVertexBuffer = _gl.createBuffer(); - geometry.__webglColorBuffer = _gl.createBuffer(); + } - _this.info.memory.geometries ++; + } - }; + if ( offset_uv > 0 ) { - function createLineBuffers ( geometry ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint ); - geometry.__webglVertexBuffer = _gl.createBuffer(); - geometry.__webglColorBuffer = _gl.createBuffer(); - geometry.__webglLineDistanceBuffer = _gl.createBuffer(); + } - _this.info.memory.geometries ++; + } - }; + if ( dirtyUvs && obj_uvs2 && uvType ) { - function createMeshBuffers ( geometryGroup ) { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - geometryGroup.__webglVertexBuffer = _gl.createBuffer(); - geometryGroup.__webglNormalBuffer = _gl.createBuffer(); - geometryGroup.__webglTangentBuffer = _gl.createBuffer(); - geometryGroup.__webglColorBuffer = _gl.createBuffer(); - geometryGroup.__webglUVBuffer = _gl.createBuffer(); - geometryGroup.__webglUV2Buffer = _gl.createBuffer(); + fi = chunk_faces3[ f ]; - geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer(); - geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer(); + uv2 = obj_uvs2[ fi ]; - geometryGroup.__webglFaceBuffer = _gl.createBuffer(); - geometryGroup.__webglLineBuffer = _gl.createBuffer(); + if ( uv2 === undefined ) continue; - var m, ml; + for ( i = 0; i < 3; i ++ ) { - if ( geometryGroup.numMorphTargets ) { + uv2i = uv2[ i ]; - geometryGroup.__webglMorphTargetsBuffers = []; + uv2Array[ offset_uv2 ] = uv2i.x; + uv2Array[ offset_uv2 + 1 ] = uv2i.y; - for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { + offset_uv2 += 2; - geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() ); + } } - } - - if ( geometryGroup.numMorphNormals ) { - - geometryGroup.__webglMorphNormalsBuffers = []; - - for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { + if ( offset_uv2 > 0 ) { - geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint ); } } - _this.info.memory.geometries ++; + if ( dirtyElements ) { - }; + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - // Events + faceArray[ offset_face ] = vertexIndex; + faceArray[ offset_face + 1 ] = vertexIndex + 1; + faceArray[ offset_face + 2 ] = vertexIndex + 2; - var onGeometryDispose = function ( event ) { + offset_face += 3; - var geometry = event.target; + lineArray[ offset_line ] = vertexIndex; + lineArray[ offset_line + 1 ] = vertexIndex + 1; - geometry.removeEventListener( 'dispose', onGeometryDispose ); + lineArray[ offset_line + 2 ] = vertexIndex; + lineArray[ offset_line + 3 ] = vertexIndex + 2; - deallocateGeometry( geometry ); + lineArray[ offset_line + 4 ] = vertexIndex + 1; + lineArray[ offset_line + 5 ] = vertexIndex + 2; - }; + offset_line += 6; - var onTextureDispose = function ( event ) { + vertexIndex += 3; - var texture = event.target; + } - texture.removeEventListener( 'dispose', onTextureDispose ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); + _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint ); - deallocateTexture( texture ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); + _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint ); - _this.info.memory.textures --; + } + if ( customAttributes ) { - }; + for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - var onRenderTargetDispose = function ( event ) { + customAttribute = customAttributes[ i ]; - var renderTarget = event.target; + if ( ! customAttribute.__original.needsUpdate ) continue; - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + offset_custom = 0; + offset_customSrc = 0; - deallocateRenderTarget( renderTarget ); + if ( customAttribute.size === 1 ) { - _this.info.memory.textures --; + if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { - }; + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - var onMaterialDispose = function ( event ) { + face = obj_faces[ chunk_faces3[ f ] ]; - var material = event.target; + customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ]; + customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ]; + customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ]; - material.removeEventListener( 'dispose', onMaterialDispose ); + offset_custom += 3; - deallocateMaterial( material ); + } - }; + } else if ( customAttribute.boundTo === 'faces' ) { - // Buffer deallocation + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - var deleteBuffers = function ( geometry ) { + value = customAttribute.value[ chunk_faces3[ f ] ]; - if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer ); - if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer ); - if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer ); - if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer ); - if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer ); - if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer ); + customAttribute.array[ offset_custom ] = value; + customAttribute.array[ offset_custom + 1 ] = value; + customAttribute.array[ offset_custom + 2 ] = value; - if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer ); - if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer ); + offset_custom += 3; - if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer ); - if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer ); + } - if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer ); - // custom attributes + } - if ( geometry.__webglCustomAttributesList !== undefined ) { + } else if ( customAttribute.size === 2 ) { - for ( var id in geometry.__webglCustomAttributesList ) { + if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { - _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer ); + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - } + face = obj_faces[ chunk_faces3[ f ] ]; - } + v1 = customAttribute.value[ face.a ]; + v2 = customAttribute.value[ face.b ]; + v3 = customAttribute.value[ face.c ]; - _this.info.memory.geometries --; + customAttribute.array[ offset_custom ] = v1.x; + customAttribute.array[ offset_custom + 1 ] = v1.y; - }; + customAttribute.array[ offset_custom + 2 ] = v2.x; + customAttribute.array[ offset_custom + 3 ] = v2.y; - var deallocateGeometry = function ( geometry ) { + customAttribute.array[ offset_custom + 4 ] = v3.x; + customAttribute.array[ offset_custom + 5 ] = v3.y; - geometry.__webglInit = undefined; + offset_custom += 6; - if ( geometry instanceof THREE.BufferGeometry ) { + } - var attributes = geometry.attributes; + } else if ( customAttribute.boundTo === 'faces' ) { - for ( var key in attributes ) { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - if ( attributes[ key ].buffer !== undefined ) { + value = customAttribute.value[ chunk_faces3[ f ] ]; - _gl.deleteBuffer( attributes[ key ].buffer ); + v1 = value; + v2 = value; + v3 = value; - } + customAttribute.array[ offset_custom ] = v1.x; + customAttribute.array[ offset_custom + 1 ] = v1.y; - } + customAttribute.array[ offset_custom + 2 ] = v2.x; + customAttribute.array[ offset_custom + 3 ] = v2.y; - _this.info.memory.geometries --; + customAttribute.array[ offset_custom + 4 ] = v3.x; + customAttribute.array[ offset_custom + 5 ] = v3.y; - } else { + offset_custom += 6; - if ( geometry.geometryGroups !== undefined ) { + } - for ( var g in geometry.geometryGroups ) { + } - var geometryGroup = geometry.geometryGroups[ g ]; + } else if ( customAttribute.size === 3 ) { - if ( geometryGroup.numMorphTargets !== undefined ) { + var pp; - for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { + if ( customAttribute.type === 'c' ) { - _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] ); + pp = [ 'r', 'g', 'b' ]; - } + } else { + + pp = [ 'x', 'y', 'z' ]; } - if ( geometryGroup.numMorphNormals !== undefined ) { + if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { - for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] ); + face = obj_faces[ chunk_faces3[ f ] ]; - } + v1 = customAttribute.value[ face.a ]; + v2 = customAttribute.value[ face.b ]; + v3 = customAttribute.value[ face.c ]; - } + customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; - deleteBuffers( geometryGroup ); + customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; - } + customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; - } else { + offset_custom += 9; - deleteBuffers( geometry ); + } - } + } else if ( customAttribute.boundTo === 'faces' ) { - } + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - }; + value = customAttribute.value[ chunk_faces3[ f ] ]; - var deallocateTexture = function ( texture ) { + v1 = value; + v2 = value; + v3 = value; - if ( texture.image && texture.image.__webglTextureCube ) { + customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; - // cube texture + customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; - _gl.deleteTexture( texture.image.__webglTextureCube ); + customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; - } else { + offset_custom += 9; - // 2D texture + } - if ( ! texture.__webglInit ) return; + } else if ( customAttribute.boundTo === 'faceVertices' ) { - texture.__webglInit = false; - _gl.deleteTexture( texture.__webglTexture ); + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - } + value = customAttribute.value[ chunk_faces3[ f ] ]; - }; + v1 = value[ 0 ]; + v2 = value[ 1 ]; + v3 = value[ 2 ]; - var deallocateRenderTarget = function ( renderTarget ) { + customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; - if ( !renderTarget || ! renderTarget.__webglTexture ) return; + customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; - _gl.deleteTexture( renderTarget.__webglTexture ); + customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; - if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { + offset_custom += 9; - for ( var i = 0; i < 6; i ++ ) { + } - _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] ); - _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] ); + } - } + } else if ( customAttribute.size === 4 ) { - } else { + if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { - _gl.deleteFramebuffer( renderTarget.__webglFramebuffer ); - _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer ); + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - } + face = obj_faces[ chunk_faces3[ f ] ]; - }; + v1 = customAttribute.value[ face.a ]; + v2 = customAttribute.value[ face.b ]; + v3 = customAttribute.value[ face.c ]; - var deallocateMaterial = function ( material ) { + customAttribute.array[ offset_custom ] = v1.x; + customAttribute.array[ offset_custom + 1 ] = v1.y; + customAttribute.array[ offset_custom + 2 ] = v1.z; + customAttribute.array[ offset_custom + 3 ] = v1.w; - var program = material.program; + customAttribute.array[ offset_custom + 4 ] = v2.x; + customAttribute.array[ offset_custom + 5 ] = v2.y; + customAttribute.array[ offset_custom + 6 ] = v2.z; + customAttribute.array[ offset_custom + 7 ] = v2.w; - if ( program === undefined ) return; + customAttribute.array[ offset_custom + 8 ] = v3.x; + customAttribute.array[ offset_custom + 9 ] = v3.y; + customAttribute.array[ offset_custom + 10 ] = v3.z; + customAttribute.array[ offset_custom + 11 ] = v3.w; - material.program = undefined; + offset_custom += 12; - // only deallocate GL program if this was the last use of shared program - // assumed there is only single copy of any program in the _programs list - // (that's how it's constructed) + } - var i, il, programInfo; - var deleteProgram = false; + } else if ( customAttribute.boundTo === 'faces' ) { - for ( i = 0, il = _programs.length; i < il; i ++ ) { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - programInfo = _programs[ i ]; + value = customAttribute.value[ chunk_faces3[ f ] ]; - if ( programInfo.program === program ) { + v1 = value; + v2 = value; + v3 = value; - programInfo.usedTimes --; + customAttribute.array[ offset_custom ] = v1.x; + customAttribute.array[ offset_custom + 1 ] = v1.y; + customAttribute.array[ offset_custom + 2 ] = v1.z; + customAttribute.array[ offset_custom + 3 ] = v1.w; - if ( programInfo.usedTimes === 0 ) { + customAttribute.array[ offset_custom + 4 ] = v2.x; + customAttribute.array[ offset_custom + 5 ] = v2.y; + customAttribute.array[ offset_custom + 6 ] = v2.z; + customAttribute.array[ offset_custom + 7 ] = v2.w; - deleteProgram = true; + customAttribute.array[ offset_custom + 8 ] = v3.x; + customAttribute.array[ offset_custom + 9 ] = v3.y; + customAttribute.array[ offset_custom + 10 ] = v3.z; + customAttribute.array[ offset_custom + 11 ] = v3.w; - } + offset_custom += 12; - break; + } - } + } else if ( customAttribute.boundTo === 'faceVertices' ) { - } + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - if ( deleteProgram === true ) { + value = customAttribute.value[ chunk_faces3[ f ] ]; - // avoid using array.splice, this is costlier than creating new array from scratch + v1 = value[ 0 ]; + v2 = value[ 1 ]; + v3 = value[ 2 ]; - var newPrograms = []; + customAttribute.array[ offset_custom ] = v1.x; + customAttribute.array[ offset_custom + 1 ] = v1.y; + customAttribute.array[ offset_custom + 2 ] = v1.z; + customAttribute.array[ offset_custom + 3 ] = v1.w; - for ( i = 0, il = _programs.length; i < il; i ++ ) { + customAttribute.array[ offset_custom + 4 ] = v2.x; + customAttribute.array[ offset_custom + 5 ] = v2.y; + customAttribute.array[ offset_custom + 6 ] = v2.z; + customAttribute.array[ offset_custom + 7 ] = v2.w; - programInfo = _programs[ i ]; + customAttribute.array[ offset_custom + 8 ] = v3.x; + customAttribute.array[ offset_custom + 9 ] = v3.y; + customAttribute.array[ offset_custom + 10 ] = v3.z; + customAttribute.array[ offset_custom + 11 ] = v3.w; - if ( programInfo.program !== program ) { + offset_custom += 12; - newPrograms.push( programInfo ); + } + + } } + _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); + } - _programs = newPrograms; + } - _gl.deleteProgram( program ); + if ( dispose ) { - _this.info.memory.programs --; + delete geometryGroup.__inittedArrays; + delete geometryGroup.__colorArray; + delete geometryGroup.__normalArray; + delete geometryGroup.__tangentArray; + delete geometryGroup.__uvArray; + delete geometryGroup.__uv2Array; + delete geometryGroup.__faceArray; + delete geometryGroup.__vertexArray; + delete geometryGroup.__lineArray; + delete geometryGroup.__skinIndexArray; + delete geometryGroup.__skinWeightArray; } }; - // Buffer initialization + function setDirectBuffers( geometry, hint ) { - function initCustomAttributes ( geometry, object ) { + var attributes = geometry.attributes; - var nvertices = geometry.vertices.length; + var attributeName, attributeItem; - var material = object.material; + for ( attributeName in attributes ) { - if ( material.attributes ) { + attributeItem = attributes[ attributeName ]; - if ( geometry.__webglCustomAttributesList === undefined ) { + if ( attributeItem.needsUpdate ) { - geometry.__webglCustomAttributesList = []; + if ( attributeName === 'index' ) { - } + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer ); + _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint ); - for ( var a in material.attributes ) { + } else { - var attribute = material.attributes[ a ]; + _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint ); - if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) { + } - attribute.__webglInitialized = true; + attributeItem.needsUpdate = false; - var size = 1; // "f" and "i" + } - if ( attribute.type === "v2" ) size = 2; - else if ( attribute.type === "v3" ) size = 3; - else if ( attribute.type === "v4" ) size = 4; - else if ( attribute.type === "c" ) size = 3; + } - attribute.size = size; + } - attribute.array = new Float32Array( nvertices * size ); + // Buffer rendering - attribute.buffer = _gl.createBuffer(); - attribute.buffer.belongsToAttribute = a; + this.renderBufferImmediate = function ( object, program, material ) { - attribute.needsUpdate = true; + initAttributes(); - } + if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer(); + if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer(); + if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer(); + if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer(); - geometry.__webglCustomAttributesList.push( attribute ); + if ( object.hasPositions ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); + enableAttribute( program.attributes.position ); + _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } - }; - - function initParticleBuffers ( geometry, object ) { + if ( object.hasNormals ) { - var nvertices = geometry.vertices.length; + _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer ); - geometry.__vertexArray = new Float32Array( nvertices * 3 ); - geometry.__colorArray = new Float32Array( nvertices * 3 ); + if ( material.shading === THREE.FlatShading ) { - geometry.__sortArray = []; + var nx, ny, nz, + nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz, + normalArray, + i, il = object.count * 3; - geometry.__webglParticleCount = nvertices; + for ( i = 0; i < il; i += 9 ) { - initCustomAttributes ( geometry, object ); + normalArray = object.normalArray; - }; + nax = normalArray[ i ]; + nay = normalArray[ i + 1 ]; + naz = normalArray[ i + 2 ]; - function initLineBuffers ( geometry, object ) { + nbx = normalArray[ i + 3 ]; + nby = normalArray[ i + 4 ]; + nbz = normalArray[ i + 5 ]; - var nvertices = geometry.vertices.length; + ncx = normalArray[ i + 6 ]; + ncy = normalArray[ i + 7 ]; + ncz = normalArray[ i + 8 ]; - geometry.__vertexArray = new Float32Array( nvertices * 3 ); - geometry.__colorArray = new Float32Array( nvertices * 3 ); - geometry.__lineDistanceArray = new Float32Array( nvertices * 1 ); + nx = ( nax + nbx + ncx ) / 3; + ny = ( nay + nby + ncy ) / 3; + nz = ( naz + nbz + ncz ) / 3; - geometry.__webglLineCount = nvertices; + normalArray[ i ] = nx; + normalArray[ i + 1 ] = ny; + normalArray[ i + 2 ] = nz; - initCustomAttributes ( geometry, object ); + normalArray[ i + 3 ] = nx; + normalArray[ i + 4 ] = ny; + normalArray[ i + 5 ] = nz; - }; + normalArray[ i + 6 ] = nx; + normalArray[ i + 7 ] = ny; + normalArray[ i + 8 ] = nz; - function initMeshBuffers ( geometryGroup, object ) { + } - var geometry = object.geometry, - faces3 = geometryGroup.faces3, + } - nvertices = faces3.length * 3, - ntris = faces3.length * 1, - nlines = faces3.length * 3, + _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); + enableAttribute( program.attributes.normal ); + _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); - material = getBufferMaterial( object, geometryGroup ), + } - uvType = bufferGuessUVType( material ), - normalType = bufferGuessNormalType( material ), - vertexColorType = bufferGuessVertexColorType( material ); + if ( object.hasUvs && material.map ) { - // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); + enableAttribute( program.attributes.uv ); + _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); - geometryGroup.__vertexArray = new Float32Array( nvertices * 3 ); + } - if ( normalType ) { + if ( object.hasColors && material.vertexColors !== THREE.NoColors ) { - geometryGroup.__normalArray = new Float32Array( nvertices * 3 ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); + enableAttribute( program.attributes.color ); + _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 ); } - if ( geometry.hasTangents ) { - - geometryGroup.__tangentArray = new Float32Array( nvertices * 4 ); + disableUnusedAttributes(); - } + _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); - if ( vertexColorType ) { + object.count = 0; - geometryGroup.__colorArray = new Float32Array( nvertices * 3 ); + }; - } + function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) { - if ( uvType ) { + for ( var attributeName in programAttributes ) { - if ( geometry.faceVertexUvs.length > 0 ) { + var attributePointer = programAttributes[ attributeName ]; + var attributeItem = geometryAttributes[ attributeName ]; - geometryGroup.__uvArray = new Float32Array( nvertices * 2 ); + if ( attributePointer >= 0 ) { - } + if ( attributeItem ) { - if ( geometry.faceVertexUvs.length > 1 ) { + var attributeSize = attributeItem.itemSize; - geometryGroup.__uv2Array = new Float32Array( nvertices * 2 ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); + enableAttribute( attributePointer ); + _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32 - } + } else if ( material.defaultAttributeValues ) { - } + if ( material.defaultAttributeValues[ attributeName ].length === 2 ) { - if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) { + _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); - geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 ); - geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 ); + } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) { - } + _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); - var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3 + } - geometryGroup.__typeArray = UintArray; - geometryGroup.__faceArray = new UintArray( ntris * 3 ); - geometryGroup.__lineArray = new UintArray( nlines * 2 ); + } - var m, ml; + } - if ( geometryGroup.numMorphTargets ) { + } - geometryGroup.__morphTargetsArrays = []; + disableUnusedAttributes(); - for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { + } - geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) ); + this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) { - } + if ( material.visible === false ) return; - } + var linewidth, a, attribute; + var attributeItem, attributeName, attributePointer, attributeSize; - if ( geometryGroup.numMorphNormals ) { + var program = setProgram( camera, lights, fog, material, object ); - geometryGroup.__morphNormalsArrays = []; + var programAttributes = program.attributes; + var geometryAttributes = geometry.attributes; - for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { + var updateBuffers = false, + wireframeBit = material.wireframe ? 1 : 0, + geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; - geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) ); + if ( geometryHash !== _currentGeometryGroupHash ) { - } + _currentGeometryGroupHash = geometryHash; + updateBuffers = true; } - geometryGroup.__webglFaceCount = ntris * 3; - geometryGroup.__webglLineCount = nlines * 2; + if ( updateBuffers ) { + initAttributes(); - // custom attributes + } - if ( material.attributes ) { + // render mesh - if ( geometryGroup.__webglCustomAttributesList === undefined ) { + if ( object instanceof THREE.Mesh ) { - geometryGroup.__webglCustomAttributesList = []; + var index = geometryAttributes[ 'index' ]; - } + if ( index ) { - for ( var a in material.attributes ) { + // indexed triangles - // Do a shallow copy of the attribute object so different geometryGroup chunks use different - // attribute buffers which are correctly indexed in the setMeshBuffers function + var type, size; - var originalAttribute = material.attributes[ a ]; + if ( index.array instanceof Uint32Array ) { - var attribute = {}; + type = _gl.UNSIGNED_INT; + size = 4; - for ( var property in originalAttribute ) { + } else { - attribute[ property ] = originalAttribute[ property ]; + type = _gl.UNSIGNED_SHORT; + size = 2; } - if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) { + var offsets = geometry.offsets; - attribute.__webglInitialized = true; + if ( offsets.length === 0 ) { - var size = 1; // "f" and "i" + if ( updateBuffers ) { - if( attribute.type === "v2" ) size = 2; - else if( attribute.type === "v3" ) size = 3; - else if( attribute.type === "v4" ) size = 4; - else if( attribute.type === "c" ) size = 3; + setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - attribute.size = size; + } - attribute.array = new Float32Array( nvertices * size ); + _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 ); - attribute.buffer = _gl.createBuffer(); - attribute.buffer.belongsToAttribute = a; + _this.info.render.calls ++; + _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared + _this.info.render.faces += index.array.length / 3; - originalAttribute.needsUpdate = true; - attribute.__original = originalAttribute; + } else { - } + // if there is more than 1 chunk + // must set attribute pointers to use new offsets for each chunk + // even if geometry and materials didn't change - geometryGroup.__webglCustomAttributesList.push( attribute ); + updateBuffers = true; - } + for ( var i = 0, il = offsets.length; i < il; i ++ ) { - } + var startIndex = offsets[ i ].index; - geometryGroup.__inittedArrays = true; + if ( updateBuffers ) { - }; + setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - function getBufferMaterial( object, geometryGroup ) { + } - return object.material instanceof THREE.MeshFaceMaterial - ? object.material.materials[ geometryGroup.materialIndex ] - : object.material; + // render indexed triangles - }; + _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size ); - function materialNeedsSmoothNormals ( material ) { + _this.info.render.calls ++; + _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared + _this.info.render.faces += offsets[ i ].count / 3; - return material && material.shading !== undefined && material.shading === THREE.SmoothShading; + } - }; + } - function bufferGuessNormalType ( material ) { + } else { - // only MeshBasicMaterial and MeshDepthMaterial don't need normals + // non-indexed triangles - if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) { + if ( updateBuffers ) { - return false; + setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); - } + } - if ( materialNeedsSmoothNormals( material ) ) { + var position = geometry.attributes[ 'position' ]; - return THREE.SmoothShading; + // render non-indexed triangles - } else { + _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 ); - return THREE.FlatShading; + _this.info.render.calls ++; + _this.info.render.vertices += position.array.length / 3; + _this.info.render.faces += position.array.length / 9; - } + } - }; + } else if ( object instanceof THREE.PointCloud ) { - function bufferGuessVertexColorType( material ) { + // render particles - if ( material.vertexColors ) { + if ( updateBuffers ) { - return material.vertexColors; + setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); - } + } - return false; + var position = geometryAttributes[ 'position' ]; - }; + // render particles - function bufferGuessUVType( material ) { + _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 ); - // material must use some texture to require uvs + _this.info.render.calls ++; + _this.info.render.points += position.array.length / 3; - if ( material.map || - material.lightMap || - material.bumpMap || - material.normalMap || - material.specularMap || - material instanceof THREE.ShaderMaterial ) { + } else if ( object instanceof THREE.Line ) { - return true; + var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; - } + setLineWidth( material.linewidth ); - return false; + var index = geometryAttributes[ 'index' ]; - }; + if ( index ) { - // + // indexed lines - function initDirectBuffers( geometry ) { + var type, size; - for ( var name in geometry.attributes ) { + if ( index.array instanceof Uint32Array ) { - var bufferType = ( name === "index" ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER; + type = _gl.UNSIGNED_INT; + size = 4; - var attribute = geometry.attributes[ name ]; - attribute.buffer = _gl.createBuffer(); + } else { - _gl.bindBuffer( bufferType, attribute.buffer ); - _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW ); + type = _gl.UNSIGNED_SHORT; + size = 2; - } + } - } + var offsets = geometry.offsets; - // Buffer setting + if ( offsets.length === 0 ) { - function setParticleBuffers ( geometry, hint, object ) { + if ( updateBuffers ) { - var v, c, vertex, offset, index, color, + setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - vertices = geometry.vertices, - vl = vertices.length, + } - colors = geometry.colors, - cl = colors.length, + _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array - vertexArray = geometry.__vertexArray, - colorArray = geometry.__colorArray, + _this.info.render.calls ++; + _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared - sortArray = geometry.__sortArray, + } else { - dirtyVertices = geometry.verticesNeedUpdate, - dirtyElements = geometry.elementsNeedUpdate, - dirtyColors = geometry.colorsNeedUpdate, + // if there is more than 1 chunk + // must set attribute pointers to use new offsets for each chunk + // even if geometry and materials didn't change - customAttributes = geometry.__webglCustomAttributesList, - i, il, - a, ca, cal, value, - customAttribute; + if ( offsets.length > 1 ) updateBuffers = true; - if ( object.sortParticles ) { + for ( var i = 0, il = offsets.length; i < il; i ++ ) { - _projScreenMatrixPS.copy( _projScreenMatrix ); - _projScreenMatrixPS.multiply( object.matrixWorld ); + var startIndex = offsets[ i ].index; - for ( v = 0; v < vl; v ++ ) { + if ( updateBuffers ) { - vertex = vertices[ v ]; + setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - _vector3.copy( vertex ); - _vector3.applyProjection( _projScreenMatrixPS ); + } - sortArray[ v ] = [ _vector3.z, v ]; + // render indexed lines - } + _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array - sortArray.sort( numericalSort ); + _this.info.render.calls ++; + _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared - for ( v = 0; v < vl; v ++ ) { + } - vertex = vertices[ sortArray[v][1] ]; + } - offset = v * 3; + } else { - vertexArray[ offset ] = vertex.x; - vertexArray[ offset + 1 ] = vertex.y; - vertexArray[ offset + 2 ] = vertex.z; + // non-indexed lines - } + if ( updateBuffers ) { - for ( c = 0; c < cl; c ++ ) { + setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); - offset = c * 3; + } - color = colors[ sortArray[c][1] ]; + var position = geometryAttributes[ 'position' ]; - colorArray[ offset ] = color.r; - colorArray[ offset + 1 ] = color.g; - colorArray[ offset + 2 ] = color.b; + _gl.drawArrays( mode, 0, position.array.length / 3 ); + + _this.info.render.calls ++; + _this.info.render.points += position.array.length / 3; } - if ( customAttributes ) { + } - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { + }; - customAttribute = customAttributes[ i ]; + this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) { - if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue; + if ( material.visible === false ) return; - offset = 0; + var linewidth, a, attribute, i, il; - cal = customAttribute.value.length; + var program = setProgram( camera, lights, fog, material, object ); - if ( customAttribute.size === 1 ) { + var attributes = program.attributes; - for ( ca = 0; ca < cal; ca ++ ) { + var updateBuffers = false, + wireframeBit = material.wireframe ? 1 : 0, + geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; - index = sortArray[ ca ][ 1 ]; + if ( geometryGroupHash !== _currentGeometryGroupHash ) { - customAttribute.array[ ca ] = customAttribute.value[ index ]; + _currentGeometryGroupHash = geometryGroupHash; + updateBuffers = true; - } + } - } else if ( customAttribute.size === 2 ) { + if ( updateBuffers ) { - for ( ca = 0; ca < cal; ca ++ ) { + initAttributes(); - index = sortArray[ ca ][ 1 ]; + } - value = customAttribute.value[ index ]; + // vertices - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; + if ( ! material.morphTargets && attributes.position >= 0 ) { - offset += 2; + if ( updateBuffers ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); + enableAttribute( attributes.position ); + _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - } else if ( customAttribute.size === 3 ) { + } - if ( customAttribute.type === "c" ) { + } else { - for ( ca = 0; ca < cal; ca ++ ) { + if ( object.morphTargetBase ) { - index = sortArray[ ca ][ 1 ]; + setupMorphTargets( material, geometryGroup, object ); - value = customAttribute.value[ index ]; + } - customAttribute.array[ offset ] = value.r; - customAttribute.array[ offset + 1 ] = value.g; - customAttribute.array[ offset + 2 ] = value.b; + } - offset += 3; - } + if ( updateBuffers ) { - } else { + // custom attributes - for ( ca = 0; ca < cal; ca ++ ) { + // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers - index = sortArray[ ca ][ 1 ]; + if ( geometryGroup.__webglCustomAttributesList ) { - value = customAttribute.value[ index ]; + for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) { - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; + attribute = geometryGroup.__webglCustomAttributesList[ i ]; - offset += 3; + if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer ); + enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] ); + _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 ); - } + } - } else if ( customAttribute.size === 4 ) { + } - for ( ca = 0; ca < cal; ca ++ ) { + } - index = sortArray[ ca ][ 1 ]; - value = customAttribute.value[ index ]; + // colors - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; - customAttribute.array[ offset + 3 ] = value.w; + if ( attributes.color >= 0 ) { - offset += 4; + if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); + enableAttribute( attributes.color ); + _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); + + } else if ( material.defaultAttributeValues ) { - } + + _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color ); } } - } else { + // normals - if ( dirtyVertices ) { + if ( attributes.normal >= 0 ) { - for ( v = 0; v < vl; v ++ ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); + enableAttribute( attributes.normal ); + _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); - vertex = vertices[ v ]; + } - offset = v * 3; + // tangents - vertexArray[ offset ] = vertex.x; - vertexArray[ offset + 1 ] = vertex.y; - vertexArray[ offset + 2 ] = vertex.z; + if ( attributes.tangent >= 0 ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); + enableAttribute( attributes.tangent ); + _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 ); } - if ( dirtyColors ) { + // uvs - for ( c = 0; c < cl; c ++ ) { + if ( attributes.uv >= 0 ) { - color = colors[ c ]; + if ( object.geometry.faceVertexUvs[ 0 ] ) { - offset = c * 3; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); + enableAttribute( attributes.uv ); + _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); + + } else if ( material.defaultAttributeValues ) { - colorArray[ offset ] = color.r; - colorArray[ offset + 1 ] = color.g; - colorArray[ offset + 2 ] = color.b; + + _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv ); } } - if ( customAttributes ) { - - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { + if ( attributes.uv2 >= 0 ) { - customAttribute = customAttributes[ i ]; + if ( object.geometry.faceVertexUvs[ 1 ] ) { - if ( customAttribute.needsUpdate && - ( customAttribute.boundTo === undefined || - customAttribute.boundTo === "vertices") ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); + enableAttribute( attributes.uv2 ); + _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 ); - cal = customAttribute.value.length; + } else if ( material.defaultAttributeValues ) { - offset = 0; - if ( customAttribute.size === 1 ) { + _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 ); - for ( ca = 0; ca < cal; ca ++ ) { + } - customAttribute.array[ ca ] = customAttribute.value[ ca ]; + } - } + if ( material.skinning && + attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) { - } else if ( customAttribute.size === 2 ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); + enableAttribute( attributes.skinIndex ); + _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 ); - for ( ca = 0; ca < cal; ca ++ ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); + enableAttribute( attributes.skinWeight ); + _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 ); - value = customAttribute.value[ ca ]; + } - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; + // line distances - offset += 2; + if ( attributes.lineDistance >= 0 ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer ); + enableAttribute( attributes.lineDistance ); + _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 ); - } else if ( customAttribute.size === 3 ) { + } - if ( customAttribute.type === "c" ) { + } - for ( ca = 0; ca < cal; ca ++ ) { + disableUnusedAttributes(); - value = customAttribute.value[ ca ]; + // render mesh - customAttribute.array[ offset ] = value.r; - customAttribute.array[ offset + 1 ] = value.g; - customAttribute.array[ offset + 2 ] = value.b; + if ( object instanceof THREE.Mesh ) { - offset += 3; + var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT; - } + // wireframe - } else { + if ( material.wireframe ) { - for ( ca = 0; ca < cal; ca ++ ) { + setLineWidth( material.wireframeLinewidth ); + if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); + _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 ); - value = customAttribute.value[ ca ]; + // triangles - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; + } else { - offset += 3; + if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); + _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 ); - } + } - } + _this.info.render.calls ++; + _this.info.render.vertices += geometryGroup.__webglFaceCount; + _this.info.render.faces += geometryGroup.__webglFaceCount / 3; - } else if ( customAttribute.size === 4 ) { + // render lines - for ( ca = 0; ca < cal; ca ++ ) { + } else if ( object instanceof THREE.Line ) { - value = customAttribute.value[ ca ]; + var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; - customAttribute.array[ offset + 3 ] = value.w; + setLineWidth( material.linewidth ); - offset += 4; + _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount ); - } + _this.info.render.calls ++; - } + // render particles - } + } else if ( object instanceof THREE.PointCloud ) { - } + _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount ); - } + _this.info.render.calls ++; + _this.info.render.points += geometryGroup.__webglParticleCount; } - if ( dirtyVertices || object.sortParticles ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); + }; - } + function initAttributes() { - if ( dirtyColors || object.sortParticles ) { + for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); + _newAttributes[ i ] = 0; } - if ( customAttributes ) { - - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - - customAttribute = customAttributes[ i ]; + } - if ( customAttribute.needsUpdate || object.sortParticles ) { + function enableAttribute( attribute ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); + _newAttributes[ attribute ] = 1; - } + if ( _enabledAttributes[ attribute ] === 0 ) { - } + _gl.enableVertexAttribArray( attribute ); + _enabledAttributes[ attribute ] = 1; } } - function setLineBuffers ( geometry, hint ) { - - var v, c, d, vertex, offset, color, + function disableUnusedAttributes() { - vertices = geometry.vertices, - colors = geometry.colors, - lineDistances = geometry.lineDistances, + for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) { - vl = vertices.length, - cl = colors.length, - dl = lineDistances.length, + if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) { - vertexArray = geometry.__vertexArray, - colorArray = geometry.__colorArray, - lineDistanceArray = geometry.__lineDistanceArray, + _gl.disableVertexAttribArray( i ); + _enabledAttributes[ i ] = 0; - dirtyVertices = geometry.verticesNeedUpdate, - dirtyColors = geometry.colorsNeedUpdate, - dirtyLineDistances = geometry.lineDistancesNeedUpdate, + } - customAttributes = geometry.__webglCustomAttributesList, + } - i, il, - a, ca, cal, value, - customAttribute; + } - if ( dirtyVertices ) { + function setupMorphTargets ( material, geometryGroup, object ) { - for ( v = 0; v < vl; v ++ ) { + // set base - vertex = vertices[ v ]; + var attributes = material.program.attributes; - offset = v * 3; + if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) { - vertexArray[ offset ] = vertex.x; - vertexArray[ offset + 1 ] = vertex.y; - vertexArray[ offset + 2 ] = vertex.z; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] ); + enableAttribute( attributes.position ); + _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - } + } else if ( attributes.position >= 0 ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); + enableAttribute( attributes.position ); + _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } - if ( dirtyColors ) { + if ( object.morphTargetForcedOrder.length ) { - for ( c = 0; c < cl; c ++ ) { + // set forced order - color = colors[ c ]; + var m = 0; + var order = object.morphTargetForcedOrder; + var influences = object.morphTargetInfluences; - offset = c * 3; + while ( m < material.numSupportedMorphTargets && m < order.length ) { - colorArray[ offset ] = color.r; - colorArray[ offset + 1 ] = color.g; - colorArray[ offset + 2 ] = color.b; + if ( attributes[ 'morphTarget' + m ] >= 0 ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] ); + enableAttribute( attributes[ 'morphTarget' + m ] ); + _gl.vertexAttribPointer( attributes[ 'morphTarget' + m ], 3, _gl.FLOAT, false, 0, 0 ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); + } - } + if ( attributes[ 'morphNormal' + m ] >= 0 && material.morphNormals ) { - if ( dirtyLineDistances ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] ); + enableAttribute( attributes[ 'morphNormal' + m ] ); + _gl.vertexAttribPointer( attributes[ 'morphNormal' + m ], 3, _gl.FLOAT, false, 0, 0 ); - for ( d = 0; d < dl; d ++ ) { + } - lineDistanceArray[ d ] = lineDistances[ d ]; + object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ]; + m ++; } - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint ); + } else { - } + // find the most influencing - if ( customAttributes ) { + var influence, activeInfluenceIndices = []; + var influences = object.morphTargetInfluences; + var i, il = influences.length; - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { + for ( i = 0; i < il; i ++ ) { - customAttribute = customAttributes[ i ]; + influence = influences[ i ]; - if ( customAttribute.needsUpdate && - ( customAttribute.boundTo === undefined || - customAttribute.boundTo === "vertices" ) ) { + if ( influence > 0 ) { - offset = 0; + activeInfluenceIndices.push( [ influence, i ] ); - cal = customAttribute.value.length; + } - if ( customAttribute.size === 1 ) { + } - for ( ca = 0; ca < cal; ca ++ ) { + if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) { - customAttribute.array[ ca ] = customAttribute.value[ ca ]; + activeInfluenceIndices.sort( numericalSort ); + activeInfluenceIndices.length = material.numSupportedMorphTargets; - } + } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) { - } else if ( customAttribute.size === 2 ) { + activeInfluenceIndices.sort( numericalSort ); - for ( ca = 0; ca < cal; ca ++ ) { + } else if ( activeInfluenceIndices.length === 0 ) { - value = customAttribute.value[ ca ]; + activeInfluenceIndices.push( [ 0, 0 ] ); - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; + }; - offset += 2; + var influenceIndex, m = 0; - } + while ( m < material.numSupportedMorphTargets ) { - } else if ( customAttribute.size === 3 ) { + if ( activeInfluenceIndices[ m ] ) { - if ( customAttribute.type === "c" ) { + influenceIndex = activeInfluenceIndices[ m ][ 1 ]; - for ( ca = 0; ca < cal; ca ++ ) { - - value = customAttribute.value[ ca ]; - - customAttribute.array[ offset ] = value.r; - customAttribute.array[ offset + 1 ] = value.g; - customAttribute.array[ offset + 2 ] = value.b; - - offset += 3; - - } - - } else { - - for ( ca = 0; ca < cal; ca ++ ) { + if ( attributes[ 'morphTarget' + m ] >= 0 ) { - value = customAttribute.value[ ca ]; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] ); + enableAttribute( attributes[ 'morphTarget' + m ] ); + _gl.vertexAttribPointer( attributes[ 'morphTarget' + m ], 3, _gl.FLOAT, false, 0, 0 ); - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; + } - offset += 3; + if ( attributes[ 'morphNormal' + m ] >= 0 && material.morphNormals ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] ); + enableAttribute( attributes[ 'morphNormal' + m ] ); + _gl.vertexAttribPointer( attributes[ 'morphNormal' + m ], 3, _gl.FLOAT, false, 0, 0 ); - } - } else if ( customAttribute.size === 4 ) { + } - for ( ca = 0; ca < cal; ca ++ ) { + object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ]; - value = customAttribute.value[ ca ]; + } else { - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; - customAttribute.array[ offset + 3 ] = value.w; + /* + _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); - offset += 4; + if ( material.morphNormals ) { - } + _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); } + */ - _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); + object.__webglMorphTargetInfluences[ m ] = 0; } + m ++; + } } - } - - function setMeshBuffers( geometryGroup, object, hint, dispose, material ) { + // load updated influences uniform - if ( ! geometryGroup.__inittedArrays ) { + if ( material.program.uniforms.morphTargetInfluences !== null ) { - return; + _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences ); } - var normalType = bufferGuessNormalType( material ), - vertexColorType = bufferGuessVertexColorType( material ), - uvType = bufferGuessUVType( material ), + }; - needsSmoothNormals = ( normalType === THREE.SmoothShading ); + // Sorting - var f, fl, fi, face, - vertexNormals, faceNormal, normal, - vertexColors, faceColor, - vertexTangents, - uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4, - c1, c2, c3, c4, - sw1, sw2, sw3, sw4, - si1, si2, si3, si4, - sa1, sa2, sa3, sa4, - sb1, sb2, sb3, sb4, - m, ml, i, il, - vn, uvi, uv2i, - vk, vkl, vka, - nka, chf, faceVertexNormals, - a, + function painterSortStable ( a, b ) { - vertexIndex = 0, + if ( a.z !== b.z ) { - offset = 0, - offset_uv = 0, - offset_uv2 = 0, - offset_face = 0, - offset_normal = 0, - offset_tangent = 0, - offset_line = 0, - offset_color = 0, - offset_skin = 0, - offset_morphTarget = 0, - offset_custom = 0, - offset_customSrc = 0, + return b.z - a.z; - value, + } else { - vertexArray = geometryGroup.__vertexArray, - uvArray = geometryGroup.__uvArray, - uv2Array = geometryGroup.__uv2Array, - normalArray = geometryGroup.__normalArray, - tangentArray = geometryGroup.__tangentArray, - colorArray = geometryGroup.__colorArray, + return a.id - b.id; - skinIndexArray = geometryGroup.__skinIndexArray, - skinWeightArray = geometryGroup.__skinWeightArray, + } - morphTargetsArrays = geometryGroup.__morphTargetsArrays, - morphNormalsArrays = geometryGroup.__morphNormalsArrays, + }; - customAttributes = geometryGroup.__webglCustomAttributesList, - customAttribute, + function reversePainterSortStable ( a, b ) { - faceArray = geometryGroup.__faceArray, - lineArray = geometryGroup.__lineArray, + if ( a.z !== b.z ) { - geometry = object.geometry, // this is shared for all chunks + return a.z - b.z; - dirtyVertices = geometry.verticesNeedUpdate, - dirtyElements = geometry.elementsNeedUpdate, - dirtyUvs = geometry.uvsNeedUpdate, - dirtyNormals = geometry.normalsNeedUpdate, - dirtyTangents = geometry.tangentsNeedUpdate, - dirtyColors = geometry.colorsNeedUpdate, - dirtyMorphTargets = geometry.morphTargetsNeedUpdate, + } else { - vertices = geometry.vertices, - chunk_faces3 = geometryGroup.faces3, - obj_faces = geometry.faces, + return a.id - b.id; - obj_uvs = geometry.faceVertexUvs[ 0 ], - obj_uvs2 = geometry.faceVertexUvs[ 1 ], + } - obj_colors = geometry.colors, + }; - obj_skinIndices = geometry.skinIndices, - obj_skinWeights = geometry.skinWeights, + function numericalSort ( a, b ) { - morphTargets = geometry.morphTargets, - morphNormals = geometry.morphNormals; + return b[ 0 ] - a[ 0 ]; - if ( dirtyVertices ) { + }; - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - face = obj_faces[ chunk_faces3[ f ] ]; + // Rendering - v1 = vertices[ face.a ]; - v2 = vertices[ face.b ]; - v3 = vertices[ face.c ]; + this.render = function ( scene, camera, renderTarget, forceClear ) { - vertexArray[ offset ] = v1.x; - vertexArray[ offset + 1 ] = v1.y; - vertexArray[ offset + 2 ] = v1.z; + if ( camera instanceof THREE.Camera === false ) { - vertexArray[ offset + 3 ] = v2.x; - vertexArray[ offset + 4 ] = v2.y; - vertexArray[ offset + 5 ] = v2.z; + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; - vertexArray[ offset + 6 ] = v3.x; - vertexArray[ offset + 7 ] = v3.y; - vertexArray[ offset + 8 ] = v3.z; + } - offset += 9; + var i, il, - } + webglObject, object, + renderList, - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); + lights = scene.__lights, + fog = scene.fog; - } + // reset caching for this frame - if ( dirtyMorphTargets ) { + _currentMaterialId = - 1; + _currentCamera = null; + _lightsNeedUpdate = true; - for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) { + // update scene graph - offset_morphTarget = 0; + if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + // update camera matrices and frustum - chf = chunk_faces3[ f ]; - face = obj_faces[ chf ]; + if ( camera.parent === undefined ) camera.updateMatrixWorld(); - // morph positions + // update Skeleton objects + function updateSkeletons( object ) { - v1 = morphTargets[ vk ].vertices[ face.a ]; - v2 = morphTargets[ vk ].vertices[ face.b ]; - v3 = morphTargets[ vk ].vertices[ face.c ]; + if ( object instanceof THREE.SkinnedMesh ) { - vka = morphTargetsArrays[ vk ]; + object.skeleton.update(); - vka[ offset_morphTarget ] = v1.x; - vka[ offset_morphTarget + 1 ] = v1.y; - vka[ offset_morphTarget + 2 ] = v1.z; + } - vka[ offset_morphTarget + 3 ] = v2.x; - vka[ offset_morphTarget + 4 ] = v2.y; - vka[ offset_morphTarget + 5 ] = v2.z; + for ( var i = 0, l = object.children.length; i < l; i ++ ) { - vka[ offset_morphTarget + 6 ] = v3.x; - vka[ offset_morphTarget + 7 ] = v3.y; - vka[ offset_morphTarget + 8 ] = v3.z; + updateSkeletons( object.children[ i ] ); - // morph normals + } - if ( material.morphNormals ) { + } - if ( needsSmoothNormals ) { + updateSkeletons( scene ); - faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ]; + camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - n1 = faceVertexNormals.a; - n2 = faceVertexNormals.b; - n3 = faceVertexNormals.c; + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - } else { + initObjects( scene ); - n1 = morphNormals[ vk ].faceNormals[ chf ]; - n2 = n1; - n3 = n1; + opaqueObjects.length = 0; + transparentObjects.length = 0; + + projectObject( scene, scene, camera ); - } + if ( _this.sortObjects === true ) { - nka = morphNormalsArrays[ vk ]; + opaqueObjects.sort( painterSortStable ); + transparentObjects.sort( reversePainterSortStable ); - nka[ offset_morphTarget ] = n1.x; - nka[ offset_morphTarget + 1 ] = n1.y; - nka[ offset_morphTarget + 2 ] = n1.z; + } - nka[ offset_morphTarget + 3 ] = n2.x; - nka[ offset_morphTarget + 4 ] = n2.y; - nka[ offset_morphTarget + 5 ] = n2.z; + // custom render plugins (pre pass) + + renderPlugins( this.renderPluginsPre, scene, camera ); - nka[ offset_morphTarget + 6 ] = n3.x; - nka[ offset_morphTarget + 7 ] = n3.y; - nka[ offset_morphTarget + 8 ] = n3.z; + // - } + _this.info.render.calls = 0; + _this.info.render.vertices = 0; + _this.info.render.faces = 0; + _this.info.render.points = 0; - // + this.setRenderTarget( renderTarget ); - offset_morphTarget += 9; + if ( this.autoClear || forceClear ) { - } + this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] ); - _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint ); + } - if ( material.morphNormals ) { + // set matrices for regular objects (frustum culled) - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] ); - _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint ); + - } - } + // set matrices for immediate objects - } + renderList = scene.__webglObjectsImmediate; - if ( obj_skinWeights.length ) { + for ( i = 0, il = renderList.length; i < il; i ++ ) { - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + webglObject = renderList[ i ]; + object = webglObject.object; - face = obj_faces[ chunk_faces3[ f ] ]; - - // weights + if ( object.visible ) { - sw1 = obj_skinWeights[ face.a ]; - sw2 = obj_skinWeights[ face.b ]; - sw3 = obj_skinWeights[ face.c ]; + setupMatrices( object, camera ); - skinWeightArray[ offset_skin ] = sw1.x; - skinWeightArray[ offset_skin + 1 ] = sw1.y; - skinWeightArray[ offset_skin + 2 ] = sw1.z; - skinWeightArray[ offset_skin + 3 ] = sw1.w; + unrollImmediateBufferMaterial( webglObject ); - skinWeightArray[ offset_skin + 4 ] = sw2.x; - skinWeightArray[ offset_skin + 5 ] = sw2.y; - skinWeightArray[ offset_skin + 6 ] = sw2.z; - skinWeightArray[ offset_skin + 7 ] = sw2.w; + } - skinWeightArray[ offset_skin + 8 ] = sw3.x; - skinWeightArray[ offset_skin + 9 ] = sw3.y; - skinWeightArray[ offset_skin + 10 ] = sw3.z; - skinWeightArray[ offset_skin + 11 ] = sw3.w; + } - // indices + if ( scene.overrideMaterial ) { - si1 = obj_skinIndices[ face.a ]; - si2 = obj_skinIndices[ face.b ]; - si3 = obj_skinIndices[ face.c ]; + var material = scene.overrideMaterial; - skinIndexArray[ offset_skin ] = si1.x; - skinIndexArray[ offset_skin + 1 ] = si1.y; - skinIndexArray[ offset_skin + 2 ] = si1.z; - skinIndexArray[ offset_skin + 3 ] = si1.w; + this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); + this.setDepthTest( material.depthTest ); + this.setDepthWrite( material.depthWrite ); + setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); - skinIndexArray[ offset_skin + 4 ] = si2.x; - skinIndexArray[ offset_skin + 5 ] = si2.y; - skinIndexArray[ offset_skin + 6 ] = si2.z; - skinIndexArray[ offset_skin + 7 ] = si2.w; + renderObjects( opaqueObjects, camera, lights, fog, true, material ); + renderObjects( transparentObjects, camera, lights, fog, true, material ); + renderObjectsImmediate( scene.__webglObjectsImmediate, '', camera, lights, fog, false, material ); - skinIndexArray[ offset_skin + 8 ] = si3.x; - skinIndexArray[ offset_skin + 9 ] = si3.y; - skinIndexArray[ offset_skin + 10 ] = si3.z; - skinIndexArray[ offset_skin + 11 ] = si3.w; + } else { - offset_skin += 12; + var material = null; - } + // opaque pass (front-to-back order) - if ( offset_skin > 0 ) { + this.setBlending( THREE.NoBlending ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint ); + renderObjects( opaqueObjects, camera, lights, fog, false, material ); + renderObjectsImmediate( scene.__webglObjectsImmediate, 'opaque', camera, lights, fog, false, material ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint ); + // transparent pass (back-to-front order) - } + renderObjects( transparentObjects, camera, lights, fog, true, material ); + renderObjectsImmediate( scene.__webglObjectsImmediate, 'transparent', camera, lights, fog, true, material ); } - if ( dirtyColors && vertexColorType ) { + // custom render plugins (post pass) - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + renderPlugins( this.renderPluginsPost, scene, camera ); - face = obj_faces[ chunk_faces3[ f ] ]; - vertexColors = face.vertexColors; - faceColor = face.color; + // Generate mipmap if we're using any kind of mipmap filtering - if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) { + if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) { - c1 = vertexColors[ 0 ]; - c2 = vertexColors[ 1 ]; - c3 = vertexColors[ 2 ]; + updateRenderTargetMipmap( renderTarget ); - } else { + } - c1 = faceColor; - c2 = faceColor; - c3 = faceColor; + // Ensure depth buffer writing is enabled so it can be cleared on next render - } + this.setDepthTest( true ); + this.setDepthWrite( true ); - colorArray[ offset_color ] = c1.r; - colorArray[ offset_color + 1 ] = c1.g; - colorArray[ offset_color + 2 ] = c1.b; + // _gl.finish(); - colorArray[ offset_color + 3 ] = c2.r; - colorArray[ offset_color + 4 ] = c2.g; - colorArray[ offset_color + 5 ] = c2.b; + }; + + function projectObject(scene, object,camera){ + + if ( object.visible === false ) return; + + var webglObjects = scene.__webglObjects[ object.id ]; + + if ( webglObjects && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { + + updateObject( scene, object ); + + for ( var i = 0, l = webglObjects.length; i < l; i ++ ) { + + var webglObject = webglObjects[i]; + + unrollBufferMaterial( webglObject ); - colorArray[ offset_color + 6 ] = c3.r; - colorArray[ offset_color + 7 ] = c3.g; - colorArray[ offset_color + 8 ] = c3.b; + webglObject.render = true; - offset_color += 9; + if ( _this.sortObjects === true ) { - } + if ( object.renderDepth !== null ) { - if ( offset_color > 0 ) { + webglObject.z = object.renderDepth; - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); + } else { + + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyProjection( _projScreenMatrix ); + + webglObject.z = _vector3.z; + + } + + } } } + + for ( var i = 0, l = object.children.length; i < l; i ++ ) { - if ( dirtyTangents && geometry.hasTangents ) { + projectObject( scene, object.children[ i ], camera ); - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + } + + } - face = obj_faces[ chunk_faces3[ f ] ]; + function renderPlugins( plugins, scene, camera ) { - vertexTangents = face.vertexTangents; + if ( plugins.length === 0 ) return; - t1 = vertexTangents[ 0 ]; - t2 = vertexTangents[ 1 ]; - t3 = vertexTangents[ 2 ]; + for ( var i = 0, il = plugins.length; i < il; i ++ ) { - tangentArray[ offset_tangent ] = t1.x; - tangentArray[ offset_tangent + 1 ] = t1.y; - tangentArray[ offset_tangent + 2 ] = t1.z; - tangentArray[ offset_tangent + 3 ] = t1.w; + // reset state for plugin (to start from clean slate) - tangentArray[ offset_tangent + 4 ] = t2.x; - tangentArray[ offset_tangent + 5 ] = t2.y; - tangentArray[ offset_tangent + 6 ] = t2.z; - tangentArray[ offset_tangent + 7 ] = t2.w; + _currentProgram = null; + _currentCamera = null; - tangentArray[ offset_tangent + 8 ] = t3.x; - tangentArray[ offset_tangent + 9 ] = t3.y; - tangentArray[ offset_tangent + 10 ] = t3.z; - tangentArray[ offset_tangent + 11 ] = t3.w; + _oldBlending = - 1; + _oldDepthTest = - 1; + _oldDepthWrite = - 1; + _oldDoubleSided = - 1; + _oldFlipSided = - 1; + _currentGeometryGroupHash = - 1; + _currentMaterialId = - 1; - offset_tangent += 12; + _lightsNeedUpdate = true; - } + plugins[ i ].render( scene, camera, _currentWidth, _currentHeight ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint ); + // reset state after plugin (anything could have changed) - } + _currentProgram = null; + _currentCamera = null; - if ( dirtyNormals && normalType ) { + _oldBlending = - 1; + _oldDepthTest = - 1; + _oldDepthWrite = - 1; + _oldDoubleSided = - 1; + _oldFlipSided = - 1; + _currentGeometryGroupHash = - 1; + _currentMaterialId = - 1; - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + _lightsNeedUpdate = true; - face = obj_faces[ chunk_faces3[ f ] ]; + } - vertexNormals = face.vertexNormals; - faceNormal = face.normal; + }; - if ( vertexNormals.length === 3 && needsSmoothNormals ) { + function renderObjects( renderList, camera, lights, fog, useBlending, overrideMaterial ) { - for ( i = 0; i < 3; i ++ ) { + var webglObject, object, buffer, material; - vn = vertexNormals[ i ]; + for ( var i = renderList.length - 1; i !== - 1; i -- ) { - normalArray[ offset_normal ] = vn.x; - normalArray[ offset_normal + 1 ] = vn.y; - normalArray[ offset_normal + 2 ] = vn.z; + webglObject = renderList[ i ]; - offset_normal += 3; + object = webglObject.object; + buffer = webglObject.buffer; + + setupMatrices( object, camera ); - } + if ( overrideMaterial ) { - } else { + material = overrideMaterial; - for ( i = 0; i < 3; i ++ ) { + } else { - normalArray[ offset_normal ] = faceNormal.x; - normalArray[ offset_normal + 1 ] = faceNormal.y; - normalArray[ offset_normal + 2 ] = faceNormal.z; + material = webglObject.material; - offset_normal += 3; + if ( ! material ) continue; - } + if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - } + _this.setDepthTest( material.depthTest ); + _this.setDepthWrite( material.depthWrite ); + setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); } - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint ); + _this.setMaterialFaces( material ); - } + if ( buffer instanceof THREE.BufferGeometry ) { - if ( dirtyUvs && obj_uvs && uvType ) { + _this.renderBufferDirect( camera, lights, fog, material, buffer, object ); - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + } else { - fi = chunk_faces3[ f ]; + _this.renderBuffer( camera, lights, fog, material, buffer, object ); - uv = obj_uvs[ fi ]; + } - if ( uv === undefined ) continue; + } - for ( i = 0; i < 3; i ++ ) { + }; - uvi = uv[ i ]; + function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) { - uvArray[ offset_uv ] = uvi.x; - uvArray[ offset_uv + 1 ] = uvi.y; + var webglObject, object, material, program; - offset_uv += 2; + for ( var i = 0, il = renderList.length; i < il; i ++ ) { - } + webglObject = renderList[ i ]; + object = webglObject.object; - } + if ( object.visible ) { - if ( offset_uv > 0 ) { + if ( overrideMaterial ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint ); + material = overrideMaterial; - } + } else { - } + material = webglObject[ materialType ]; - if ( dirtyUvs && obj_uvs2 && uvType ) { + if ( ! material ) continue; - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - fi = chunk_faces3[ f ]; + _this.setDepthTest( material.depthTest ); + _this.setDepthWrite( material.depthWrite ); + setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); - uv2 = obj_uvs2[ fi ]; + } - if ( uv2 === undefined ) continue; + _this.renderImmediateObject( camera, lights, fog, material, object ); - for ( i = 0; i < 3; i ++ ) { + } - uv2i = uv2[ i ]; + } - uv2Array[ offset_uv2 ] = uv2i.x; - uv2Array[ offset_uv2 + 1 ] = uv2i.y; + }; - offset_uv2 += 2; + this.renderImmediateObject = function ( camera, lights, fog, material, object ) { - } + var program = setProgram( camera, lights, fog, material, object ); - } + _currentGeometryGroupHash = - 1; - if ( offset_uv2 > 0 ) { + _this.setMaterialFaces( material ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint ); + if ( object.immediateRenderCallback ) { - } + object.immediateRenderCallback( program, _gl, _frustum ); - } + } else { - if ( dirtyElements ) { + object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } ); - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + } - faceArray[ offset_face ] = vertexIndex; - faceArray[ offset_face + 1 ] = vertexIndex + 1; - faceArray[ offset_face + 2 ] = vertexIndex + 2; + }; - offset_face += 3; + function unrollImmediateBufferMaterial ( globject ) { - lineArray[ offset_line ] = vertexIndex; - lineArray[ offset_line + 1 ] = vertexIndex + 1; - - lineArray[ offset_line + 2 ] = vertexIndex; - lineArray[ offset_line + 3 ] = vertexIndex + 2; - - lineArray[ offset_line + 4 ] = vertexIndex + 1; - lineArray[ offset_line + 5 ] = vertexIndex + 2; - - offset_line += 6; + var object = globject.object, + material = object.material; - vertexIndex += 3; + if ( material.transparent ) { - } + globject.transparent = material; + globject.opaque = null; - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); - _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint ); + } else { - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); - _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint ); + globject.opaque = material; + globject.transparent = null; } - if ( customAttributes ) { + }; - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { + function unrollBufferMaterial ( globject ) { - customAttribute = customAttributes[ i ]; + var object = globject.object; + var buffer = globject.buffer; - if ( ! customAttribute.__original.needsUpdate ) continue; + var geometry = object.geometry; + var material = object.material; - offset_custom = 0; - offset_customSrc = 0; + if ( material instanceof THREE.MeshFaceMaterial ) { - if ( customAttribute.size === 1 ) { + var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex; - if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { + material = material.materials[ materialIndex ]; - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + if ( material.transparent ) { - face = obj_faces[ chunk_faces3[ f ] ]; + globject.material = material; + transparentObjects.push( globject ); - customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ]; - customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ]; - customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ]; + } else { - offset_custom += 3; + globject.material = material; + opaqueObjects.push( globject ); - } + } - } else if ( customAttribute.boundTo === "faces" ) { + } else { - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + if ( material ) { - value = customAttribute.value[ chunk_faces3[ f ] ]; + if ( material.transparent ) { - customAttribute.array[ offset_custom ] = value; - customAttribute.array[ offset_custom + 1 ] = value; - customAttribute.array[ offset_custom + 2 ] = value; + globject.material = material; + transparentObjects.push( globject ); - offset_custom += 3; + } else { - } + globject.material = material; + opaqueObjects.push( globject ); - } + } - } else if ( customAttribute.size === 2 ) { + } - if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { + } - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + }; - face = obj_faces[ chunk_faces3[ f ] ]; + // Objects refresh - v1 = customAttribute.value[ face.a ]; - v2 = customAttribute.value[ face.b ]; - v3 = customAttribute.value[ face.c ]; + var initObjects = function ( scene ) { - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; + if ( ! scene.__webglObjects ) { - customAttribute.array[ offset_custom + 2 ] = v2.x; - customAttribute.array[ offset_custom + 3 ] = v2.y; + scene.__webglObjects = {}; + scene.__webglObjectsImmediate = []; - customAttribute.array[ offset_custom + 4 ] = v3.x; - customAttribute.array[ offset_custom + 5 ] = v3.y; + } - offset_custom += 6; + while ( scene.__objectsAdded.length ) { - } + addObject( scene.__objectsAdded[ 0 ], scene ); + scene.__objectsAdded.splice( 0, 1 ); - } else if ( customAttribute.boundTo === "faces" ) { + } - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + while ( scene.__objectsRemoved.length ) { - value = customAttribute.value[ chunk_faces3[ f ] ]; + removeObject( scene.__objectsRemoved[ 0 ], scene ); + scene.__objectsRemoved.splice( 0, 1 ); - v1 = value; - v2 = value; - v3 = value; + } - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; + }; - customAttribute.array[ offset_custom + 2 ] = v2.x; - customAttribute.array[ offset_custom + 3 ] = v2.y; + // Objects adding - customAttribute.array[ offset_custom + 4 ] = v3.x; - customAttribute.array[ offset_custom + 5 ] = v3.y; + function addObject( object, scene ) { - offset_custom += 6; + var g, geometry, geometryGroup; - } + if ( object.__webglInit === undefined ) { - } + object.__webglInit = true; - } else if ( customAttribute.size === 3 ) { + object._modelViewMatrix = new THREE.Matrix4(); + object._normalMatrix = new THREE.Matrix3(); - var pp; + } + + geometry = object.geometry; + + if ( geometry === undefined ) { - if ( customAttribute.type === "c" ) { + // ImmediateRenderObject - pp = [ "r", "g", "b" ]; + } else if ( geometry.__webglInit === undefined ) { - } else { + geometry.__webglInit = true; + geometry.addEventListener( 'dispose', onGeometryDispose ); - pp = [ "x", "y", "z" ]; + if ( geometry instanceof THREE.BufferGeometry ) { - } + initDirectBuffers( geometry ); - if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { + } else if ( object instanceof THREE.Mesh ) { + + if ( object.__webglActive !== undefined ) { - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + removeObject( object, scene ); - face = obj_faces[ chunk_faces3[ f ] ]; + } + + initGeometryGroups(scene, object, geometry); - v1 = customAttribute.value[ face.a ]; - v2 = customAttribute.value[ face.b ]; - v3 = customAttribute.value[ face.c ]; + } else if ( object instanceof THREE.Line ) { - customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; + if ( ! geometry.__webglVertexBuffer ) { - customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; + createLineBuffers( geometry ); + initLineBuffers( geometry, object ); - customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; + geometry.verticesNeedUpdate = true; + geometry.colorsNeedUpdate = true; + geometry.lineDistancesNeedUpdate = true; - offset_custom += 9; + } - } + } else if ( object instanceof THREE.PointCloud ) { - } else if ( customAttribute.boundTo === "faces" ) { + if ( ! geometry.__webglVertexBuffer ) { - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + createParticleBuffers( geometry ); + initParticleBuffers( geometry, object ); - value = customAttribute.value[ chunk_faces3[ f ] ]; + geometry.verticesNeedUpdate = true; + geometry.colorsNeedUpdate = true; - v1 = value; - v2 = value; - v3 = value; + } - customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; + } - customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; + } - customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; + if ( object.__webglActive === undefined) { - offset_custom += 9; + if ( object instanceof THREE.Mesh ) { - } + geometry = object.geometry; - } else if ( customAttribute.boundTo === "faceVertices" ) { + if ( geometry instanceof THREE.BufferGeometry ) { - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + addBuffer( scene.__webglObjects, geometry, object ); - value = customAttribute.value[ chunk_faces3[ f ] ]; + } else if ( geometry instanceof THREE.Geometry ) { - v1 = value[ 0 ]; - v2 = value[ 1 ]; - v3 = value[ 2 ]; + for ( var i = 0,l = geometry.geometryGroupsList.length; i= 0; o -- ) { - var attributePointer = programAttributes[ attributeName ]; - var attributeItem = geometryAttributes[ attributeName ]; + if ( objlist[ o ].object === object ) { - if ( attributePointer >= 0 ) { + objlist.splice( o, 1 ); - if ( attributeItem ) { + } - var attributeSize = attributeItem.itemSize; + } - _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); - enableAttribute( attributePointer ); - _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32 + }; - } else if ( material.defaultAttributeValues ) { + // Materials - if ( material.defaultAttributeValues[ attributeName ].length === 2 ) { + this.initMaterial = function ( material, lights, fog, object ) { - _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); + material.addEventListener( 'dispose', onMaterialDispose ); - } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) { + var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID; - _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); + if ( material instanceof THREE.MeshDepthMaterial ) { - } + shaderID = 'depth'; - } + } else if ( material instanceof THREE.MeshNormalMaterial ) { - } + shaderID = 'normal'; - } + } else if ( material instanceof THREE.MeshBasicMaterial ) { - disableUnusedAttributes(); + shaderID = 'basic'; - } + } else if ( material instanceof THREE.MeshLambertMaterial ) { - this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) { + shaderID = 'lambert'; - if ( material.visible === false ) return; + } else if ( material instanceof THREE.MeshPhongMaterial ) { - var linewidth, a, attribute; - var attributeItem, attributeName, attributePointer, attributeSize; + shaderID = 'phong'; - var program = setProgram( camera, lights, fog, material, object ); - - var programAttributes = program.attributes; - var geometryAttributes = geometry.attributes; - - var updateBuffers = false, - wireframeBit = material.wireframe ? 1 : 0, - geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; + } else if ( material instanceof THREE.LineBasicMaterial ) { - if ( geometryHash !== _currentGeometryGroupHash ) { + shaderID = 'basic'; - _currentGeometryGroupHash = geometryHash; - updateBuffers = true; + } else if ( material instanceof THREE.LineDashedMaterial ) { - } + shaderID = 'dashed'; - if ( updateBuffers ) { + } else if ( material instanceof THREE.PointCloudMaterial ) { - initAttributes(); + shaderID = 'particle_basic'; } - // render mesh - - if ( object instanceof THREE.Mesh ) { - - var index = geometryAttributes[ "index" ]; + if ( shaderID ) { - if ( index ) { + var shader = THREE.ShaderLib[ shaderID ]; - // indexed triangles + material.__webglShader = { + uniforms: THREE.UniformsUtils.clone( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader + } - var type, size; + } else { - if ( index.array instanceof Uint32Array ) { + material.__webglShader = { + uniforms: material.uniforms, + vertexShader: material.vertexShader, + fragmentShader: material.fragmentShader + } - type = _gl.UNSIGNED_INT; - size = 4; + } - } else { + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) - type = _gl.UNSIGNED_SHORT; - size = 2; + maxLightCount = allocateLights( lights ); - } + maxShadows = allocateShadows( lights ); - var offsets = geometry.offsets; + maxBones = allocateBones( object ); - if ( offsets.length === 0 ) { + parameters = { - if ( updateBuffers ) { + precision: _precision, + supportsVertexTextures: _supportsVertexTextures, - setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); + map: !! material.map, + envMap: !! material.envMap, + lightMap: !! material.lightMap, + bumpMap: !! material.bumpMap, + normalMap: !! material.normalMap, + specularMap: !! material.specularMap, + alphaMap: !! material.alphaMap, - } + vertexColors: material.vertexColors, - _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 ); + fog: fog, + useFog: material.fog, + fogExp: fog instanceof THREE.FogExp2, - _this.info.render.calls ++; - _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared - _this.info.render.faces += index.array.length / 3; + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: _logarithmicDepthBuffer, - } else { + skinning: material.skinning, + maxBones: maxBones, + useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture, - // if there is more than 1 chunk - // must set attribute pointers to use new offsets for each chunk - // even if geometry and materials didn't change + morphTargets: material.morphTargets, + morphNormals: material.morphNormals, + maxMorphTargets: this.maxMorphTargets, + maxMorphNormals: this.maxMorphNormals, - updateBuffers = true; + maxDirLights: maxLightCount.directional, + maxPointLights: maxLightCount.point, + maxSpotLights: maxLightCount.spot, + maxHemiLights: maxLightCount.hemi, - for ( var i = 0, il = offsets.length; i < il; i ++ ) { + maxShadows: maxShadows, + shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0, + shadowMapType: this.shadowMapType, + shadowMapDebug: this.shadowMapDebug, + shadowMapCascade: this.shadowMapCascade, - var startIndex = offsets[ i ].index; + alphaTest: material.alphaTest, + metal: material.metal, + wrapAround: material.wrapAround, + doubleSided: material.side === THREE.DoubleSide, + flipSided: material.side === THREE.BackSide - if ( updateBuffers ) { + }; - setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ); - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); + // Generate code - } + var chunks = []; - // render indexed triangles + if ( shaderID ) { - _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size ); + chunks.push( shaderID ); - _this.info.render.calls ++; - _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared - _this.info.render.faces += offsets[ i ].count / 3; + } else { - } + chunks.push( material.fragmentShader ); + chunks.push( material.vertexShader ); - } + } - } else { + for ( var d in material.defines ) { - // non-indexed triangles + chunks.push( d ); + chunks.push( material.defines[ d ] ); - if ( updateBuffers ) { + } - setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); + for ( var p in parameters ) { - } + chunks.push( p ); + chunks.push( parameters[ p ] ); - var position = geometry.attributes[ "position" ]; + } - // render non-indexed triangles + var code = chunks.join(); - _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 ); + var program; - _this.info.render.calls ++; - _this.info.render.vertices += position.array.length / 3; - _this.info.render.faces += position.array.length / 9; + // Check if code has been already compiled - } + for ( var p = 0, pl = _programs.length; p < pl; p ++ ) { - } else if ( object instanceof THREE.ParticleSystem ) { + var programInfo = _programs[ p ]; - // render particles + if ( programInfo.code === code ) { - if ( updateBuffers ) { + program = programInfo; + program.usedTimes ++; - setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); + break; } - var position = geometryAttributes[ "position" ]; - - // render particles + } - _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 ); + if ( program === undefined ) { - _this.info.render.calls ++; - _this.info.render.points += position.array.length / 3; + program = new THREE.WebGLProgram( this, code, material, parameters ); + _programs.push( program ); - } else if ( object instanceof THREE.Line ) { + _this.info.memory.programs = _programs.length; - var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; + } - setLineWidth( material.linewidth ); + material.program = program; - var index = geometryAttributes[ "index" ]; + var attributes = material.program.attributes; - if ( index ) { + if ( material.morphTargets ) { - // indexed lines + material.numSupportedMorphTargets = 0; - var type, size; + var id, base = 'morphTarget'; - if ( index.array instanceof Uint32Array ){ + for ( i = 0; i < this.maxMorphTargets; i ++ ) { - type = _gl.UNSIGNED_INT; - size = 4; + id = base + i; - } else { + if ( attributes[ id ] >= 0 ) { - type = _gl.UNSIGNED_SHORT; - size = 2; + material.numSupportedMorphTargets ++; } - var offsets = geometry.offsets; - - if ( offsets.length === 0 ) { + } - if ( updateBuffers ) { + } - setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); + if ( material.morphNormals ) { - } + material.numSupportedMorphNormals = 0; - _gl.drawElements( _gl.LINES, index.array.length, type, 0 ); // 2 bytes per Uint16Array + var id, base = 'morphNormal'; - _this.info.render.calls ++; - _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared + for ( i = 0; i < this.maxMorphNormals; i ++ ) { - } else { + id = base + i; - // if there is more than 1 chunk - // must set attribute pointers to use new offsets for each chunk - // even if geometry and materials didn't change + if ( attributes[ id ] >= 0 ) { - if ( offsets.length > 1 ) updateBuffers = true; + material.numSupportedMorphNormals ++; - for ( var i = 0, il = offsets.length; i < il; i ++ ) { + } - var startIndex = offsets[ i ].index; + } - if ( updateBuffers ) { + } - setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ); - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); + material.uniformsList = []; - } + for ( u in material.__webglShader.uniforms ) { - // render indexed lines + var location = material.program.uniforms[ u ]; - _gl.drawElements( _gl.LINES, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array + if ( location ) { + material.uniformsList.push( [ material.__webglShader.uniforms[ u ], location ] ); + } - _this.info.render.calls ++; - _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared + } - } + }; - } + function setProgram( camera, lights, fog, material, object ) { - } else { + _usedTextureUnits = 0; - // non-indexed lines + if ( material.needsUpdate ) { - if ( updateBuffers ) { + if ( material.program ) deallocateMaterial( material ); - setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); + _this.initMaterial( material, lights, fog, object ); + material.needsUpdate = false; - } + } - var position = geometryAttributes[ "position" ]; + if ( material.morphTargets ) { - _gl.drawArrays( mode, 0, position.array.length / 3 ); + if ( ! object.__webglMorphTargetInfluences ) { - _this.info.render.calls ++; - _this.info.render.points += position.array.length / 3; + object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets ); } } - }; + var refreshProgram = false; + var refreshMaterial = false; + var refreshLights = false; - this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) { + var program = material.program, + p_uniforms = program.uniforms, + m_uniforms = material.__webglShader.uniforms; - if ( material.visible === false ) return; + if ( program.id !== _currentProgram ) { - var linewidth, a, attribute, i, il; + _gl.useProgram( program.program ); + _currentProgram = program.id; - var program = setProgram( camera, lights, fog, material, object ); + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; - var attributes = program.attributes; + } - var updateBuffers = false, - wireframeBit = material.wireframe ? 1 : 0, - geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; + if ( material.id !== _currentMaterialId ) { - if ( geometryGroupHash !== _currentGeometryGroupHash ) { + if ( _currentMaterialId === -1 ) refreshLights = true; + _currentMaterialId = material.id; - _currentGeometryGroupHash = geometryGroupHash; - updateBuffers = true; + refreshMaterial = true; } - if ( updateBuffers ) { + if ( refreshProgram || camera !== _currentCamera ) { - initAttributes(); + _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); - } + if ( _logarithmicDepthBuffer ) { - // vertices + _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); - if ( !material.morphTargets && attributes.position >= 0 ) { + } - if ( updateBuffers ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); - enableAttribute( attributes.position ); - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); + if ( camera !== _currentCamera ) _currentCamera = camera; - } + // load material specific uniforms + // (shader material also gets them for the sake of genericity) - } else { + if ( material instanceof THREE.ShaderMaterial || + material instanceof THREE.MeshPhongMaterial || + material.envMap ) { - if ( object.morphTargetBase ) { + if ( p_uniforms.cameraPosition !== null ) { - setupMorphTargets( material, geometryGroup, object ); + _vector3.setFromMatrixPosition( camera.matrixWorld ); + _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z ); + + } } - } + if ( material instanceof THREE.MeshPhongMaterial || + material instanceof THREE.MeshLambertMaterial || + material instanceof THREE.ShaderMaterial || + material.skinning ) { + if ( p_uniforms.viewMatrix !== null ) { - if ( updateBuffers ) { + _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements ); - // custom attributes + } - // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers + } - if ( geometryGroup.__webglCustomAttributesList ) { + } - for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) { + // skinning uniforms must be set even if material didn't change + // auto-setting of texture unit for bone texture must go before other textures + // not sure why, but otherwise weird things happen - attribute = geometryGroup.__webglCustomAttributesList[ i ]; + if ( material.skinning ) { - if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) { + if ( object.bindMatrix && p_uniforms.bindMatrix !== null ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer ); - enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] ); - _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 ); + _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements ); - } + } - } + if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== null ) { + + _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements ); } + if ( _supportsBoneTextures && object.skeleton && object.skeleton.useVertexTexture ) { - // colors + if ( p_uniforms.boneTexture !== null ) { - if ( attributes.color >= 0 ) { + var textureUnit = getTextureUnit(); - if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) { + _gl.uniform1i( p_uniforms.boneTexture, textureUnit ); + _this.setTexture( object.skeleton.boneTexture, textureUnit ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); - enableAttribute( attributes.color ); - _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); + } - } else if ( material.defaultAttributeValues ) { + if ( p_uniforms.boneTextureWidth !== null ) { + _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth ); - _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color ); + } + + if ( p_uniforms.boneTextureHeight !== null ) { + + _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight ); } - } + } else if ( object.skeleton && object.skeleton.boneMatrices ) { - // normals + if ( p_uniforms.boneGlobalMatrices !== null ) { - if ( attributes.normal >= 0 ) { + _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); - enableAttribute( attributes.normal ); - _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); + } } - // tangents + } - if ( attributes.tangent >= 0 ) { + if ( refreshMaterial ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); - enableAttribute( attributes.tangent ); - _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 ); + // refresh uniforms common to several materials - } + if ( fog && material.fog ) { - // uvs + refreshUniformsFog( m_uniforms, fog ); - if ( attributes.uv >= 0 ) { + } - if ( object.geometry.faceVertexUvs[0] ) { + if ( material instanceof THREE.MeshPhongMaterial || + material instanceof THREE.MeshLambertMaterial || + material.lights ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); - enableAttribute( attributes.uv ); - _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); + if ( _lightsNeedUpdate ) { - } else if ( material.defaultAttributeValues ) { + refreshLights = true; + setupLights( lights ); + _lightsNeedUpdate = false; + } + + if ( refreshLights ) { + refreshUniformsLights( m_uniforms, _lights ); + markUniformsLightsNeedsUpdate( m_uniforms, true ); + } else { + markUniformsLightsNeedsUpdate( m_uniforms, false ); + } + } - _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv ); + if ( material instanceof THREE.MeshBasicMaterial || + material instanceof THREE.MeshLambertMaterial || + material instanceof THREE.MeshPhongMaterial ) { - } + refreshUniformsCommon( m_uniforms, material ); } - if ( attributes.uv2 >= 0 ) { + // refresh single material specific uniforms - if ( object.geometry.faceVertexUvs[1] ) { + if ( material instanceof THREE.LineBasicMaterial ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); - enableAttribute( attributes.uv2 ); - _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 ); + refreshUniformsLine( m_uniforms, material ); - } else if ( material.defaultAttributeValues ) { + } else if ( material instanceof THREE.LineDashedMaterial ) { + refreshUniformsLine( m_uniforms, material ); + refreshUniformsDash( m_uniforms, material ); - _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 ); + } else if ( material instanceof THREE.PointCloudMaterial ) { - } + refreshUniformsParticle( m_uniforms, material ); - } + } else if ( material instanceof THREE.MeshPhongMaterial ) { - if ( material.skinning && - attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) { + refreshUniformsPhong( m_uniforms, material ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); - enableAttribute( attributes.skinIndex ); - _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 ); + } else if ( material instanceof THREE.MeshLambertMaterial ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); - enableAttribute( attributes.skinWeight ); - _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 ); + refreshUniformsLambert( m_uniforms, material ); - } + } else if ( material instanceof THREE.MeshDepthMaterial ) { - // line distances + m_uniforms.mNear.value = camera.near; + m_uniforms.mFar.value = camera.far; + m_uniforms.opacity.value = material.opacity; - if ( attributes.lineDistance >= 0 ) { + } else if ( material instanceof THREE.MeshNormalMaterial ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer ); - enableAttribute( attributes.lineDistance ); - _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 ); + m_uniforms.opacity.value = material.opacity; } - } + if ( object.receiveShadow && ! material._shadowPass ) { - disableUnusedAttributes(); + refreshUniformsShadow( m_uniforms, lights ); - // render mesh + } - if ( object instanceof THREE.Mesh ) { + // load common uniforms - var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT; + loadUniformsGeneric( material.uniformsList ); - // wireframe + } - if ( material.wireframe ) { + loadUniformsMatrices( p_uniforms, object ); - setLineWidth( material.wireframeLinewidth ); - if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); - _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 ); + if ( p_uniforms.modelMatrix !== null ) { - // triangles + _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements ); - } else { + } - if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); - _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 ); + return program; - } + }; - _this.info.render.calls ++; - _this.info.render.vertices += geometryGroup.__webglFaceCount; - _this.info.render.faces += geometryGroup.__webglFaceCount / 3; + // Uniforms (refresh uniforms objects) - // render lines + function refreshUniformsCommon ( uniforms, material ) { - } else if ( object instanceof THREE.Line ) { + uniforms.opacity.value = material.opacity; - var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; + if ( _this.gammaInput ) { - setLineWidth( material.linewidth ); + uniforms.diffuse.value.copyGammaToLinear( material.color ); - _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount ); + } else { - _this.info.render.calls ++; + uniforms.diffuse.value = material.color; - // render particles + } - } else if ( object instanceof THREE.ParticleSystem ) { + uniforms.map.value = material.map; + uniforms.lightMap.value = material.lightMap; + uniforms.specularMap.value = material.specularMap; + uniforms.alphaMap.value = material.alphaMap; - _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount ); + if ( material.bumpMap ) { - _this.info.render.calls ++; - _this.info.render.points += geometryGroup.__webglParticleCount; + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; } - }; - - function initAttributes() { - - for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) { + if ( material.normalMap ) { - _newAttributes[ i ] = 0; + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); } - } + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. normal map + // 4. bump map + // 5. alpha map - function enableAttribute( attribute ) { + var uvScaleMap; - _newAttributes[ attribute ] = 1; + if ( material.map ) { - if ( _enabledAttributes[ attribute ] === 0 ) { + uvScaleMap = material.map; - _gl.enableVertexAttribArray( attribute ); - _enabledAttributes[ attribute ] = 1; + } else if ( material.specularMap ) { - } + uvScaleMap = material.specularMap; - } + } else if ( material.normalMap ) { - function disableUnusedAttributes() { + uvScaleMap = material.normalMap; - for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) { + } else if ( material.bumpMap ) { - if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) { + uvScaleMap = material.bumpMap; - _gl.disableVertexAttribArray( i ); - _enabledAttributes[ i ] = 0; + } else if ( material.alphaMap ) { - } + uvScaleMap = material.alphaMap; } - } + if ( uvScaleMap !== undefined ) { - function setupMorphTargets ( material, geometryGroup, object ) { + var offset = uvScaleMap.offset; + var repeat = uvScaleMap.repeat; - // set base + uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); - var attributes = material.program.attributes; + } - if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) { + uniforms.envMap.value = material.envMap; + uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1; - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] ); - enableAttribute( attributes.position ); - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); + if ( _this.gammaInput ) { - } else if ( attributes.position >= 0 ) { + //uniforms.reflectivity.value = material.reflectivity * material.reflectivity; + uniforms.reflectivity.value = material.reflectivity; - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); - enableAttribute( attributes.position ); - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); + } else { + + uniforms.reflectivity.value = material.reflectivity; } - if ( object.morphTargetForcedOrder.length ) { + uniforms.refractionRatio.value = material.refractionRatio; + uniforms.combine.value = material.combine; + uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping; - // set forced order + }; - var m = 0; - var order = object.morphTargetForcedOrder; - var influences = object.morphTargetInfluences; + function refreshUniformsLine ( uniforms, material ) { - while ( m < material.numSupportedMorphTargets && m < order.length ) { + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; - if ( attributes[ "morphTarget" + m ] >= 0 ) { + }; - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] ); - enableAttribute( attributes[ "morphTarget" + m ] ); - _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); + function refreshUniformsDash ( uniforms, material ) { - } + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; - if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) { + }; - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] ); - enableAttribute( attributes[ "morphNormal" + m ] ); - _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); + function refreshUniformsParticle ( uniforms, material ) { - } + uniforms.psColor.value = material.color; + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size; + uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this. - object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ]; + uniforms.map.value = material.map; - m ++; - } + }; - } else { + function refreshUniformsFog ( uniforms, fog ) { - // find the most influencing + uniforms.fogColor.value = fog.color; - var influence, activeInfluenceIndices = []; - var influences = object.morphTargetInfluences; - var i, il = influences.length; + if ( fog instanceof THREE.Fog ) { - for ( i = 0; i < il; i ++ ) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; - influence = influences[ i ]; + } else if ( fog instanceof THREE.FogExp2 ) { - if ( influence > 0 ) { + uniforms.fogDensity.value = fog.density; - activeInfluenceIndices.push( [ influence, i ] ); + } - } + }; - } + function refreshUniformsPhong ( uniforms, material ) { - if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) { + uniforms.shininess.value = material.shininess; - activeInfluenceIndices.sort( numericalSort ); - activeInfluenceIndices.length = material.numSupportedMorphTargets; + if ( _this.gammaInput ) { - } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) { + uniforms.ambient.value.copyGammaToLinear( material.ambient ); + uniforms.emissive.value.copyGammaToLinear( material.emissive ); + uniforms.specular.value.copyGammaToLinear( material.specular ); - activeInfluenceIndices.sort( numericalSort ); + } else { - } else if ( activeInfluenceIndices.length === 0 ) { + uniforms.ambient.value = material.ambient; + uniforms.emissive.value = material.emissive; + uniforms.specular.value = material.specular; - activeInfluenceIndices.push( [ 0, 0 ] ); + } - }; + if ( material.wrapAround ) { - var influenceIndex, m = 0; + uniforms.wrapRGB.value.copy( material.wrapRGB ); - while ( m < material.numSupportedMorphTargets ) { + } - if ( activeInfluenceIndices[ m ] ) { + }; - influenceIndex = activeInfluenceIndices[ m ][ 1 ]; + function refreshUniformsLambert ( uniforms, material ) { - if ( attributes[ "morphTarget" + m ] >= 0 ) { + if ( _this.gammaInput ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] ); - enableAttribute( attributes[ "morphTarget" + m ] ); - _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); + uniforms.ambient.value.copyGammaToLinear( material.ambient ); + uniforms.emissive.value.copyGammaToLinear( material.emissive ); - } + } else { - if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) { + uniforms.ambient.value = material.ambient; + uniforms.emissive.value = material.emissive; - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] ); - enableAttribute( attributes[ "morphNormal" + m ] ); - _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); + } + if ( material.wrapAround ) { - } + uniforms.wrapRGB.value.copy( material.wrapRGB ); - object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ]; + } - } else { + }; - /* - _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); + function refreshUniformsLights ( uniforms, lights ) { - if ( material.morphNormals ) { + uniforms.ambientLightColor.value = lights.ambient; - _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); + uniforms.directionalLightColor.value = lights.directional.colors; + uniforms.directionalLightDirection.value = lights.directional.positions; - } - */ + uniforms.pointLightColor.value = lights.point.colors; + uniforms.pointLightPosition.value = lights.point.positions; + uniforms.pointLightDistance.value = lights.point.distances; - object.__webglMorphTargetInfluences[ m ] = 0; + uniforms.spotLightColor.value = lights.spot.colors; + uniforms.spotLightPosition.value = lights.spot.positions; + uniforms.spotLightDistance.value = lights.spot.distances; + uniforms.spotLightDirection.value = lights.spot.directions; + uniforms.spotLightAngleCos.value = lights.spot.anglesCos; + uniforms.spotLightExponent.value = lights.spot.exponents; - } + uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors; + uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors; + uniforms.hemisphereLightDirection.value = lights.hemi.positions; - m ++; + }; - } + // If uniforms are marked as clean, they don't need to be loaded to the GPU. - } + function markUniformsLightsNeedsUpdate ( uniforms, boolean ) { - // load updated influences uniform + uniforms.ambientLightColor.needsUpdate = boolean; - if ( material.program.uniforms.morphTargetInfluences !== null ) { + uniforms.directionalLightColor.needsUpdate = boolean; + uniforms.directionalLightDirection.needsUpdate = boolean; - _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences ); + uniforms.pointLightColor.needsUpdate = boolean; + uniforms.pointLightPosition.needsUpdate = boolean; + uniforms.pointLightDistance.needsUpdate = boolean; - } + uniforms.spotLightColor.needsUpdate = boolean; + uniforms.spotLightPosition.needsUpdate = boolean; + uniforms.spotLightDistance.needsUpdate = boolean; + uniforms.spotLightDirection.needsUpdate = boolean; + uniforms.spotLightAngleCos.needsUpdate = boolean; + uniforms.spotLightExponent.needsUpdate = boolean; + + uniforms.hemisphereLightSkyColor.needsUpdate = boolean; + uniforms.hemisphereLightGroundColor.needsUpdate = boolean; + uniforms.hemisphereLightDirection.needsUpdate = boolean; }; - // Sorting + function refreshUniformsShadow ( uniforms, lights ) { - function painterSortStable ( a, b ) { + if ( uniforms.shadowMatrix ) { - if ( a.z !== b.z ) { + var j = 0; - return b.z - a.z; + for ( var i = 0, il = lights.length; i < il; i ++ ) { - } else { + var light = lights[ i ]; - return a.id - b.id; + if ( ! light.castShadow ) continue; - } + if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) { - }; + uniforms.shadowMap.value[ j ] = light.shadowMap; + uniforms.shadowMapSize.value[ j ] = light.shadowMapSize; - function numericalSort ( a, b ) { + uniforms.shadowMatrix.value[ j ] = light.shadowMatrix; - return b[ 0 ] - a[ 0 ]; + uniforms.shadowDarkness.value[ j ] = light.shadowDarkness; + uniforms.shadowBias.value[ j ] = light.shadowBias; + + j ++; + + } + + } + + } }; + // Uniforms (load to GPU) - // Rendering + function loadUniformsMatrices ( uniforms, object ) { - this.render = function ( scene, camera, renderTarget, forceClear ) { + _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements ); - if ( camera instanceof THREE.Camera === false ) { + if ( uniforms.normalMatrix ) { - console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); - return; + _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements ); } - var i, il, + }; - webglObject, object, - renderList, + function getTextureUnit() { - lights = scene.__lights, - fog = scene.fog; + var textureUnit = _usedTextureUnits; - // reset caching for this frame + if ( textureUnit >= _maxTextures ) { - _currentMaterialId = -1; - _lightsNeedUpdate = true; + console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures ); - // update scene graph + } - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); + _usedTextureUnits += 1; - // update camera matrices and frustum + return textureUnit; - if ( camera.parent === undefined ) camera.updateMatrixWorld(); + }; - camera.matrixWorldInverse.getInverse( camera.matrixWorld ); + function loadUniformsGeneric ( uniforms ) { - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + var texture, textureUnit, offset; - // update WebGL objects + for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) { - if ( this.autoUpdateObjects ) this.initWebGLObjects( scene ); + var uniform = uniforms[ j ][ 0 ]; - // custom render plugins (pre pass) + // needsUpdate property is not added to all uniforms. + if ( uniform.needsUpdate === false ) continue; - renderPlugins( this.renderPluginsPre, scene, camera ); + var type = uniform.type; + var value = uniform.value; + var location = uniforms[ j ][ 1 ]; - // + switch ( type ) { - _this.info.render.calls = 0; - _this.info.render.vertices = 0; - _this.info.render.faces = 0; - _this.info.render.points = 0; + case '1i': + _gl.uniform1i( location, value ); + break; - this.setRenderTarget( renderTarget ); + case '1f': + _gl.uniform1f( location, value ); + break; - if ( this.autoClear || forceClear ) { + case '2f': + _gl.uniform2f( location, value[ 0 ], value[ 1 ] ); + break; - this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); + case '3f': + _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] ); + break; - } + case '4f': + _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] ); + break; - // set matrices for regular objects (frustum culled) + case '1iv': + _gl.uniform1iv( location, value ); + break; - renderList = scene.__webglObjects; + case '3iv': + _gl.uniform3iv( location, value ); + break; - for ( i = 0, il = renderList.length; i < il; i ++ ) { + case '1fv': + _gl.uniform1fv( location, value ); + break; - webglObject = renderList[ i ]; - object = webglObject.object; + case '2fv': + _gl.uniform2fv( location, value ); + break; - webglObject.id = i; - webglObject.render = false; + case '3fv': + _gl.uniform3fv( location, value ); + break; - if ( object.visible ) { + case '4fv': + _gl.uniform4fv( location, value ); + break; - if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) { + case 'Matrix3fv': + _gl.uniformMatrix3fv( location, false, value ); + break; - setupMatrices( object, camera ); + case 'Matrix4fv': + _gl.uniformMatrix4fv( location, false, value ); + break; - unrollBufferMaterial( webglObject ); + // - webglObject.render = true; + case 'i': - if ( this.sortObjects === true ) { + // single integer + _gl.uniform1i( location, value ); - if ( object.renderDepth !== null ) { + break; - webglObject.z = object.renderDepth; + case 'f': - } else { + // single float + _gl.uniform1f( location, value ); - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _projScreenMatrix ); + break; - webglObject.z = _vector3.z; + case 'v2': - } + // single THREE.Vector2 + _gl.uniform2f( location, value.x, value.y ); - } + break; - } + case 'v3': - } + // single THREE.Vector3 + _gl.uniform3f( location, value.x, value.y, value.z ); - } + break; - if ( this.sortObjects ) { + case 'v4': - renderList.sort( painterSortStable ); + // single THREE.Vector4 + _gl.uniform4f( location, value.x, value.y, value.z, value.w ); - } + break; - // set matrices for immediate objects + case 'c': - renderList = scene.__webglObjectsImmediate; + // single THREE.Color + _gl.uniform3f( location, value.r, value.g, value.b ); - for ( i = 0, il = renderList.length; i < il; i ++ ) { + break; - webglObject = renderList[ i ]; - object = webglObject.object; + case 'iv1': - if ( object.visible ) { + // flat array of integers (JS or typed array) + _gl.uniform1iv( location, value ); - setupMatrices( object, camera ); + break; - unrollImmediateBufferMaterial( webglObject ); + case 'iv': - } + // flat array of integers with 3 x N size (JS or typed array) + _gl.uniform3iv( location, value ); - } - - if ( scene.overrideMaterial ) { + break; - var material = scene.overrideMaterial; + case 'fv1': - this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - this.setDepthTest( material.depthTest ); - this.setDepthWrite( material.depthWrite ); - setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + // flat array of floats (JS or typed array) + _gl.uniform1fv( location, value ); - renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material ); - renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material ); + break; - } else { + case 'fv': - var material = null; + // flat array of floats with 3 x N size (JS or typed array) + _gl.uniform3fv( location, value ); - // opaque pass (front-to-back order) + break; - this.setBlending( THREE.NoBlending ); + case 'v2v': - renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material ); - renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material ); + // array of THREE.Vector2 - // transparent pass (back-to-front order) + if ( uniform._array === undefined ) { - renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material ); - renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material ); + uniform._array = new Float32Array( 2 * value.length ); - } + } - // custom render plugins (post pass) + for ( var i = 0, il = value.length; i < il; i ++ ) { - renderPlugins( this.renderPluginsPost, scene, camera ); + offset = i * 2; + uniform._array[ offset ] = value[ i ].x; + uniform._array[ offset + 1 ] = value[ i ].y; - // Generate mipmap if we're using any kind of mipmap filtering + } - if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) { + _gl.uniform2fv( location, uniform._array ); - updateRenderTargetMipmap( renderTarget ); + break; - } + case 'v3v': - // Ensure depth buffer writing is enabled so it can be cleared on next render + // array of THREE.Vector3 - this.setDepthTest( true ); - this.setDepthWrite( true ); + if ( uniform._array === undefined ) { - // _gl.finish(); + uniform._array = new Float32Array( 3 * value.length ); - }; + } - function renderPlugins( plugins, scene, camera ) { + for ( var i = 0, il = value.length; i < il; i ++ ) { - if ( ! plugins.length ) return; + offset = i * 3; - for ( var i = 0, il = plugins.length; i < il; i ++ ) { + uniform._array[ offset ] = value[ i ].x; + uniform._array[ offset + 1 ] = value[ i ].y; + uniform._array[ offset + 2 ] = value[ i ].z; - // reset state for plugin (to start from clean slate) + } - _currentProgram = null; - _currentCamera = null; + _gl.uniform3fv( location, uniform._array ); - _oldBlending = -1; - _oldDepthTest = -1; - _oldDepthWrite = -1; - _oldDoubleSided = -1; - _oldFlipSided = -1; - _currentGeometryGroupHash = -1; - _currentMaterialId = -1; + break; - _lightsNeedUpdate = true; + case 'v4v': - plugins[ i ].render( scene, camera, _currentWidth, _currentHeight ); + // array of THREE.Vector4 - // reset state after plugin (anything could have changed) + if ( uniform._array === undefined ) { - _currentProgram = null; - _currentCamera = null; + uniform._array = new Float32Array( 4 * value.length ); - _oldBlending = -1; - _oldDepthTest = -1; - _oldDepthWrite = -1; - _oldDoubleSided = -1; - _oldFlipSided = -1; - _currentGeometryGroupHash = -1; - _currentMaterialId = -1; + } - _lightsNeedUpdate = true; + for ( var i = 0, il = value.length; i < il; i ++ ) { - } + offset = i * 4; - }; + uniform._array[ offset ] = value[ i ].x; + uniform._array[ offset + 1 ] = value[ i ].y; + uniform._array[ offset + 2 ] = value[ i ].z; + uniform._array[ offset + 3 ] = value[ i ].w; - function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) { + } - var webglObject, object, buffer, material, start, end, delta; + _gl.uniform4fv( location, uniform._array ); - if ( reverse ) { + break; - start = renderList.length - 1; - end = -1; - delta = -1; + case 'm3': - } else { + // single THREE.Matrix3 + _gl.uniformMatrix3fv( location, false, value.elements ); - start = 0; - end = renderList.length; - delta = 1; - } + break; - for ( var i = start; i !== end; i += delta ) { + case 'm3v': - webglObject = renderList[ i ]; + // array of THREE.Matrix3 - if ( webglObject.render ) { + if ( uniform._array === undefined ) { - object = webglObject.object; - buffer = webglObject.buffer; + uniform._array = new Float32Array( 9 * value.length ); - if ( overrideMaterial ) { + } - material = overrideMaterial; + for ( var i = 0, il = value.length; i < il; i ++ ) { - } else { + value[ i ].flattenToArrayOffset( uniform._array, i * 9 ); - material = webglObject[ materialType ]; + } - if ( ! material ) continue; + _gl.uniformMatrix3fv( location, false, uniform._array ); - if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); + break; - _this.setDepthTest( material.depthTest ); - _this.setDepthWrite( material.depthWrite ); - setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + case 'm4': - } + // single THREE.Matrix4 + _gl.uniformMatrix4fv( location, false, value.elements ); - _this.setMaterialFaces( material ); + break; - if ( buffer instanceof THREE.BufferGeometry ) { + case 'm4v': - _this.renderBufferDirect( camera, lights, fog, material, buffer, object ); + // array of THREE.Matrix4 - } else { + if ( uniform._array === undefined ) { - _this.renderBuffer( camera, lights, fog, material, buffer, object ); + uniform._array = new Float32Array( 16 * value.length ); - } + } - } + for ( var i = 0, il = value.length; i < il; i ++ ) { - } + value[ i ].flattenToArrayOffset( uniform._array, i * 16 ); - }; + } - function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) { + _gl.uniformMatrix4fv( location, false, uniform._array ); - var webglObject, object, material, program; + break; - for ( var i = 0, il = renderList.length; i < il; i ++ ) { + case 't': - webglObject = renderList[ i ]; - object = webglObject.object; + // single THREE.Texture (2d or cube) - if ( object.visible ) { + texture = value; + textureUnit = getTextureUnit(); - if ( overrideMaterial ) { + _gl.uniform1i( location, textureUnit ); - material = overrideMaterial; + if ( ! texture ) continue; - } else { + if ( texture instanceof THREE.CubeTexture || + ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/ - material = webglObject[ materialType ]; + setCubeTexture( texture, textureUnit ); - if ( ! material ) continue; + } else if ( texture instanceof THREE.WebGLRenderTargetCube ) { - if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); + setCubeTextureDynamic( texture, textureUnit ); - _this.setDepthTest( material.depthTest ); - _this.setDepthWrite( material.depthWrite ); - setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + } else { - } + _this.setTexture( texture, textureUnit ); - _this.renderImmediateObject( camera, lights, fog, material, object ); + } - } + break; - } + case 'tv': - }; + // array of THREE.Texture (2d) - this.renderImmediateObject = function ( camera, lights, fog, material, object ) { + if ( uniform._array === undefined ) { - var program = setProgram( camera, lights, fog, material, object ); + uniform._array = []; - _currentGeometryGroupHash = -1; + } - _this.setMaterialFaces( material ); + for ( var i = 0, il = uniform.value.length; i < il; i ++ ) { - if ( object.immediateRenderCallback ) { + uniform._array[ i ] = getTextureUnit(); - object.immediateRenderCallback( program, _gl, _frustum ); + } - } else { + _gl.uniform1iv( location, uniform._array ); - object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } ); + for ( var i = 0, il = uniform.value.length; i < il; i ++ ) { - } + texture = uniform.value[ i ]; + textureUnit = uniform._array[ i ]; - }; + if ( ! texture ) continue; - function unrollImmediateBufferMaterial ( globject ) { + _this.setTexture( texture, textureUnit ); - var object = globject.object, - material = object.material; + } - if ( material.transparent ) { + break; - globject.transparent = material; - globject.opaque = null; + default: - } else { + console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type ); - globject.opaque = material; - globject.transparent = null; + } } }; - function unrollBufferMaterial ( globject ) { + function setupMatrices ( object, camera ) { - var object = globject.object; - var buffer = globject.buffer; + object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object._normalMatrix.getNormalMatrix( object._modelViewMatrix ); - var geometry = object.geometry; - var material = object.material; + }; - if ( material instanceof THREE.MeshFaceMaterial ) { + // - var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex; + function setColorGamma( array, offset, color, intensitySq ) { - material = material.materials[ materialIndex ]; + array[ offset ] = color.r * color.r * intensitySq; + array[ offset + 1 ] = color.g * color.g * intensitySq; + array[ offset + 2 ] = color.b * color.b * intensitySq; - if ( material.transparent ) { + }; - globject.transparent = material; - globject.opaque = null; + function setColorLinear( array, offset, color, intensity ) { - } else { + array[ offset ] = color.r * intensity; + array[ offset + 1 ] = color.g * intensity; + array[ offset + 2 ] = color.b * intensity; - globject.opaque = material; - globject.transparent = null; + }; - } + function setupLights ( lights ) { - } else { + var l, ll, light, n, + r = 0, g = 0, b = 0, + color, skyColor, groundColor, + intensity, intensitySq, + position, + distance, - if ( material ) { + zlights = _lights, - if ( material.transparent ) { + dirColors = zlights.directional.colors, + dirPositions = zlights.directional.positions, - globject.transparent = material; - globject.opaque = null; + pointColors = zlights.point.colors, + pointPositions = zlights.point.positions, + pointDistances = zlights.point.distances, - } else { + spotColors = zlights.spot.colors, + spotPositions = zlights.spot.positions, + spotDistances = zlights.spot.distances, + spotDirections = zlights.spot.directions, + spotAnglesCos = zlights.spot.anglesCos, + spotExponents = zlights.spot.exponents, - globject.opaque = material; - globject.transparent = null; + hemiSkyColors = zlights.hemi.skyColors, + hemiGroundColors = zlights.hemi.groundColors, + hemiPositions = zlights.hemi.positions, - } + dirLength = 0, + pointLength = 0, + spotLength = 0, + hemiLength = 0, - } + dirCount = 0, + pointCount = 0, + spotCount = 0, + hemiCount = 0, - } + dirOffset = 0, + pointOffset = 0, + spotOffset = 0, + hemiOffset = 0; - }; + for ( l = 0, ll = lights.length; l < ll; l ++ ) { - // Objects refresh + light = lights[ l ]; - this.initWebGLObjects = function ( scene ) { + if ( light.onlyShadow ) continue; - if ( !scene.__webglObjects ) { + color = light.color; + intensity = light.intensity; + distance = light.distance; - scene.__webglObjects = []; - scene.__webglObjectsImmediate = []; - scene.__webglSprites = []; - scene.__webglFlares = []; + if ( light instanceof THREE.AmbientLight ) { - } + if ( ! light.visible ) continue; - while ( scene.__objectsAdded.length ) { + if ( _this.gammaInput ) { - addObject( scene.__objectsAdded[ 0 ], scene ); - scene.__objectsAdded.splice( 0, 1 ); + r += color.r * color.r; + g += color.g * color.g; + b += color.b * color.b; - } + } else { - while ( scene.__objectsRemoved.length ) { + r += color.r; + g += color.g; + b += color.b; - removeObject( scene.__objectsRemoved[ 0 ], scene ); - scene.__objectsRemoved.splice( 0, 1 ); + } - } + } else if ( light instanceof THREE.DirectionalLight ) { + + dirCount += 1; + + if ( ! light.visible ) continue; - // update must be called after objects adding / removal + _direction.setFromMatrixPosition( light.matrixWorld ); + _vector3.setFromMatrixPosition( light.target.matrixWorld ); + _direction.sub( _vector3 ); + _direction.normalize(); - for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) { + dirOffset = dirLength * 3; - var object = scene.__webglObjects[ o ].object; + dirPositions[ dirOffset ] = _direction.x; + dirPositions[ dirOffset + 1 ] = _direction.y; + dirPositions[ dirOffset + 2 ] = _direction.z; - // TODO: Remove this hack (WebGLRenderer refactoring) + if ( _this.gammaInput ) { - if ( object.__webglInit === undefined ) { + setColorGamma( dirColors, dirOffset, color, intensity * intensity ); - if ( object.__webglActive !== undefined ) { + } else { - removeObject( object, scene ); + setColorLinear( dirColors, dirOffset, color, intensity ); } - addObject( object, scene ); + dirLength += 1; - } + } else if ( light instanceof THREE.PointLight ) { - updateObject( object ); + pointCount += 1; - } + if ( ! light.visible ) continue; - }; + pointOffset = pointLength * 3; - // Objects adding + if ( _this.gammaInput ) { - function addObject( object, scene ) { + setColorGamma( pointColors, pointOffset, color, intensity * intensity ); - var g, geometry, material, geometryGroup; + } else { - if ( object.__webglInit === undefined ) { + setColorLinear( pointColors, pointOffset, color, intensity ); - object.__webglInit = true; + } - object._modelViewMatrix = new THREE.Matrix4(); - object._normalMatrix = new THREE.Matrix3(); + _vector3.setFromMatrixPosition( light.matrixWorld ); - geometry = object.geometry; + pointPositions[ pointOffset ] = _vector3.x; + pointPositions[ pointOffset + 1 ] = _vector3.y; + pointPositions[ pointOffset + 2 ] = _vector3.z; - if ( geometry === undefined ) { + pointDistances[ pointLength ] = distance; - // ImmediateRenderObject + pointLength += 1; - } else if ( geometry.__webglInit === undefined ) { + } else if ( light instanceof THREE.SpotLight ) { - geometry.__webglInit = true; - geometry.addEventListener( 'dispose', onGeometryDispose ); + spotCount += 1; - if ( geometry instanceof THREE.BufferGeometry ) { + if ( ! light.visible ) continue; - initDirectBuffers( geometry ); + spotOffset = spotLength * 3; - } else if ( object instanceof THREE.Mesh ) { + if ( _this.gammaInput ) { - material = object.material; + setColorGamma( spotColors, spotOffset, color, intensity * intensity ); - if ( geometry.geometryGroups === undefined ) { + } else { - geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 ); + setColorLinear( spotColors, spotOffset, color, intensity ); - } + } - // create separate VBOs per geometry chunk + _vector3.setFromMatrixPosition( light.matrixWorld ); - for ( g in geometry.geometryGroups ) { + spotPositions[ spotOffset ] = _vector3.x; + spotPositions[ spotOffset + 1 ] = _vector3.y; + spotPositions[ spotOffset + 2 ] = _vector3.z; - geometryGroup = geometry.geometryGroups[ g ]; + spotDistances[ spotLength ] = distance; - // initialise VBO on the first access + _direction.copy( _vector3 ); + _vector3.setFromMatrixPosition( light.target.matrixWorld ); + _direction.sub( _vector3 ); + _direction.normalize(); - if ( ! geometryGroup.__webglVertexBuffer ) { + spotDirections[ spotOffset ] = _direction.x; + spotDirections[ spotOffset + 1 ] = _direction.y; + spotDirections[ spotOffset + 2 ] = _direction.z; - createMeshBuffers( geometryGroup ); - initMeshBuffers( geometryGroup, object ); + spotAnglesCos[ spotLength ] = Math.cos( light.angle ); + spotExponents[ spotLength ] = light.exponent; - geometry.verticesNeedUpdate = true; - geometry.morphTargetsNeedUpdate = true; - geometry.elementsNeedUpdate = true; - geometry.uvsNeedUpdate = true; - geometry.normalsNeedUpdate = true; - geometry.tangentsNeedUpdate = true; - geometry.colorsNeedUpdate = true; + spotLength += 1; - } + } else if ( light instanceof THREE.HemisphereLight ) { - } + hemiCount += 1; - } else if ( object instanceof THREE.Line ) { + if ( ! light.visible ) continue; - if ( ! geometry.__webglVertexBuffer ) { + _direction.setFromMatrixPosition( light.matrixWorld ); + _direction.normalize(); - createLineBuffers( geometry ); - initLineBuffers( geometry, object ); + hemiOffset = hemiLength * 3; - geometry.verticesNeedUpdate = true; - geometry.colorsNeedUpdate = true; - geometry.lineDistancesNeedUpdate = true; + hemiPositions[ hemiOffset ] = _direction.x; + hemiPositions[ hemiOffset + 1 ] = _direction.y; + hemiPositions[ hemiOffset + 2 ] = _direction.z; - } + skyColor = light.color; + groundColor = light.groundColor; - } else if ( object instanceof THREE.ParticleSystem ) { + if ( _this.gammaInput ) { - if ( ! geometry.__webglVertexBuffer ) { + intensitySq = intensity * intensity; - createParticleBuffers( geometry ); - initParticleBuffers( geometry, object ); + setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq ); + setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq ); - geometry.verticesNeedUpdate = true; - geometry.colorsNeedUpdate = true; + } else { - } + setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity ); + setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity ); } + hemiLength += 1; + } } - if ( object.__webglActive === undefined ) { - - if ( object instanceof THREE.Mesh ) { - - geometry = object.geometry; - - if ( geometry instanceof THREE.BufferGeometry ) { - - addBuffer( scene.__webglObjects, geometry, object ); - - } else if ( geometry instanceof THREE.Geometry ) { + // null eventual remains from removed lights + // (this is to avoid if in shader) - for ( g in geometry.geometryGroups ) { + for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0; + for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0; + for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0; + for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0; + for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0; - geometryGroup = geometry.geometryGroups[ g ]; + zlights.directional.length = dirLength; + zlights.point.length = pointLength; + zlights.spot.length = spotLength; + zlights.hemi.length = hemiLength; - addBuffer( scene.__webglObjects, geometryGroup, object ); + zlights.ambient[ 0 ] = r; + zlights.ambient[ 1 ] = g; + zlights.ambient[ 2 ] = b; - } + }; - } + // GL state setting - } else if ( object instanceof THREE.Line || - object instanceof THREE.ParticleSystem ) { + this.setFaceCulling = function ( cullFace, frontFaceDirection ) { - geometry = object.geometry; - addBuffer( scene.__webglObjects, geometry, object ); + if ( cullFace === THREE.CullFaceNone ) { - } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { + _gl.disable( _gl.CULL_FACE ); - addBufferImmediate( scene.__webglObjectsImmediate, object ); + } else { - } else if ( object instanceof THREE.Sprite ) { + if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) { - scene.__webglSprites.push( object ); + _gl.frontFace( _gl.CW ); - } else if ( object instanceof THREE.LensFlare ) { + } else { - scene.__webglFlares.push( object ); + _gl.frontFace( _gl.CCW ); } - object.__webglActive = true; - - } + if ( cullFace === THREE.CullFaceBack ) { - }; + _gl.cullFace( _gl.BACK ); - function addBuffer( objlist, buffer, object ) { + } else if ( cullFace === THREE.CullFaceFront ) { - objlist.push( - { - id: null, - buffer: buffer, - object: object, - opaque: null, - transparent: null, - z: 0 - } - ); + _gl.cullFace( _gl.FRONT ); - }; + } else { - function addBufferImmediate( objlist, object ) { + _gl.cullFace( _gl.FRONT_AND_BACK ); - objlist.push( - { - id: null, - object: object, - opaque: null, - transparent: null, - z: 0 } - ); - }; + _gl.enable( _gl.CULL_FACE ); - // Objects updates + } - function updateObject( object ) { + }; - var geometry = object.geometry, - geometryGroup, customAttributesDirty, material; + this.setMaterialFaces = function ( material ) { - if ( geometry instanceof THREE.BufferGeometry ) { + var doubleSided = material.side === THREE.DoubleSide; + var flipSided = material.side === THREE.BackSide; - setDirectBuffers( geometry, _gl.DYNAMIC_DRAW ); + if ( _oldDoubleSided !== doubleSided ) { - } else if ( object instanceof THREE.Mesh ) { + if ( doubleSided ) { - // check all geometry groups + _gl.disable( _gl.CULL_FACE ); - for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) { + } else { - geometryGroup = geometry.geometryGroupsList[ i ]; + _gl.enable( _gl.CULL_FACE ); - material = getBufferMaterial( object, geometryGroup ); + } - if ( geometry.buffersNeedUpdate ) { + _oldDoubleSided = doubleSided; - initMeshBuffers( geometryGroup, object ); + } - } + if ( _oldFlipSided !== flipSided ) { - customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); + if ( flipSided ) { - if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate || - geometry.uvsNeedUpdate || geometry.normalsNeedUpdate || - geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) { + _gl.frontFace( _gl.CW ); - setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material ); + } else { - } + _gl.frontFace( _gl.CCW ); } - geometry.verticesNeedUpdate = false; - geometry.morphTargetsNeedUpdate = false; - geometry.elementsNeedUpdate = false; - geometry.uvsNeedUpdate = false; - geometry.normalsNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.tangentsNeedUpdate = false; + _oldFlipSided = flipSided; - geometry.buffersNeedUpdate = false; + } - material.attributes && clearCustomAttributes( material ); + }; - } else if ( object instanceof THREE.Line ) { + this.setDepthTest = function ( depthTest ) { - material = getBufferMaterial( object, geometry ); + if ( _oldDepthTest !== depthTest ) { - customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); + if ( depthTest ) { - if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) { + _gl.enable( _gl.DEPTH_TEST ); - setLineBuffers( geometry, _gl.DYNAMIC_DRAW ); + } else { + + _gl.disable( _gl.DEPTH_TEST ); } - geometry.verticesNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.lineDistancesNeedUpdate = false; + _oldDepthTest = depthTest; - material.attributes && clearCustomAttributes( material ); + } + }; - } else if ( object instanceof THREE.ParticleSystem ) { + this.setDepthWrite = function ( depthWrite ) { - material = getBufferMaterial( object, geometry ); + if ( _oldDepthWrite !== depthWrite ) { - customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); + _gl.depthMask( depthWrite ); + _oldDepthWrite = depthWrite; - if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) { + } - setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object ); + }; - } + function setLineWidth ( width ) { - geometry.verticesNeedUpdate = false; - geometry.colorsNeedUpdate = false; + if ( width !== _oldLineWidth ) { - material.attributes && clearCustomAttributes( material ); + _gl.lineWidth( width ); + + _oldLineWidth = width; } }; - // Objects updates - custom attributes check - - function areCustomAttributesDirty( material ) { - - for ( var a in material.attributes ) { + function setPolygonOffset ( polygonoffset, factor, units ) { - if ( material.attributes[ a ].needsUpdate ) return true; + if ( _oldPolygonOffset !== polygonoffset ) { - } + if ( polygonoffset ) { - return false; + _gl.enable( _gl.POLYGON_OFFSET_FILL ); - }; + } else { - function clearCustomAttributes( material ) { + _gl.disable( _gl.POLYGON_OFFSET_FILL ); - for ( var a in material.attributes ) { + } - material.attributes[ a ].needsUpdate = false; + _oldPolygonOffset = polygonoffset; } - }; + if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) { - // Objects removal + _gl.polygonOffset( factor, units ); - function removeObject( object, scene ) { + _oldPolygonOffsetFactor = factor; + _oldPolygonOffsetUnits = units; - if ( object instanceof THREE.Mesh || - object instanceof THREE.ParticleSystem || - object instanceof THREE.Line ) { + } - removeInstances( scene.__webglObjects, object ); + }; - } else if ( object instanceof THREE.Sprite ) { + this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) { - removeInstancesDirect( scene.__webglSprites, object ); + if ( blending !== _oldBlending ) { - } else if ( object instanceof THREE.LensFlare ) { + if ( blending === THREE.NoBlending ) { - removeInstancesDirect( scene.__webglFlares, object ); + _gl.disable( _gl.BLEND ); - } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { + } else if ( blending === THREE.AdditiveBlending ) { - removeInstances( scene.__webglObjectsImmediate, object ); + _gl.enable( _gl.BLEND ); + _gl.blendEquation( _gl.FUNC_ADD ); + _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE ); - } + } else if ( blending === THREE.SubtractiveBlending ) { - delete object.__webglActive; + // TODO: Find blendFuncSeparate() combination + _gl.enable( _gl.BLEND ); + _gl.blendEquation( _gl.FUNC_ADD ); + _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR ); - }; + } else if ( blending === THREE.MultiplyBlending ) { - function removeInstances( objlist, object ) { + // TODO: Find blendFuncSeparate() combination + _gl.enable( _gl.BLEND ); + _gl.blendEquation( _gl.FUNC_ADD ); + _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR ); - for ( var o = objlist.length - 1; o >= 0; o -- ) { + } else if ( blending === THREE.CustomBlending ) { - if ( objlist[ o ].object === object ) { + _gl.enable( _gl.BLEND ); - objlist.splice( o, 1 ); + } else { + + _gl.enable( _gl.BLEND ); + _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD ); + _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA ); } - } + _oldBlending = blending; - }; + } - function removeInstancesDirect( objlist, object ) { + if ( blending === THREE.CustomBlending ) { - for ( var o = objlist.length - 1; o >= 0; o -- ) { + if ( blendEquation !== _oldBlendEquation ) { - if ( objlist[ o ] === object ) { + _gl.blendEquation( paramThreeToGL( blendEquation ) ); - objlist.splice( o, 1 ); + _oldBlendEquation = blendEquation; } - } - - }; + if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) { - // Materials + _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) ); - this.initMaterial = function ( material, lights, fog, object ) { + _oldBlendSrc = blendSrc; + _oldBlendDst = blendDst; - material.addEventListener( 'dispose', onMaterialDispose ); + } - var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID; + } else { - if ( material instanceof THREE.MeshDepthMaterial ) { + _oldBlendEquation = null; + _oldBlendSrc = null; + _oldBlendDst = null; - shaderID = 'depth'; + } - } else if ( material instanceof THREE.MeshNormalMaterial ) { + }; - shaderID = 'normal'; + // Textures - } else if ( material instanceof THREE.MeshBasicMaterial ) { + function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) { - shaderID = 'basic'; + if ( isImagePowerOfTwo ) { - } else if ( material instanceof THREE.MeshLambertMaterial ) { + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); - shaderID = 'lambert'; + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); - } else if ( material instanceof THREE.MeshPhongMaterial ) { + } else { - shaderID = 'phong'; + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - } else if ( material instanceof THREE.LineBasicMaterial ) { + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); - shaderID = 'basic'; + } - } else if ( material instanceof THREE.LineDashedMaterial ) { + if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) { - shaderID = 'dashed'; + if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) { - } else if ( material instanceof THREE.ParticleSystemMaterial ) { + _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) ); + texture.__oldAnisotropy = texture.anisotropy; - shaderID = 'particle_basic'; + } } - if ( shaderID ) { - - setMaterialShaders( material, THREE.ShaderLib[ shaderID ] ); - - } + }; - // heuristics to create shader parameters according to lights in the scene - // (not to blow over maxLights budget) + this.setTexture = function ( texture, slot ) { - maxLightCount = allocateLights( lights ); + if ( texture.needsUpdate ) { - maxShadows = allocateShadows( lights ); + if ( ! texture.__webglInit ) { - maxBones = allocateBones( object ); + texture.__webglInit = true; - parameters = { + texture.addEventListener( 'dispose', onTextureDispose ); - precision: _precision, - supportsVertexTextures: _supportsVertexTextures, + texture.__webglTexture = _gl.createTexture(); - map: !!material.map, - envMap: !!material.envMap, - lightMap: !!material.lightMap, - bumpMap: !!material.bumpMap, - normalMap: !!material.normalMap, - specularMap: !!material.specularMap, + _this.info.memory.textures ++; - vertexColors: material.vertexColors, + } - fog: fog, - useFog: material.fog, - fogExp: fog instanceof THREE.FogExp2, + _gl.activeTexture( _gl.TEXTURE0 + slot ); + _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); - sizeAttenuation: material.sizeAttenuation, - logarithmicDepthBuffer: _logarithmicDepthBuffer, + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); - skinning: material.skinning, - maxBones: maxBones, - useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture, + var image = texture.image, + isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - morphTargets: material.morphTargets, - morphNormals: material.morphNormals, - maxMorphTargets: this.maxMorphTargets, - maxMorphNormals: this.maxMorphNormals, + setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo ); - maxDirLights: maxLightCount.directional, - maxPointLights: maxLightCount.point, - maxSpotLights: maxLightCount.spot, - maxHemiLights: maxLightCount.hemi, + var mipmap, mipmaps = texture.mipmaps; - maxShadows: maxShadows, - shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0, - shadowMapType: this.shadowMapType, - shadowMapDebug: this.shadowMapDebug, - shadowMapCascade: this.shadowMapCascade, + if ( texture instanceof THREE.DataTexture ) { - alphaTest: material.alphaTest, - metal: material.metal, - wrapAround: material.wrapAround, - doubleSided: material.side === THREE.DoubleSide, - flipSided: material.side === THREE.BackSide + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - }; + if ( mipmaps.length > 0 && isImagePowerOfTwo ) { - // Generate code + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - var chunks = []; + mipmap = mipmaps[ i ]; + _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - if ( shaderID ) { + } - chunks.push( shaderID ); + texture.generateMipmaps = false; - } else { + } else { - chunks.push( material.fragmentShader ); - chunks.push( material.vertexShader ); + _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); - } + } - for ( var d in material.defines ) { + } else if ( texture instanceof THREE.CompressedTexture ) { - chunks.push( d ); - chunks.push( material.defines[ d ] ); + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - } + mipmap = mipmaps[ i ]; + if ( texture.format !== THREE.RGBAFormat ) { + _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + } else { + _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + } - for ( var p in parameters ) { + } - chunks.push( p ); - chunks.push( parameters[ p ] ); + } else { // regular Texture (image, video, canvas) - } + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - var code = chunks.join(); + if ( mipmaps.length > 0 && isImagePowerOfTwo ) { - var program; + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - // Check if code has been already compiled + mipmap = mipmaps[ i ]; + _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); - for ( var p = 0, pl = _programs.length; p < pl; p ++ ) { + } - var programInfo = _programs[ p ]; + texture.generateMipmaps = false; - if ( programInfo.code === code ) { + } else { - program = programInfo; - program.usedTimes ++; + _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image ); - break; + } } - } + if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); - if ( program === undefined ) { + texture.needsUpdate = false; - program = new THREE.WebGLProgram( this, code, material, parameters ); - _programs.push( program ); + if ( texture.onUpdate ) texture.onUpdate(); - _this.info.memory.programs = _programs.length; + } else { + + _gl.activeTexture( _gl.TEXTURE0 + slot ); + _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); } - material.program = program; + }; - var attributes = material.program.attributes; + function clampToMaxSize ( image, maxSize ) { - if ( material.morphTargets ) { + if ( image.width <= maxSize && image.height <= maxSize ) { - material.numSupportedMorphTargets = 0; + return image; - var id, base = "morphTarget"; + } - for ( i = 0; i < this.maxMorphTargets; i ++ ) { + // Warning: Scaling through the canvas will only work with images that use + // premultiplied alpha. - id = base + i; + var maxDimension = Math.max( image.width, image.height ); + var newWidth = Math.floor( image.width * maxSize / maxDimension ); + var newHeight = Math.floor( image.height * maxSize / maxDimension ); - if ( attributes[ id ] >= 0 ) { + var canvas = document.createElement( 'canvas' ); + canvas.width = newWidth; + canvas.height = newHeight; - material.numSupportedMorphTargets ++; + var ctx = canvas.getContext( '2d' ); + ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight ); - } + return canvas; - } + } - } + function setCubeTexture ( texture, slot ) { - if ( material.morphNormals ) { + if ( texture.image.length === 6 ) { - material.numSupportedMorphNormals = 0; + if ( texture.needsUpdate ) { - var id, base = "morphNormal"; + if ( ! texture.image.__webglTextureCube ) { - for ( i = 0; i < this.maxMorphNormals; i ++ ) { + texture.addEventListener( 'dispose', onTextureDispose ); - id = base + i; - - if ( attributes[ id ] >= 0 ) { + texture.image.__webglTextureCube = _gl.createTexture(); - material.numSupportedMorphNormals ++; + _this.info.memory.textures ++; } - } + _gl.activeTexture( _gl.TEXTURE0 + slot ); + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); - } + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - material.uniformsList = []; + var isCompressed = texture instanceof THREE.CompressedTexture; - for ( u in material.uniforms ) { + var cubeImage = []; - material.uniformsList.push( [ material.uniforms[ u ], u ] ); + for ( var i = 0; i < 6; i ++ ) { - } + if ( _this.autoScaleCubemaps && ! isCompressed ) { - }; + cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize ); - function setMaterialShaders( material, shaders ) { + } else { - material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms ); - material.vertexShader = shaders.vertexShader; - material.fragmentShader = shaders.fragmentShader; + cubeImage[ i ] = texture.image[ i ]; - }; + } - function setProgram( camera, lights, fog, material, object ) { + } - _usedTextureUnits = 0; + var image = cubeImage[ 0 ], + isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - if ( material.needsUpdate ) { + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo ); - if ( material.program ) deallocateMaterial( material ); + for ( var i = 0; i < 6; i ++ ) { - _this.initMaterial( material, lights, fog, object ); - material.needsUpdate = false; + if ( ! isCompressed ) { - } + _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); - if ( material.morphTargets ) { + } else { - if ( ! object.__webglMorphTargetInfluences ) { + var mipmap, mipmaps = cubeImage[ i ].mipmaps; - object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets ); + for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { - } + mipmap = mipmaps[ j ]; + if ( texture.format !== THREE.RGBAFormat ) { - } + _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - var refreshMaterial = false; + } else { + _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + } - var program = material.program, - p_uniforms = program.uniforms, - m_uniforms = material.uniforms; + } + } + } - if ( program.id !== _currentProgram ) { + if ( texture.generateMipmaps && isImagePowerOfTwo ) { - _gl.useProgram( program.program ); - _currentProgram = program.id; + _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - refreshMaterial = true; + } - } + texture.needsUpdate = false; - if ( material.id !== _currentMaterialId ) { + if ( texture.onUpdate ) texture.onUpdate(); - _currentMaterialId = material.id; - refreshMaterial = true; + } else { + + _gl.activeTexture( _gl.TEXTURE0 + slot ); + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); + + } } - if ( refreshMaterial || camera !== _currentCamera ) { + }; - _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); + function setCubeTextureDynamic ( texture, slot ) { - if ( _logarithmicDepthBuffer ) { + _gl.activeTexture( _gl.TEXTURE0 + slot ); + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture ); - _gl.uniform1f(p_uniforms.logDepthBufFC, 2.0 / (Math.log(camera.far + 1.0) / Math.LN2)); + }; - } + // Render targets + function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) { - if ( camera !== _currentCamera ) _currentCamera = camera; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 ); - } + }; - // skinning uniforms must be set even if material didn't change - // auto-setting of texture unit for bone texture must go before other textures - // not sure why, but otherwise weird things happen + function setupRenderBuffer ( renderbuffer, renderTarget ) { - if ( material.skinning ) { + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); - if ( _supportsBoneTextures && object.skeleton.useVertexTexture ) { + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - if ( p_uniforms.boneTexture !== null ) { + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - var textureUnit = getTextureUnit(); + /* For some reason this is not working. Defaulting to RGBA4. + } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - _gl.uniform1i( p_uniforms.boneTexture, textureUnit ); - _this.setTexture( object.skeleton.boneTexture, textureUnit ); + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + */ + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - } + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - if ( p_uniforms.boneTextureWidth !== null ) { + } else { - _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth ); + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); - } + } - if ( p_uniforms.boneTextureHeight !== null ) { + }; - _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight ); + this.setRenderTarget = function ( renderTarget ) { - } + var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); - } else { + if ( renderTarget && ! renderTarget.__webglFramebuffer ) { - if ( p_uniforms.boneGlobalMatrices !== null ) { + if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true; + if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true; - _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices ); + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - } + renderTarget.__webglTexture = _gl.createTexture(); - } + _this.info.memory.textures ++; - } + // Setup texture, create render and frame buffers - if ( refreshMaterial ) { + var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ), + glFormat = paramThreeToGL( renderTarget.format ), + glType = paramThreeToGL( renderTarget.type ); - // refresh uniforms common to several materials + if ( isCube ) { - if ( fog && material.fog ) { + renderTarget.__webglFramebuffer = []; + renderTarget.__webglRenderbuffer = []; - refreshUniformsFog( m_uniforms, fog ); + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo ); - } + for ( var i = 0; i < 6; i ++ ) { - if ( material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshLambertMaterial || - material.lights ) { + renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer(); - if ( _lightsNeedUpdate ) { + _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - setupLights( program, lights ); - _lightsNeedUpdate = false; + setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); + setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget ); } - refreshUniformsLights( m_uniforms, _lights ); + if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - } + } else { - if ( material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshPhongMaterial ) { + renderTarget.__webglFramebuffer = _gl.createFramebuffer(); - refreshUniformsCommon( m_uniforms, material ); + if ( renderTarget.shareDepthFrom ) { - } + renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer; - // refresh single material specific uniforms + } else { - if ( material instanceof THREE.LineBasicMaterial ) { + renderTarget.__webglRenderbuffer = _gl.createRenderbuffer(); - refreshUniformsLine( m_uniforms, material ); + } - } else if ( material instanceof THREE.LineDashedMaterial ) { + _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); + setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo ); - refreshUniformsLine( m_uniforms, material ); - refreshUniformsDash( m_uniforms, material ); + _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - } else if ( material instanceof THREE.ParticleSystemMaterial ) { + setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D ); - refreshUniformsParticle( m_uniforms, material ); + if ( renderTarget.shareDepthFrom ) { - } else if ( material instanceof THREE.MeshPhongMaterial ) { + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - refreshUniformsPhong( m_uniforms, material ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); - } else if ( material instanceof THREE.MeshLambertMaterial ) { + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - refreshUniformsLambert( m_uniforms, material ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); - } else if ( material instanceof THREE.MeshDepthMaterial ) { + } - m_uniforms.mNear.value = camera.near; - m_uniforms.mFar.value = camera.far; - m_uniforms.opacity.value = material.opacity; + } else { - } else if ( material instanceof THREE.MeshNormalMaterial ) { + setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget ); - m_uniforms.opacity.value = material.opacity; + } - } + if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); - if ( object.receiveShadow && ! material._shadowPass ) { + } - refreshUniformsShadow( m_uniforms, lights ); + // Release everything - } + if ( isCube ) { - // load common uniforms + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); - loadUniformsGeneric( program, material.uniformsList ); + } else { - // load material specific uniforms - // (shader material also gets them for the sake of genericity) + _gl.bindTexture( _gl.TEXTURE_2D, null ); - if ( material instanceof THREE.ShaderMaterial || - material instanceof THREE.MeshPhongMaterial || - material.envMap ) { + } - if ( p_uniforms.cameraPosition !== null ) { + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - _vector3.setFromMatrixPosition( camera.matrixWorld ); - _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z ); + } - } + var framebuffer, width, height, vx, vy; - } + if ( renderTarget ) { - if ( material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.ShaderMaterial || - material.skinning ) { + if ( isCube ) { - if ( p_uniforms.viewMatrix !== null ) { + framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ]; - _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements ); + } else { - } + framebuffer = renderTarget.__webglFramebuffer; } - } + width = renderTarget.width; + height = renderTarget.height; - loadUniformsMatrices( p_uniforms, object ); + vx = 0; + vy = 0; - if ( p_uniforms.modelMatrix !== null ) { + } else { - _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements ); + framebuffer = null; - } + width = _viewportWidth; + height = _viewportHeight; - return program; + vx = _viewportX; + vy = _viewportY; - }; + } - // Uniforms (refresh uniforms objects) + if ( framebuffer !== _currentFramebuffer ) { - function refreshUniformsCommon ( uniforms, material ) { + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _gl.viewport( vx, vy, width, height ); - uniforms.opacity.value = material.opacity; + _currentFramebuffer = framebuffer; - if ( _this.gammaInput ) { + } - uniforms.diffuse.value.copyGammaToLinear( material.color ); + _currentWidth = width; + _currentHeight = height; - } else { + }; - uniforms.diffuse.value = material.color; + function updateRenderTargetMipmap ( renderTarget ) { - } + if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { - uniforms.map.value = material.map; - uniforms.lightMap.value = material.lightMap; - uniforms.specularMap.value = material.specularMap; + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); + _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); - if ( material.bumpMap ) { + } else { - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); + _gl.generateMipmap( _gl.TEXTURE_2D ); + _gl.bindTexture( _gl.TEXTURE_2D, null ); } - if ( material.normalMap ) { - - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - - } + }; - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. normal map - // 4. bump map + // Fallback filters for non-power-of-2 textures - var uvScaleMap; + function filterFallback ( f ) { - if ( material.map ) { + if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) { - uvScaleMap = material.map; + return _gl.NEAREST; - } else if ( material.specularMap ) { + } - uvScaleMap = material.specularMap; + return _gl.LINEAR; - } else if ( material.normalMap ) { + }; - uvScaleMap = material.normalMap; + // Map three.js constants to WebGL constants - } else if ( material.bumpMap ) { + function paramThreeToGL ( p ) { - uvScaleMap = material.bumpMap; + if ( p === THREE.RepeatWrapping ) return _gl.REPEAT; + if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; + if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; - } + if ( p === THREE.NearestFilter ) return _gl.NEAREST; + if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; + if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; - if ( uvScaleMap !== undefined ) { + if ( p === THREE.LinearFilter ) return _gl.LINEAR; + if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; + if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; - var offset = uvScaleMap.offset; - var repeat = uvScaleMap.repeat; + if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE; + if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; + if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; + if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + if ( p === THREE.ByteType ) return _gl.BYTE; + if ( p === THREE.ShortType ) return _gl.SHORT; + if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT; + if ( p === THREE.IntType ) return _gl.INT; + if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT; + if ( p === THREE.FloatType ) return _gl.FLOAT; - } + if ( p === THREE.AlphaFormat ) return _gl.ALPHA; + if ( p === THREE.RGBFormat ) return _gl.RGB; + if ( p === THREE.RGBAFormat ) return _gl.RGBA; + if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE; + if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; - uniforms.envMap.value = material.envMap; - uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1; + if ( p === THREE.AddEquation ) return _gl.FUNC_ADD; + if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT; + if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; - if ( _this.gammaInput ) { + if ( p === THREE.ZeroFactor ) return _gl.ZERO; + if ( p === THREE.OneFactor ) return _gl.ONE; + if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR; + if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; + if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA; + if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; + if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA; + if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; - //uniforms.reflectivity.value = material.reflectivity * material.reflectivity; - uniforms.reflectivity.value = material.reflectivity; + if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR; + if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; + if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; - } else { + if ( _glExtensionCompressedTextureS3TC !== undefined ) { - uniforms.reflectivity.value = material.reflectivity; + if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT; } - uniforms.refractionRatio.value = material.refractionRatio; - uniforms.combine.value = material.combine; - uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping; + return 0; }; - function refreshUniformsLine ( uniforms, material ) { - - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; + // Allocations - }; + function allocateBones ( object ) { - function refreshUniformsDash ( uniforms, material ) { + if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; + return 1024; - }; + } else { - function refreshUniformsParticle ( uniforms, material ) { + // default for when object is not specified + // ( for example when prebuilding shader + // to be used with multiple objects ) + // + // - leave some extra space for other uniforms + // - limit here is ANGLE's 254 max uniform vectors + // (up to 54 should be safe) - uniforms.psColor.value = material.color; - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size; - uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this. + var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ); + var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); - uniforms.map.value = material.map; + var maxBones = nVertexMatrices; - }; + if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { - function refreshUniformsFog ( uniforms, fog ) { + maxBones = Math.min( object.skeleton.bones.length, maxBones ); - uniforms.fogColor.value = fog.color; + if ( maxBones < object.skeleton.bones.length ) { - if ( fog instanceof THREE.Fog ) { + console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; + } - } else if ( fog instanceof THREE.FogExp2 ) { + } - uniforms.fogDensity.value = fog.density; + return maxBones; } }; - function refreshUniformsPhong ( uniforms, material ) { + function allocateLights( lights ) { - uniforms.shininess.value = material.shininess; + var dirLights = 0; + var pointLights = 0; + var spotLights = 0; + var hemiLights = 0; - if ( _this.gammaInput ) { + for ( var l = 0, ll = lights.length; l < ll; l ++ ) { - uniforms.ambient.value.copyGammaToLinear( material.ambient ); - uniforms.emissive.value.copyGammaToLinear( material.emissive ); - uniforms.specular.value.copyGammaToLinear( material.specular ); + var light = lights[ l ]; - } else { + if ( light.onlyShadow || light.visible === false ) continue; - uniforms.ambient.value = material.ambient; - uniforms.emissive.value = material.emissive; - uniforms.specular.value = material.specular; + if ( light instanceof THREE.DirectionalLight ) dirLights ++; + if ( light instanceof THREE.PointLight ) pointLights ++; + if ( light instanceof THREE.SpotLight ) spotLights ++; + if ( light instanceof THREE.HemisphereLight ) hemiLights ++; } - if ( material.wrapAround ) { - - uniforms.wrapRGB.value.copy( material.wrapRGB ); - - } + return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights }; }; - function refreshUniformsLambert ( uniforms, material ) { - - if ( _this.gammaInput ) { - - uniforms.ambient.value.copyGammaToLinear( material.ambient ); - uniforms.emissive.value.copyGammaToLinear( material.emissive ); + function allocateShadows( lights ) { - } else { + var maxShadows = 0; - uniforms.ambient.value = material.ambient; - uniforms.emissive.value = material.emissive; + for ( var l = 0, ll = lights.length; l < ll; l ++ ) { - } + var light = lights[ l ]; - if ( material.wrapAround ) { + if ( ! light.castShadow ) continue; - uniforms.wrapRGB.value.copy( material.wrapRGB ); + if ( light instanceof THREE.SpotLight ) maxShadows ++; + if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++; } + return maxShadows; + }; - function refreshUniformsLights ( uniforms, lights ) { + // Initialization - uniforms.ambientLightColor.value = lights.ambient; + function initGL() { - uniforms.directionalLightColor.value = lights.directional.colors; - uniforms.directionalLightDirection.value = lights.directional.positions; + try { - uniforms.pointLightColor.value = lights.point.colors; - uniforms.pointLightPosition.value = lights.point.positions; - uniforms.pointLightDistance.value = lights.point.distances; + var attributes = { + alpha: _alpha, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer + }; - uniforms.spotLightColor.value = lights.spot.colors; - uniforms.spotLightPosition.value = lights.spot.positions; - uniforms.spotLightDistance.value = lights.spot.distances; - uniforms.spotLightDirection.value = lights.spot.directions; - uniforms.spotLightAngleCos.value = lights.spot.anglesCos; - uniforms.spotLightExponent.value = lights.spot.exponents; + _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); - uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors; - uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors; - uniforms.hemisphereLightDirection.value = lights.hemi.positions; + if ( _gl === null ) { - }; + throw 'Error creating WebGL context.'; - function refreshUniformsShadow ( uniforms, lights ) { + } - if ( uniforms.shadowMatrix ) { + } catch ( error ) { - var j = 0; + console.error( error ); - for ( var i = 0, il = lights.length; i < il; i ++ ) { + } - var light = lights[ i ]; - - if ( ! light.castShadow ) continue; - - if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) { + _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' ); + _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' ); + _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' ); - uniforms.shadowMap.value[ j ] = light.shadowMap; - uniforms.shadowMapSize.value[ j ] = light.shadowMapSize; + _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); - uniforms.shadowMatrix.value[ j ] = light.shadowMatrix; + _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); - uniforms.shadowDarkness.value[ j ] = light.shadowDarkness; - uniforms.shadowBias.value[ j ] = light.shadowBias; + _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' ); - j ++; - } + if ( _glExtensionTextureFloat === null ) { - } + console.log( 'THREE.WebGLRenderer: Float textures not supported.' ); } - }; - - // Uniforms (load to GPU) + if ( _glExtensionStandardDerivatives === null ) { - function loadUniformsMatrices ( uniforms, object ) { + console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' ); - _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements ); + } - if ( uniforms.normalMatrix ) { + if ( _glExtensionTextureFilterAnisotropic === null ) { - _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements ); + console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' ); } - }; + if ( _glExtensionCompressedTextureS3TC === null ) { - function getTextureUnit() { + console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' ); - var textureUnit = _usedTextureUnits; + } - if ( textureUnit >= _maxTextures ) { + if ( _glExtensionElementIndexUint === null ) { - console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures ); + console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' ); } - _usedTextureUnits += 1; - - return textureUnit; + if ( _gl.getShaderPrecisionFormat === undefined ) { - }; + _gl.getShaderPrecisionFormat = function () { - function loadUniformsGeneric ( program, uniforms ) { + return { + 'rangeMin': 1, + 'rangeMax': 1, + 'precision': 1 + }; - var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset; + } + } - for ( j = 0, jl = uniforms.length; j < jl; j ++ ) { + if ( _logarithmicDepthBuffer ) { - location = program.uniforms[ uniforms[ j ][ 1 ] ]; - if ( !location ) continue; + _glExtensionFragDepth = _gl.getExtension( 'EXT_frag_depth' ); - uniform = uniforms[ j ][ 0 ]; + } - type = uniform.type; - value = uniform.value; + }; - if ( type === "i" ) { // single integer + function setDefaultGLState () { - _gl.uniform1i( location, value ); + _gl.clearColor( 0, 0, 0, 1 ); + _gl.clearDepth( 1 ); + _gl.clearStencil( 0 ); - } else if ( type === "f" ) { // single float + _gl.enable( _gl.DEPTH_TEST ); + _gl.depthFunc( _gl.LEQUAL ); - _gl.uniform1f( location, value ); + _gl.frontFace( _gl.CCW ); + _gl.cullFace( _gl.BACK ); + _gl.enable( _gl.CULL_FACE ); - } else if ( type === "v2" ) { // single THREE.Vector2 + _gl.enable( _gl.BLEND ); + _gl.blendEquation( _gl.FUNC_ADD ); + _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA ); - _gl.uniform2f( location, value.x, value.y ); + _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); - } else if ( type === "v3" ) { // single THREE.Vector3 + _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - _gl.uniform3f( location, value.x, value.y, value.z ); + }; - } else if ( type === "v4" ) { // single THREE.Vector4 + // default plugins (order is important) - _gl.uniform4f( location, value.x, value.y, value.z, value.w ); + this.shadowMapPlugin = new THREE.ShadowMapPlugin(); + this.addPrePlugin( this.shadowMapPlugin ); - } else if ( type === "c" ) { // single THREE.Color + this.addPostPlugin( new THREE.SpritePlugin() ); + this.addPostPlugin( new THREE.LensFlarePlugin() ); - _gl.uniform3f( location, value.r, value.g, value.b ); +}; - } else if ( type === "iv1" ) { // flat array of integers (JS or typed array) +// File:src/renderers/WebGLRenderTarget.js - _gl.uniform1iv( location, value ); +/** + * @author szimek / https://github.com/szimek/ + * @author alteredq / http://alteredqualia.com/ + */ - } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array) +THREE.WebGLRenderTarget = function ( width, height, options ) { - _gl.uniform3iv( location, value ); + this.width = width; + this.height = height; - } else if ( type === "fv1" ) { // flat array of floats (JS or typed array) + options = options || {}; - _gl.uniform1fv( location, value ); + this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping; + this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping; - } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array) + this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter; + this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter; - _gl.uniform3fv( location, value ); + this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1; - } else if ( type === "v2v" ) { // array of THREE.Vector2 + this.offset = new THREE.Vector2( 0, 0 ); + this.repeat = new THREE.Vector2( 1, 1 ); - if ( uniform._array === undefined ) { + this.format = options.format !== undefined ? options.format : THREE.RGBAFormat; + this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType; - uniform._array = new Float32Array( 2 * value.length ); + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; - } + this.generateMipmaps = true; - for ( i = 0, il = value.length; i < il; i ++ ) { + this.shareDepthFrom = null; - offset = i * 2; +}; - uniform._array[ offset ] = value[ i ].x; - uniform._array[ offset + 1 ] = value[ i ].y; +THREE.WebGLRenderTarget.prototype = { - } + constructor: THREE.WebGLRenderTarget, - _gl.uniform2fv( location, uniform._array ); + setSize: function ( width, height ) { - } else if ( type === "v3v" ) { // array of THREE.Vector3 + this.width = width; + this.height = height; - if ( uniform._array === undefined ) { + }, - uniform._array = new Float32Array( 3 * value.length ); + clone: function () { - } + var tmp = new THREE.WebGLRenderTarget( this.width, this.height ); - for ( i = 0, il = value.length; i < il; i ++ ) { + tmp.wrapS = this.wrapS; + tmp.wrapT = this.wrapT; - offset = i * 3; + tmp.magFilter = this.magFilter; + tmp.minFilter = this.minFilter; - uniform._array[ offset ] = value[ i ].x; - uniform._array[ offset + 1 ] = value[ i ].y; - uniform._array[ offset + 2 ] = value[ i ].z; + tmp.anisotropy = this.anisotropy; - } + tmp.offset.copy( this.offset ); + tmp.repeat.copy( this.repeat ); - _gl.uniform3fv( location, uniform._array ); + tmp.format = this.format; + tmp.type = this.type; - } else if ( type === "v4v" ) { // array of THREE.Vector4 + tmp.depthBuffer = this.depthBuffer; + tmp.stencilBuffer = this.stencilBuffer; - if ( uniform._array === undefined ) { + tmp.generateMipmaps = this.generateMipmaps; - uniform._array = new Float32Array( 4 * value.length ); + tmp.shareDepthFrom = this.shareDepthFrom; - } + return tmp; - for ( i = 0, il = value.length; i < il; i ++ ) { + }, - offset = i * 4; + dispose: function () { - uniform._array[ offset ] = value[ i ].x; - uniform._array[ offset + 1 ] = value[ i ].y; - uniform._array[ offset + 2 ] = value[ i ].z; - uniform._array[ offset + 3 ] = value[ i ].w; + this.dispatchEvent( { type: 'dispose' } ); - } + } - _gl.uniform4fv( location, uniform._array ); +}; - } else if ( type === "m3") { // single THREE.Matrix3 +THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype ); - _gl.uniformMatrix3fv( location, false, value.elements ); +// File:src/renderers/WebGLRenderTargetCube.js - } else if ( type === "m3v" ) { // array of THREE.Matrix3 +/** + * @author alteredq / http://alteredqualia.com + */ - if ( uniform._array === undefined ) { +THREE.WebGLRenderTargetCube = function ( width, height, options ) { - uniform._array = new Float32Array( 9 * value.length ); + THREE.WebGLRenderTarget.call( this, width, height, options ); - } + this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 - for ( i = 0, il = value.length; i < il; i ++ ) { +}; - value[ i ].flattenToArrayOffset( uniform._array, i * 9 ); +THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype ); - } +// File:src/renderers/webgl/WebGLProgram.js - _gl.uniformMatrix3fv( location, false, uniform._array ); +THREE.WebGLProgram = ( function () { - } else if ( type === "m4") { // single THREE.Matrix4 + var programIdCount = 0; - _gl.uniformMatrix4fv( location, false, value.elements ); + var generateDefines = function ( defines ) { - } else if ( type === "m4v" ) { // array of THREE.Matrix4 + var value, chunk, chunks = []; - if ( uniform._array === undefined ) { + for ( var d in defines ) { - uniform._array = new Float32Array( 16 * value.length ); + value = defines[ d ]; + if ( value === false ) continue; - } + chunk = "#define " + d + " " + value; + chunks.push( chunk ); - for ( i = 0, il = value.length; i < il; i ++ ) { + } - value[ i ].flattenToArrayOffset( uniform._array, i * 16 ); + return chunks.join( "\n" ); - } + }; - _gl.uniformMatrix4fv( location, false, uniform._array ); + var cacheUniformLocations = function ( gl, program, identifiers ) { - } else if ( type === "t" ) { // single THREE.Texture (2d or cube) + var uniforms = {}; - texture = value; - textureUnit = getTextureUnit(); + for ( var i = 0, l = identifiers.length; i < l; i ++ ) { - _gl.uniform1i( location, textureUnit ); + var id = identifiers[ i ]; + uniforms[ id ] = gl.getUniformLocation( program, id ); - if ( !texture ) continue; + } - if ( texture.image instanceof Array && texture.image.length === 6 ) { + return uniforms; - setCubeTexture( texture, textureUnit ); + }; - } else if ( texture instanceof THREE.WebGLRenderTargetCube ) { + var cacheAttributeLocations = function ( gl, program, identifiers ) { - setCubeTextureDynamic( texture, textureUnit ); + var attributes = {}; - } else { + for ( var i = 0, l = identifiers.length; i < l; i ++ ) { - _this.setTexture( texture, textureUnit ); + var id = identifiers[ i ]; + attributes[ id ] = gl.getAttribLocation( program, id ); - } + } - } else if ( type === "tv" ) { // array of THREE.Texture (2d) + return attributes; - if ( uniform._array === undefined ) { + }; - uniform._array = []; + return function ( renderer, code, material, parameters ) { - } + var _this = renderer; + var _gl = _this.context; - for( i = 0, il = uniform.value.length; i < il; i ++ ) { + var defines = material.defines; + var uniforms = material.__webglShader.uniforms; + var attributes = material.attributes; - uniform._array[ i ] = getTextureUnit(); + var vertexShader = material.__webglShader.vertexShader; + var fragmentShader = material.__webglShader.fragmentShader; - } + var index0AttributeName = material.index0AttributeName; - _gl.uniform1iv( location, uniform._array ); + if ( index0AttributeName === undefined && parameters.morphTargets === true ) { - for( i = 0, il = uniform.value.length; i < il; i ++ ) { + // programs with morphTargets displace position out of attribute 0 - texture = uniform.value[ i ]; - textureUnit = uniform._array[ i ]; + index0AttributeName = 'position'; - if ( !texture ) continue; + } - _this.setTexture( texture, textureUnit ); + var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; - } + if ( parameters.shadowMapType === THREE.PCFShadowMap ) { - } else { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; - console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type ); + } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) { - } + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; } - }; - - function setupMatrices ( object, camera ) { + // console.log( "building new program " ); - object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - object._normalMatrix.getNormalMatrix( object._modelViewMatrix ); + // - }; + var customDefines = generateDefines( defines ); - // + // - function setColorGamma( array, offset, color, intensitySq ) { + var program = _gl.createProgram(); - array[ offset ] = color.r * color.r * intensitySq; - array[ offset + 1 ] = color.g * color.g * intensitySq; - array[ offset + 2 ] = color.b * color.b * intensitySq; + var prefix_vertex, prefix_fragment; - }; + if ( material instanceof THREE.RawShaderMaterial ) { - function setColorLinear( array, offset, color, intensity ) { + prefix_vertex = ''; + prefix_fragment = ''; - array[ offset ] = color.r * intensity; - array[ offset + 1 ] = color.g * intensity; - array[ offset + 2 ] = color.b * intensity; + } else { - }; + prefix_vertex = [ - function setupLights ( program, lights ) { + "precision " + parameters.precision + " float;", + "precision " + parameters.precision + " int;", - var l, ll, light, n, - r = 0, g = 0, b = 0, - color, skyColor, groundColor, - intensity, intensitySq, - position, - distance, + customDefines, - zlights = _lights, + parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "", - dirColors = zlights.directional.colors, - dirPositions = zlights.directional.positions, + _this.gammaInput ? "#define GAMMA_INPUT" : "", + _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", - pointColors = zlights.point.colors, - pointPositions = zlights.point.positions, - pointDistances = zlights.point.distances, + "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, + "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, + "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, + "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights, - spotColors = zlights.spot.colors, - spotPositions = zlights.spot.positions, - spotDistances = zlights.spot.distances, - spotDirections = zlights.spot.directions, - spotAnglesCos = zlights.spot.anglesCos, - spotExponents = zlights.spot.exponents, + "#define MAX_SHADOWS " + parameters.maxShadows, - hemiSkyColors = zlights.hemi.skyColors, - hemiGroundColors = zlights.hemi.groundColors, - hemiPositions = zlights.hemi.positions, + "#define MAX_BONES " + parameters.maxBones, - dirLength = 0, - pointLength = 0, - spotLength = 0, - hemiLength = 0, + parameters.map ? "#define USE_MAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.vertexColors ? "#define USE_COLOR" : "", - dirCount = 0, - pointCount = 0, - spotCount = 0, - hemiCount = 0, + parameters.skinning ? "#define USE_SKINNING" : "", + parameters.useVertexTexture ? "#define BONE_TEXTURE" : "", - dirOffset = 0, - pointOffset = 0, - spotOffset = 0, - hemiOffset = 0; + parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", + parameters.morphNormals ? "#define USE_MORPHNORMALS" : "", + parameters.wrapAround ? "#define WRAP_AROUND" : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", - for ( l = 0, ll = lights.length; l < ll; l ++ ) { + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", + parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", - light = lights[ l ]; + parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", - if ( light.onlyShadow ) continue; + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "", - color = light.color; - intensity = light.intensity; - distance = light.distance; - if ( light instanceof THREE.AmbientLight ) { + "uniform mat4 modelMatrix;", + "uniform mat4 modelViewMatrix;", + "uniform mat4 projectionMatrix;", + "uniform mat4 viewMatrix;", + "uniform mat3 normalMatrix;", + "uniform vec3 cameraPosition;", - if ( ! light.visible ) continue; + "attribute vec3 position;", + "attribute vec3 normal;", + "attribute vec2 uv;", + "attribute vec2 uv2;", - if ( _this.gammaInput ) { + "#ifdef USE_COLOR", - r += color.r * color.r; - g += color.g * color.g; - b += color.b * color.b; + " attribute vec3 color;", - } else { + "#endif", - r += color.r; - g += color.g; - b += color.b; + "#ifdef USE_MORPHTARGETS", - } + " attribute vec3 morphTarget0;", + " attribute vec3 morphTarget1;", + " attribute vec3 morphTarget2;", + " attribute vec3 morphTarget3;", - } else if ( light instanceof THREE.DirectionalLight ) { + " #ifdef USE_MORPHNORMALS", - dirCount += 1; + " attribute vec3 morphNormal0;", + " attribute vec3 morphNormal1;", + " attribute vec3 morphNormal2;", + " attribute vec3 morphNormal3;", - if ( ! light.visible ) continue; + " #else", - _direction.setFromMatrixPosition( light.matrixWorld ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - _direction.sub( _vector3 ); - _direction.normalize(); + " attribute vec3 morphTarget4;", + " attribute vec3 morphTarget5;", + " attribute vec3 morphTarget6;", + " attribute vec3 morphTarget7;", - // skip lights with undefined direction - // these create troubles in OpenGL (making pixel black) + " #endif", - if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue; + "#endif", - dirOffset = dirLength * 3; + "#ifdef USE_SKINNING", - dirPositions[ dirOffset ] = _direction.x; - dirPositions[ dirOffset + 1 ] = _direction.y; - dirPositions[ dirOffset + 2 ] = _direction.z; + " attribute vec4 skinIndex;", + " attribute vec4 skinWeight;", - if ( _this.gammaInput ) { + "#endif", - setColorGamma( dirColors, dirOffset, color, intensity * intensity ); + "" - } else { + ].join( '\n' ); - setColorLinear( dirColors, dirOffset, color, intensity ); + prefix_fragment = [ - } + "precision " + parameters.precision + " float;", + "precision " + parameters.precision + " int;", - dirLength += 1; + ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "", - } else if ( light instanceof THREE.PointLight ) { + customDefines, - pointCount += 1; + "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, + "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, + "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, + "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights, - if ( ! light.visible ) continue; + "#define MAX_SHADOWS " + parameters.maxShadows, - pointOffset = pointLength * 3; + parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "", - if ( _this.gammaInput ) { + _this.gammaInput ? "#define GAMMA_INPUT" : "", + _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", - setColorGamma( pointColors, pointOffset, color, intensity * intensity ); + ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "", + ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "", - } else { + parameters.map ? "#define USE_MAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.vertexColors ? "#define USE_COLOR" : "", - setColorLinear( pointColors, pointOffset, color, intensity ); + parameters.metal ? "#define METAL" : "", + parameters.wrapAround ? "#define WRAP_AROUND" : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", - } + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", + parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", - _vector3.setFromMatrixPosition( light.matrixWorld ); + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "", - pointPositions[ pointOffset ] = _vector3.x; - pointPositions[ pointOffset + 1 ] = _vector3.y; - pointPositions[ pointOffset + 2 ] = _vector3.z; + "uniform mat4 viewMatrix;", + "uniform vec3 cameraPosition;", + "" - pointDistances[ pointLength ] = distance; + ].join( '\n' ); - pointLength += 1; + } - } else if ( light instanceof THREE.SpotLight ) { + var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader ); + var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader ); - spotCount += 1; + _gl.attachShader( program, glVertexShader ); + _gl.attachShader( program, glFragmentShader ); - if ( ! light.visible ) continue; + if ( index0AttributeName !== undefined ) { - spotOffset = spotLength * 3; + // Force a particular attribute to index 0. + // because potentially expensive emulation is done by browser if attribute 0 is disabled. + // And, color, for example is often automatically bound to index 0 so disabling it - if ( _this.gammaInput ) { + _gl.bindAttribLocation( program, 0, index0AttributeName ); - setColorGamma( spotColors, spotOffset, color, intensity * intensity ); + } - } else { + _gl.linkProgram( program ); - setColorLinear( spotColors, spotOffset, color, intensity ); + if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) { - } + console.error( 'THREE.WebGLProgram: Could not initialise shader.' ); + console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) ); + console.error( 'gl.getError()', _gl.getError() ); - _vector3.setFromMatrixPosition( light.matrixWorld ); + } - spotPositions[ spotOffset ] = _vector3.x; - spotPositions[ spotOffset + 1 ] = _vector3.y; - spotPositions[ spotOffset + 2 ] = _vector3.z; + if ( _gl.getProgramInfoLog( program ) !== '' ) { - spotDistances[ spotLength ] = distance; + console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) ); - _direction.copy( _vector3 ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - _direction.sub( _vector3 ); - _direction.normalize(); + } - spotDirections[ spotOffset ] = _direction.x; - spotDirections[ spotOffset + 1 ] = _direction.y; - spotDirections[ spotOffset + 2 ] = _direction.z; + // clean up - spotAnglesCos[ spotLength ] = Math.cos( light.angle ); - spotExponents[ spotLength ] = light.exponent; + _gl.deleteShader( glVertexShader ); + _gl.deleteShader( glFragmentShader ); - spotLength += 1; + // cache uniform locations - } else if ( light instanceof THREE.HemisphereLight ) { + var identifiers = [ - hemiCount += 1; + 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition', 'morphTargetInfluences', 'bindMatrix', 'bindMatrixInverse' - if ( ! light.visible ) continue; + ]; - _direction.setFromMatrixPosition( light.matrixWorld ); - _direction.normalize(); + if ( parameters.useVertexTexture ) { - // skip lights with undefined direction - // these create troubles in OpenGL (making pixel black) + identifiers.push( 'boneTexture' ); + identifiers.push( 'boneTextureWidth' ); + identifiers.push( 'boneTextureHeight' ); - if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue; + } else { - hemiOffset = hemiLength * 3; + identifiers.push( 'boneGlobalMatrices' ); - hemiPositions[ hemiOffset ] = _direction.x; - hemiPositions[ hemiOffset + 1 ] = _direction.y; - hemiPositions[ hemiOffset + 2 ] = _direction.z; + } - skyColor = light.color; - groundColor = light.groundColor; + if ( parameters.logarithmicDepthBuffer ) { - if ( _this.gammaInput ) { + identifiers.push('logDepthBufFC'); - intensitySq = intensity * intensity; + } - setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq ); - setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq ); - } else { + for ( var u in uniforms ) { - setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity ); - setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity ); + identifiers.push( u ); - } + } - hemiLength += 1; + this.uniforms = cacheUniformLocations( _gl, program, identifiers ); - } + // cache attributes locations - } + identifiers = [ - // null eventual remains from removed lights - // (this is to avoid if in shader) + "position", "normal", "uv", "uv2", "tangent", "color", + "skinIndex", "skinWeight", "lineDistance" - for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0; - for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0; - for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0; - for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0; - for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0; + ]; - zlights.directional.length = dirLength; - zlights.point.length = pointLength; - zlights.spot.length = spotLength; - zlights.hemi.length = hemiLength; + for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) { - zlights.ambient[ 0 ] = r; - zlights.ambient[ 1 ] = g; - zlights.ambient[ 2 ] = b; + identifiers.push( "morphTarget" + i ); - }; + } - // GL state setting + for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) { - this.setFaceCulling = function ( cullFace, frontFaceDirection ) { + identifiers.push( "morphNormal" + i ); - if ( cullFace === THREE.CullFaceNone ) { + } - _gl.disable( _gl.CULL_FACE ); + for ( var a in attributes ) { - } else { + identifiers.push( a ); - if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) { + } - _gl.frontFace( _gl.CW ); + this.attributes = cacheAttributeLocations( _gl, program, identifiers ); - } else { + // - _gl.frontFace( _gl.CCW ); + this.id = programIdCount ++; + this.code = code; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; - } + return this; - if ( cullFace === THREE.CullFaceBack ) { + }; - _gl.cullFace( _gl.BACK ); +} )(); - } else if ( cullFace === THREE.CullFaceFront ) { +// File:src/renderers/webgl/WebGLShader.js - _gl.cullFace( _gl.FRONT ); +THREE.WebGLShader = ( function () { - } else { + var addLineNumbers = function ( string ) { - _gl.cullFace( _gl.FRONT_AND_BACK ); + var lines = string.split( '\n' ); - } + for ( var i = 0; i < lines.length; i ++ ) { - _gl.enable( _gl.CULL_FACE ); + lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; } - }; + return lines.join( '\n' ); - this.setMaterialFaces = function ( material ) { + }; - var doubleSided = material.side === THREE.DoubleSide; - var flipSided = material.side === THREE.BackSide; + return function ( gl, type, string ) { - if ( _oldDoubleSided !== doubleSided ) { + var shader = gl.createShader( type ); - if ( doubleSided ) { + gl.shaderSource( shader, string ); + gl.compileShader( shader ); - _gl.disable( _gl.CULL_FACE ); + if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { - } else { + console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); - _gl.enable( _gl.CULL_FACE ); + } - } + if ( gl.getShaderInfoLog( shader ) !== '' ) { - _oldDoubleSided = doubleSided; + console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ) ); + console.warn( addLineNumbers( string ) ); } - if ( _oldFlipSided !== flipSided ) { + // --enable-privileged-webgl-extension + // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - if ( flipSided ) { + return shader; - _gl.frontFace( _gl.CW ); + }; - } else { +} )(); - _gl.frontFace( _gl.CCW ); +// File:src/renderers/renderables/RenderableVertex.js - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - _oldFlipSided = flipSided; +THREE.RenderableVertex = function () { - } + this.position = new THREE.Vector3(); + this.positionWorld = new THREE.Vector3(); + this.positionScreen = new THREE.Vector4(); - }; + this.visible = true; - this.setDepthTest = function ( depthTest ) { +}; - if ( _oldDepthTest !== depthTest ) { +THREE.RenderableVertex.prototype.copy = function ( vertex ) { - if ( depthTest ) { + this.positionWorld.copy( vertex.positionWorld ); + this.positionScreen.copy( vertex.positionScreen ); - _gl.enable( _gl.DEPTH_TEST ); +}; - } else { +// File:src/renderers/renderables/RenderableFace.js - _gl.disable( _gl.DEPTH_TEST ); +/** + * @author mrdoob / http://mrdoob.com/ + */ - } +THREE.RenderableFace = function () { - _oldDepthTest = depthTest; + this.id = 0; - } + this.v1 = new THREE.RenderableVertex(); + this.v2 = new THREE.RenderableVertex(); + this.v3 = new THREE.RenderableVertex(); - }; + this.normalModel = new THREE.Vector3(); - this.setDepthWrite = function ( depthWrite ) { + this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ]; + this.vertexNormalsLength = 0; - if ( _oldDepthWrite !== depthWrite ) { + this.color = new THREE.Color(); + this.material = null; + this.uvs = [ new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ]; - _gl.depthMask( depthWrite ); - _oldDepthWrite = depthWrite; + this.z = 0; - } +}; - }; +// File:src/renderers/renderables/RenderableObject.js - function setLineWidth ( width ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - if ( width !== _oldLineWidth ) { +THREE.RenderableObject = function () { - _gl.lineWidth( width ); + this.id = 0; - _oldLineWidth = width; + this.object = null; + this.z = 0; - } +}; - }; +// File:src/renderers/renderables/RenderableSprite.js - function setPolygonOffset ( polygonoffset, factor, units ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - if ( _oldPolygonOffset !== polygonoffset ) { +THREE.RenderableSprite = function () { - if ( polygonoffset ) { + this.id = 0; - _gl.enable( _gl.POLYGON_OFFSET_FILL ); + this.object = null; - } else { + this.x = 0; + this.y = 0; + this.z = 0; - _gl.disable( _gl.POLYGON_OFFSET_FILL ); + this.rotation = 0; + this.scale = new THREE.Vector2(); - } + this.material = null; - _oldPolygonOffset = polygonoffset; +}; - } +// File:src/renderers/renderables/RenderableLine.js - if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - _gl.polygonOffset( factor, units ); +THREE.RenderableLine = function () { - _oldPolygonOffsetFactor = factor; - _oldPolygonOffsetUnits = units; + this.id = 0; - } + this.v1 = new THREE.RenderableVertex(); + this.v2 = new THREE.RenderableVertex(); - }; + this.vertexColors = [ new THREE.Color(), new THREE.Color() ]; + this.material = null; - this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) { + this.z = 0; - if ( blending !== _oldBlending ) { +}; - if ( blending === THREE.NoBlending ) { +// File:src/extras/GeometryUtils.js - _gl.disable( _gl.BLEND ); +/** + * @author mrdoob / http://mrdoob.com/ + */ - } else if ( blending === THREE.AdditiveBlending ) { +THREE.GeometryUtils = { - _gl.enable( _gl.BLEND ); - _gl.blendEquation( _gl.FUNC_ADD ); - _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE ); + merge: function ( geometry1, geometry2, materialIndexOffset ) { - } else if ( blending === THREE.SubtractiveBlending ) { + console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); - // TODO: Find blendFuncSeparate() combination - _gl.enable( _gl.BLEND ); - _gl.blendEquation( _gl.FUNC_ADD ); - _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR ); + var matrix; - } else if ( blending === THREE.MultiplyBlending ) { + if ( geometry2 instanceof THREE.Mesh ) { - // TODO: Find blendFuncSeparate() combination - _gl.enable( _gl.BLEND ); - _gl.blendEquation( _gl.FUNC_ADD ); - _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR ); + geometry2.matrixAutoUpdate && geometry2.updateMatrix(); - } else if ( blending === THREE.CustomBlending ) { + matrix = geometry2.matrix; + geometry2 = geometry2.geometry; - _gl.enable( _gl.BLEND ); + } - } else { + geometry1.merge( geometry2, matrix, materialIndexOffset ); - _gl.enable( _gl.BLEND ); - _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD ); - _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA ); + }, - } + center: function ( geometry ) { - _oldBlending = blending; + console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' ); + return geometry.center(); - } + } - if ( blending === THREE.CustomBlending ) { +}; - if ( blendEquation !== _oldBlendEquation ) { +// File:src/extras/ImageUtils.js - _gl.blendEquation( paramThreeToGL( blendEquation ) ); +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author Daosheng Mu / https://github.com/DaoshengMu/ + */ - _oldBlendEquation = blendEquation; +THREE.ImageUtils = { - } + crossOrigin: undefined, - if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) { + loadTexture: function ( url, mapping, onLoad, onError ) { - _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) ); + var loader = new THREE.ImageLoader(); + loader.crossOrigin = this.crossOrigin; - _oldBlendSrc = blendSrc; - _oldBlendDst = blendDst; + var texture = new THREE.Texture( undefined, mapping ); - } + loader.load( url, function ( image ) { - } else { + texture.image = image; + texture.needsUpdate = true; - _oldBlendEquation = null; - _oldBlendSrc = null; - _oldBlendDst = null; + if ( onLoad ) onLoad( texture ); - } + }, undefined, function ( event ) { - }; + if ( onError ) onError( event ); - // Textures + } ); - function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) { + texture.sourceFile = url; - if ( isImagePowerOfTwo ) { + return texture; - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); - - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); - - } else { + }, - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); + loadTextureCube: function ( array, mapping, onLoad, onError ) { - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); + var images = []; - } + var loader = new THREE.ImageLoader(); + loader.crossOrigin = this.crossOrigin; - if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) { + var texture = new THREE.CubeTexture( images, mapping ); - if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) { + // no flipping needed for cube textures - _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) ); - texture.__oldAnisotropy = texture.anisotropy; + texture.flipY = false; - } + var loaded = 0; - } + var loadTexture = function ( i ) { - }; + loader.load( array[ i ], function ( image ) { - this.setTexture = function ( texture, slot ) { + texture.images[ i ] = image; - if ( texture.needsUpdate ) { + loaded += 1; - if ( ! texture.__webglInit ) { + if ( loaded === 6 ) { - texture.__webglInit = true; + texture.needsUpdate = true; - texture.addEventListener( 'dispose', onTextureDispose ); + if ( onLoad ) onLoad( texture ); - texture.__webglTexture = _gl.createTexture(); + } - _this.info.memory.textures ++; + } ); - } + } - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); + for ( var i = 0, il = array.length; i < il; ++ i ) { - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); - _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); + loadTexture( i ); - var image = texture.image, - isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + } - setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo ); + return texture; - var mipmap, mipmaps = texture.mipmaps; + }, - if ( texture instanceof THREE.DataTexture ) { + loadCompressedTexture: function () { - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ) - if ( mipmaps.length > 0 && isImagePowerOfTwo ) { + }, - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + loadCompressedTextureCube: function () { - mipmap = mipmaps[ i ]; - _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ) - } + }, - texture.generateMipmaps = false; + getNormalMap: function ( image, depth ) { - } else { + // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/ - _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); + var cross = function ( a, b ) { - } + return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ]; - } else if ( texture instanceof THREE.CompressedTexture ) { + } - for( var i = 0, il = mipmaps.length; i < il; i ++ ) { + var subtract = function ( a, b ) { - mipmap = mipmaps[ i ]; - if ( texture.format!==THREE.RGBAFormat ) { - _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - } else { - _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - } + return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ]; - } + } - } else { // regular Texture (image, video, canvas) + var normalize = function ( a ) { - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] ); + return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ]; - if ( mipmaps.length > 0 && isImagePowerOfTwo ) { + } - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + depth = depth | 1; - mipmap = mipmaps[ i ]; - _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); + var width = image.width; + var height = image.height; - } + var canvas = document.createElement( 'canvas' ); + canvas.width = width; + canvas.height = height; - texture.generateMipmaps = false; + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0 ); - } else { + var data = context.getImageData( 0, 0, width, height ).data; + var imageData = context.createImageData( width, height ); + var output = imageData.data; - _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image ); + for ( var x = 0; x < width; x ++ ) { - } + for ( var y = 0; y < height; y ++ ) { - } + var ly = y - 1 < 0 ? 0 : y - 1; + var uy = y + 1 > height - 1 ? height - 1 : y + 1; + var lx = x - 1 < 0 ? 0 : x - 1; + var ux = x + 1 > width - 1 ? width - 1 : x + 1; - if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); + var points = []; + var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ]; + points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] ); + points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] ); + points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] ); + points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] ); + points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] ); + points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] ); + points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] ); + points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] ); - texture.needsUpdate = false; + var normals = []; + var num_points = points.length; - if ( texture.onUpdate ) texture.onUpdate(); + for ( var i = 0; i < num_points; i ++ ) { - } else { + var v1 = points[ i ]; + var v2 = points[ ( i + 1 ) % num_points ]; + v1 = subtract( v1, origin ); + v2 = subtract( v2, origin ); + normals.push( normalize( cross( v1, v2 ) ) ); - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); + } - } + var normal = [ 0, 0, 0 ]; - }; + for ( var i = 0; i < normals.length; i ++ ) { - function clampToMaxSize ( image, maxSize ) { + normal[ 0 ] += normals[ i ][ 0 ]; + normal[ 1 ] += normals[ i ][ 1 ]; + normal[ 2 ] += normals[ i ][ 2 ]; - if ( image.width <= maxSize && image.height <= maxSize ) { + } - return image; + normal[ 0 ] /= normals.length; + normal[ 1 ] /= normals.length; + normal[ 2 ] /= normals.length; - } + var idx = ( y * width + x ) * 4; - // Warning: Scaling through the canvas will only work with images that use - // premultiplied alpha. + output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0; + output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0; + output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0; + output[ idx + 3 ] = 255; - var maxDimension = Math.max( image.width, image.height ); - var newWidth = Math.floor( image.width * maxSize / maxDimension ); - var newHeight = Math.floor( image.height * maxSize / maxDimension ); + } - var canvas = document.createElement( 'canvas' ); - canvas.width = newWidth; - canvas.height = newHeight; + } - var ctx = canvas.getContext( "2d" ); - ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight ); + context.putImageData( imageData, 0, 0 ); return canvas; - } - - function setCubeTexture ( texture, slot ) { - - if ( texture.image.length === 6 ) { + }, - if ( texture.needsUpdate ) { + generateDataTexture: function ( width, height, color ) { - if ( ! texture.image.__webglTextureCube ) { + var size = width * height; + var data = new Uint8Array( 3 * size ); - texture.addEventListener( 'dispose', onTextureDispose ); + var r = Math.floor( color.r * 255 ); + var g = Math.floor( color.g * 255 ); + var b = Math.floor( color.b * 255 ); - texture.image.__webglTextureCube = _gl.createTexture(); + for ( var i = 0; i < size; i ++ ) { - _this.info.memory.textures ++; + data[ i * 3 ] = r; + data[ i * 3 + 1 ] = g; + data[ i * 3 + 2 ] = b; - } + } - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); + var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat ); + texture.needsUpdate = true; - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + return texture; - var isCompressed = texture instanceof THREE.CompressedTexture; + } - var cubeImage = []; +}; - for ( var i = 0; i < 6; i ++ ) { +// File:src/extras/SceneUtils.js - if ( _this.autoScaleCubemaps && ! isCompressed ) { +/** + * @author alteredq / http://alteredqualia.com/ + */ - cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize ); +THREE.SceneUtils = { - } else { + createMultiMaterialObject: function ( geometry, materials ) { - cubeImage[ i ] = texture.image[ i ]; + var group = new THREE.Object3D(); - } + for ( var i = 0, l = materials.length; i < l; i ++ ) { - } + group.add( new THREE.Mesh( geometry, materials[ i ] ) ); - var image = cubeImage[ 0 ], - isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + } - setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo ); + return group; - for ( var i = 0; i < 6; i ++ ) { + }, - if( !isCompressed ) { + detach: function ( child, parent, scene ) { - _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); + child.applyMatrix( parent.matrixWorld ); + parent.remove( child ); + scene.add( child ); - } else { + }, - var mipmap, mipmaps = cubeImage[ i ].mipmaps; + attach: function ( child, scene, parent ) { - for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { + var matrixWorldInverse = new THREE.Matrix4(); + matrixWorldInverse.getInverse( parent.matrixWorld ); + child.applyMatrix( matrixWorldInverse ); - mipmap = mipmaps[ j ]; - if ( texture.format!==THREE.RGBAFormat ) { + scene.remove( child ); + parent.add( child ); - _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + } - } else { - _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - } +}; - } - } - } +// File:src/extras/FontUtils.js - if ( texture.generateMipmaps && isImagePowerOfTwo ) { +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author alteredq / http://alteredqualia.com/ + * + * For Text operations in three.js (See TextGeometry) + * + * It uses techniques used in: + * + * typeface.js and canvastext + * For converting fonts and rendering with javascript + * http://typeface.neocracy.org + * + * Triangulation ported from AS3 + * Simple Polygon Triangulation + * http://actionsnippet.com/?p=1462 + * + * A Method to triangulate shapes with holes + * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/ + * + */ - _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); +THREE.FontUtils = { - } + faces: {}, - texture.needsUpdate = false; + // Just for now. face[weight][style] - if ( texture.onUpdate ) texture.onUpdate(); + face: 'helvetiker', + weight: 'normal', + style: 'normal', + size: 150, + divisions: 10, - } else { + getFace: function () { - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); + try { - } + return this.faces[ this.face ][ this.weight ][ this.style ]; - } + } catch (e) { - }; + throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing." - function setCubeTextureDynamic ( texture, slot ) { + }; - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture ); + }, - }; + loadFace: function ( data ) { - // Render targets + var family = data.familyName.toLowerCase(); - function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) { + var ThreeFont = this; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 ); + ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {}; - }; + ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {}; + ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data; - function setupRenderBuffer ( renderbuffer, renderTarget ) { + var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data; - _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + return data; - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + }, - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + drawText: function ( text ) { - /* For some reason this is not working. Defaulting to RGBA4. - } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + var characterPts = [], allPts = []; - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - */ - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + // RenderText - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + var i, p, + face = this.getFace(), + scale = this.size / face.resolution, + offset = 0, + chars = String( text ).split( '' ), + length = chars.length; - } else { + var fontPaths = []; - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); + for ( i = 0; i < length; i ++ ) { - } + var path = new THREE.Path(); - }; + var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path ); + offset += ret.offset; - this.setRenderTarget = function ( renderTarget ) { + fontPaths.push( ret.path ); - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + } - if ( renderTarget && ! renderTarget.__webglFramebuffer ) { + // get the width - if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true; - if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true; + var width = offset / 2; + // + // for ( p = 0; p < allPts.length; p++ ) { + // + // allPts[ p ].x -= width; + // + // } - renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + //var extract = this.extractPoints( allPts, characterPts ); + //extract.contour = allPts; - renderTarget.__webglTexture = _gl.createTexture(); + //extract.paths = fontPaths; + //extract.offset = width; - _this.info.memory.textures ++; + return { paths: fontPaths, offset: width }; - // Setup texture, create render and frame buffers + }, - var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ), - glFormat = paramThreeToGL( renderTarget.format ), - glType = paramThreeToGL( renderTarget.type ); - if ( isCube ) { - renderTarget.__webglFramebuffer = []; - renderTarget.__webglRenderbuffer = []; - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); - setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo ); + extractGlyphPoints: function ( c, face, scale, offset, path ) { - for ( var i = 0; i < 6; i ++ ) { + var pts = []; - renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer(); + var i, i2, divisions, + outline, action, length, + scaleX, scaleY, + x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, + laste, + glyph = face.glyphs[ c ] || face.glyphs[ '?' ]; - _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + if ( ! glyph ) return; - setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); - setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget ); + if ( glyph.o ) { - } + outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); + length = outline.length; - if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + scaleX = scale; + scaleY = scale; - } else { + for ( i = 0; i < length; ) { - renderTarget.__webglFramebuffer = _gl.createFramebuffer(); + action = outline[ i ++ ]; - if ( renderTarget.shareDepthFrom ) { + //console.log( action ); - renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer; + switch ( action ) { - } else { + case 'm': - renderTarget.__webglRenderbuffer = _gl.createRenderbuffer(); + // Move To - } + x = outline[ i ++ ] * scaleX + offset; + y = outline[ i ++ ] * scaleY; - _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); - setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo ); + path.moveTo( x, y ); + break; - _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + case 'l': - setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D ); + // Line To - if ( renderTarget.shareDepthFrom ) { + x = outline[ i ++ ] * scaleX + offset; + y = outline[ i ++ ] * scaleY; + path.lineTo( x,y ); + break; - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + case 'q': - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); + // QuadraticCurveTo - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + cpx = outline[ i ++ ] * scaleX + offset; + cpy = outline[ i ++ ] * scaleY; + cpx1 = outline[ i ++ ] * scaleX + offset; + cpy1 = outline[ i ++ ] * scaleY; - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); + path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); - } + laste = pts[ pts.length - 1 ]; - } else { + if ( laste ) { - setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget ); + cpx0 = laste.x; + cpy0 = laste.y; - } + for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) { - if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); + var t = i2 / divisions; + var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx ); + var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy ); + } - } + } - // Release everything + break; - if ( isCube ) { + case 'b': - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); + // Cubic Bezier Curve - } else { + cpx = outline[ i ++ ] * scaleX + offset; + cpy = outline[ i ++ ] * scaleY; + cpx1 = outline[ i ++ ] * scaleX + offset; + cpy1 = outline[ i ++ ] * scaleY; + cpx2 = outline[ i ++ ] * scaleX + offset; + cpy2 = outline[ i ++ ] * scaleY; - _gl.bindTexture( _gl.TEXTURE_2D, null ); + path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); - } + laste = pts[ pts.length - 1 ]; - _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); + if ( laste ) { - } + cpx0 = laste.x; + cpy0 = laste.y; - var framebuffer, width, height, vx, vy; + for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) { - if ( renderTarget ) { + var t = i2 / divisions; + var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx ); + var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy ); - if ( isCube ) { + } - framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ]; + } - } else { + break; - framebuffer = renderTarget.__webglFramebuffer; + } } + } - width = renderTarget.width; - height = renderTarget.height; - vx = 0; - vy = 0; - } else { + return { offset: glyph.ha * scale, path:path }; + } - framebuffer = null; +}; - width = _viewportWidth; - height = _viewportHeight; - vx = _viewportX; - vy = _viewportY; +THREE.FontUtils.generateShapes = function ( text, parameters ) { - } + // Parameters - if ( framebuffer !== _currentFramebuffer ) { + parameters = parameters || {}; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _gl.viewport( vx, vy, width, height ); + var size = parameters.size !== undefined ? parameters.size : 100; + var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments : 4; - _currentFramebuffer = framebuffer; + var font = parameters.font !== undefined ? parameters.font : 'helvetiker'; + var weight = parameters.weight !== undefined ? parameters.weight : 'normal'; + var style = parameters.style !== undefined ? parameters.style : 'normal'; - } + THREE.FontUtils.size = size; + THREE.FontUtils.divisions = curveSegments; - _currentWidth = width; - _currentHeight = height; + THREE.FontUtils.face = font; + THREE.FontUtils.weight = weight; + THREE.FontUtils.style = style; - }; + // Get a Font data json object - function updateRenderTargetMipmap ( renderTarget ) { + var data = THREE.FontUtils.drawText( text ); - if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { + var paths = data.paths; + var shapes = []; - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); - _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); + for ( var p = 0, pl = paths.length; p < pl; p ++ ) { - } else { + Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); - _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); - _gl.generateMipmap( _gl.TEXTURE_2D ); - _gl.bindTexture( _gl.TEXTURE_2D, null ); + } - } + return shapes; - }; - - // Fallback filters for non-power-of-2 textures - - function filterFallback ( f ) { - - if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) { - - return _gl.NEAREST; +}; - } - return _gl.LINEAR; +/** + * This code is a quick port of code written in C++ which was submitted to + * flipcode.com by John W. Ratcliff // July 22, 2000 + * See original code and more information here: + * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml + * + * ported to actionscript by Zevan Rosser + * www.actionsnippet.com + * + * ported to javascript by Joshua Koo + * http://www.lab4games.net/zz85/blog + * + */ - }; - // Map three.js constants to WebGL constants +( function ( namespace ) { - function paramThreeToGL ( p ) { + var EPSILON = 0.0000000001; - if ( p === THREE.RepeatWrapping ) return _gl.REPEAT; - if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; - if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; + // takes in an contour array and returns - if ( p === THREE.NearestFilter ) return _gl.NEAREST; - if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; - if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; + var process = function ( contour, indices ) { - if ( p === THREE.LinearFilter ) return _gl.LINEAR; - if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; - if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; + var n = contour.length; - if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE; - if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; - if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; - if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; + if ( n < 3 ) return null; - if ( p === THREE.ByteType ) return _gl.BYTE; - if ( p === THREE.ShortType ) return _gl.SHORT; - if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT; - if ( p === THREE.IntType ) return _gl.INT; - if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT; - if ( p === THREE.FloatType ) return _gl.FLOAT; + var result = [], + verts = [], + vertIndices = []; - if ( p === THREE.AlphaFormat ) return _gl.ALPHA; - if ( p === THREE.RGBFormat ) return _gl.RGB; - if ( p === THREE.RGBAFormat ) return _gl.RGBA; - if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE; - if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; + /* we want a counter-clockwise polygon in verts */ - if ( p === THREE.AddEquation ) return _gl.FUNC_ADD; - if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT; - if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; + var u, v, w; - if ( p === THREE.ZeroFactor ) return _gl.ZERO; - if ( p === THREE.OneFactor ) return _gl.ONE; - if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR; - if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; - if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA; - if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; - if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA; - if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; + if ( area( contour ) > 0.0 ) { - if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR; - if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; - if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; + for ( v = 0; v < n; v ++ ) verts[ v ] = v; - if ( _glExtensionCompressedTextureS3TC !== undefined ) { + } else { - if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT; - if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT; - if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT; - if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT; + for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; } - return 0; - - }; - - // Allocations - - function allocateBones ( object ) { - - if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { - - return 1024; - - } else { + var nv = n; - // default for when object is not specified - // ( for example when prebuilding shader - // to be used with multiple objects ) - // - // - leave some extra space for other uniforms - // - limit here is ANGLE's 254 max uniform vectors - // (up to 54 should be safe) + /* remove nv - 2 vertices, creating 1 triangle every time */ - var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ); - var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); + var count = 2 * nv; /* error detection */ - var maxBones = nVertexMatrices; + for ( v = nv - 1; nv > 2; ) { - if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { + /* if we loop, it is probably a non-simple polygon */ - maxBones = Math.min( object.skeleton.bones.length, maxBones ); + if ( ( count -- ) <= 0 ) { - if ( maxBones < object.skeleton.bones.length ) { + //** Triangulate: ERROR - probable bad polygon! - console.warn( "WebGLRenderer: too many bones - " + object.skeleton.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" ); + //throw ( "Warning, unable to triangulate polygon!" ); + //return null; + // Sometimes warning is fine, especially polygons are triangulated in reverse. + console.log( 'Warning, unable to triangulate polygon!' ); - } + if ( indices ) return vertIndices; + return result; } - return maxBones; + /* three consecutive vertices in current polygon, */ - } + u = v; if ( nv <= u ) u = 0; /* previous */ + v = u + 1; if ( nv <= v ) v = 0; /* new v */ + w = v + 1; if ( nv <= w ) w = 0; /* next */ - }; + if ( snip( contour, u, v, w, nv, verts ) ) { - function allocateLights( lights ) { + var a, b, c, s, t; - var dirLights = 0; - var pointLights = 0; - var spotLights = 0; - var hemiLights = 0; + /* true names of the vertices */ - for ( var l = 0, ll = lights.length; l < ll; l ++ ) { + a = verts[ u ]; + b = verts[ v ]; + c = verts[ w ]; - var light = lights[ l ]; + /* output Triangle */ - if ( light.onlyShadow || light.visible === false ) continue; + result.push( [ contour[ a ], + contour[ b ], + contour[ c ] ] ); - if ( light instanceof THREE.DirectionalLight ) dirLights ++; - if ( light instanceof THREE.PointLight ) pointLights ++; - if ( light instanceof THREE.SpotLight ) spotLights ++; - if ( light instanceof THREE.HemisphereLight ) hemiLights ++; - } + vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); - return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights }; + /* remove v from the remaining polygon */ - }; + for ( s = v, t = v + 1; t < nv; s++, t++ ) { - function allocateShadows( lights ) { + verts[ s ] = verts[ t ]; - var maxShadows = 0; + } - for ( var l = 0, ll = lights.length; l < ll; l++ ) { + nv --; - var light = lights[ l ]; + /* reset error detection counter */ - if ( ! light.castShadow ) continue; + count = 2 * nv; - if ( light instanceof THREE.SpotLight ) maxShadows ++; - if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++; + } } - return maxShadows; + if ( indices ) return vertIndices; + return result; }; - // Initialization - - function initGL() { - - try { - - var attributes = { - alpha: _alpha, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer - }; - - _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); - - if ( _gl === null ) { + // calculate area of the contour polygon - throw 'Error creating WebGL context.'; + var area = function ( contour ) { - } + var n = contour.length; + var a = 0.0; - } catch ( error ) { + for ( var p = n - 1, q = 0; q < n; p = q ++ ) { - console.error( error ); + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; } - _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' ); - _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' ); - _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' ); - - _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); - - _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); + return a * 0.5; - _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' ); + }; + var snip = function ( contour, u, v, w, n, verts ) { - if ( _glExtensionTextureFloat === null ) { + var p; + var ax, ay, bx, by; + var cx, cy, px, py; - console.log( 'THREE.WebGLRenderer: Float textures not supported.' ); + ax = contour[ verts[ u ] ].x; + ay = contour[ verts[ u ] ].y; - } + bx = contour[ verts[ v ] ].x; + by = contour[ verts[ v ] ].y; - if ( _glExtensionStandardDerivatives === null ) { + cx = contour[ verts[ w ] ].x; + cy = contour[ verts[ w ] ].y; - console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' ); + if ( EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false; - } + var aX, aY, bX, bY, cX, cY; + var apx, apy, bpx, bpy, cpx, cpy; + var cCROSSap, bCROSScp, aCROSSbp; - if ( _glExtensionTextureFilterAnisotropic === null ) { + aX = cx - bx; aY = cy - by; + bX = ax - cx; bY = ay - cy; + cX = bx - ax; cY = by - ay; - console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' ); + for ( p = 0; p < n; p ++ ) { - } + px = contour[ verts[ p ] ].x + py = contour[ verts[ p ] ].y - if ( _glExtensionCompressedTextureS3TC === null ) { + if ( ( ( px === ax ) && ( py === ay ) ) || + ( ( px === bx ) && ( py === by ) ) || + ( ( px === cx ) && ( py === cy ) ) ) continue; - console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' ); + apx = px - ax; apy = py - ay; + bpx = px - bx; bpy = py - by; + cpx = px - cx; cpy = py - cy; - } + // see if p is inside triangle abc - if ( _glExtensionElementIndexUint === null ) { + aCROSSbp = aX * bpy - aY * bpx; + cCROSSap = cX * apy - cY * apx; + bCROSScp = bX * cpy - bY * cpx; - console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' ); + if ( ( aCROSSbp >= - EPSILON ) && ( bCROSScp >= - EPSILON ) && ( cCROSSap >= - EPSILON ) ) return false; } - if ( _gl.getShaderPrecisionFormat === undefined ) { + return true; - _gl.getShaderPrecisionFormat = function() { + }; - return { - "rangeMin" : 1, - "rangeMax" : 1, - "precision" : 1 - }; - } - } + namespace.Triangulate = process; + namespace.Triangulate.area = area; - if ( _logarithmicDepthBuffer ) { + return namespace; - _glExtensionFragDepth = _gl.getExtension( 'EXT_frag_depth' ); +} )( THREE.FontUtils ); - } +// To use the typeface.js face files, hook up the API +self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace }; +THREE.typeface_js = self._typeface_js; - }; +// File:src/extras/core/Curve.js - function setDefaultGLState () { +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Extensible curve object + * + * Some common of Curve methods + * .getPoint(t), getTangent(t) + * .getPointAt(u), getTagentAt(u) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() + * + * This following classes subclasses THREE.Curve: + * + * -- 2d classes -- + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.CubicBezierCurve + * THREE.SplineCurve + * THREE.ArcCurve + * THREE.EllipseCurve + * + * -- 3d classes -- + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 + * THREE.CubicBezierCurve3 + * THREE.SplineCurve3 + * THREE.ClosedSplineCurve3 + * + * A series of curves can be represented as a THREE.CurvePath + * + **/ - _gl.clearColor( 0, 0, 0, 1 ); - _gl.clearDepth( 1 ); - _gl.clearStencil( 0 ); +/************************************************************** + * Abstract Curve base class + **************************************************************/ - _gl.enable( _gl.DEPTH_TEST ); - _gl.depthFunc( _gl.LEQUAL ); +THREE.Curve = function () { - _gl.frontFace( _gl.CCW ); - _gl.cullFace( _gl.BACK ); - _gl.enable( _gl.CULL_FACE ); +}; - _gl.enable( _gl.BLEND ); - _gl.blendEquation( _gl.FUNC_ADD ); - _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA ); +// Virtual base class method to overwrite and implement in subclasses +// - t [0 .. 1] - _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); +THREE.Curve.prototype.getPoint = function ( t ) { - _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + console.log( "Warning, getPoint() not implemented!" ); + return null; - }; +}; - // default plugins (order is important) +// Get point at relative position in curve according to arc length +// - u [0 .. 1] - this.shadowMapPlugin = new THREE.ShadowMapPlugin(); - this.addPrePlugin( this.shadowMapPlugin ); +THREE.Curve.prototype.getPointAt = function ( u ) { - this.addPostPlugin( new THREE.SpritePlugin() ); - this.addPostPlugin( new THREE.LensFlarePlugin() ); + var t = this.getUtoTmapping( u ); + return this.getPoint( t ); }; -/** - * @author szimek / https://github.com/szimek/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.WebGLRenderTarget = function ( width, height, options ) { +// Get sequence of points using getPoint( t ) - this.width = width; - this.height = height; +THREE.Curve.prototype.getPoints = function ( divisions ) { - options = options || {}; + if ( ! divisions ) divisions = 5; - this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping; - this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping; + var d, pts = []; - this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter; - this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter; + for ( d = 0; d <= divisions; d ++ ) { - this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1; + pts.push( this.getPoint( d / divisions ) ); - this.offset = new THREE.Vector2( 0, 0 ); - this.repeat = new THREE.Vector2( 1, 1 ); + } - this.format = options.format !== undefined ? options.format : THREE.RGBAFormat; - this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType; + return pts; - this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; - this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; +}; - this.generateMipmaps = true; +// Get sequence of points using getPointAt( u ) - this.shareDepthFrom = null; +THREE.Curve.prototype.getSpacedPoints = function ( divisions ) { -}; + if ( ! divisions ) divisions = 5; -THREE.WebGLRenderTarget.prototype = { + var d, pts = []; - constructor: THREE.WebGLRenderTarget, + for ( d = 0; d <= divisions; d ++ ) { - setSize: function ( width, height ) { + pts.push( this.getPointAt( d / divisions ) ); - this.width = width; - this.height = height; + } - }, + return pts; - clone: function () { +}; - var tmp = new THREE.WebGLRenderTarget( this.width, this.height ); +// Get total curve arc length - tmp.wrapS = this.wrapS; - tmp.wrapT = this.wrapT; +THREE.Curve.prototype.getLength = function () { - tmp.magFilter = this.magFilter; - tmp.minFilter = this.minFilter; + var lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; - tmp.anisotropy = this.anisotropy; +}; - tmp.offset.copy( this.offset ); - tmp.repeat.copy( this.repeat ); +// Get list of cumulative segment lengths - tmp.format = this.format; - tmp.type = this.type; +THREE.Curve.prototype.getLengths = function ( divisions ) { - tmp.depthBuffer = this.depthBuffer; - tmp.stencilBuffer = this.stencilBuffer; + if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200; - tmp.generateMipmaps = this.generateMipmaps; + if ( this.cacheArcLengths + && ( this.cacheArcLengths.length == divisions + 1 ) + && ! this.needsUpdate) { - tmp.shareDepthFrom = this.shareDepthFrom; + //console.log( "cached", this.cacheArcLengths ); + return this.cacheArcLengths; - return tmp; + } - }, + this.needsUpdate = false; - dispose: function () { + var cache = []; + var current, last = this.getPoint( 0 ); + var p, sum = 0; - this.dispatchEvent( { type: 'dispose' } ); + cache.push( 0 ); - } + for ( p = 1; p <= divisions; p ++ ) { -}; + current = this.getPoint ( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; -THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype ); + } -/** - * @author alteredq / http://alteredqualia.com - */ + this.cacheArcLengths = cache; -THREE.WebGLRenderTargetCube = function ( width, height, options ) { + return cache; // { sums: cache, sum:sum }; Sum is in the last element. - THREE.WebGLRenderTarget.call( this, width, height, options ); +}; - this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 +THREE.Curve.prototype.updateArcLengths = function() { + this.needsUpdate = true; + this.getLengths(); }; -THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype ); +// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance -THREE.WebGLProgram = ( function () { +THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) { - var programIdCount = 0; + var arcLengths = this.getLengths(); - var generateDefines = function ( defines ) { + var i = 0, il = arcLengths.length; - var value, chunk, chunks = []; + var targetArcLength; // The targeted u distance value to get - for ( var d in defines ) { + if ( distance ) { - value = defines[ d ]; - if ( value === false ) continue; + targetArcLength = distance; - chunk = "#define " + d + " " + value; - chunks.push( chunk ); + } else { - } + targetArcLength = u * arcLengths[ il - 1 ]; - return chunks.join( "\n" ); + } - }; + //var time = Date.now(); - var cacheUniformLocations = function ( gl, program, identifiers ) { + // binary search for the index with largest value smaller than target u distance - var uniforms = {}; + var low = 0, high = il - 1, comparison; - for ( var i = 0, l = identifiers.length; i < l; i ++ ) { + while ( low <= high ) { - var id = identifiers[ i ]; - uniforms[ id ] = gl.getUniformLocation( program, id ); + i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats - } + comparison = arcLengths[ i ] - targetArcLength; - return uniforms; + if ( comparison < 0 ) { - }; + low = i + 1; + continue; - var cacheAttributeLocations = function ( gl, program, identifiers ) { + } else if ( comparison > 0 ) { - var attributes = {}; + high = i - 1; + continue; - for ( var i = 0, l = identifiers.length; i < l; i ++ ) { + } else { - var id = identifiers[ i ]; - attributes[ id ] = gl.getAttribLocation( program, id ); + high = i; + break; + + // DONE } - return attributes; + } - }; + i = high; - return function ( renderer, code, material, parameters ) { + //console.log('b' , i, low, high, Date.now()- time); - var _this = renderer; - var _gl = _this.context; + if ( arcLengths[ i ] == targetArcLength ) { - var fragmentShader = material.fragmentShader; - var vertexShader = material.vertexShader; - var uniforms = material.uniforms; - var attributes = material.attributes; - var defines = material.defines; - var index0AttributeName = material.index0AttributeName; + var t = i / ( il - 1 ); + return t; - if ( index0AttributeName === undefined && parameters.morphTargets === true ) { + } - // programs with morphTargets displace position out of attribute 0 + // we could get finer grain at lengths, or use simple interpolatation between two points - index0AttributeName = 'position'; + var lengthBefore = arcLengths[ i ]; + var lengthAfter = arcLengths[ i + 1 ]; - } + var segmentLength = lengthAfter - lengthBefore; - var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; + // determine where we are between the 'before' and 'after' points - if ( parameters.shadowMapType === THREE.PCFShadowMap ) { + var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; + // add that fractional amount to t - } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) { + var t = ( i + segmentFraction ) / ( il -1 ); - shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; + return t; - } +}; - // console.log( "building new program " ); +// Returns a unit vector tangent at t +// In case any sub curve does not implement its tangent derivation, +// 2 points a small delta apart will be used to find its gradient +// which seems to give a reasonable approximation - // +THREE.Curve.prototype.getTangent = function( t ) { - var customDefines = generateDefines( defines ); + var delta = 0.0001; + var t1 = t - delta; + var t2 = t + delta; - // + // Capping in case of danger - var program = _gl.createProgram(); + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; - var prefix_vertex, prefix_fragment; + var pt1 = this.getPoint( t1 ); + var pt2 = this.getPoint( t2 ); - if ( material instanceof THREE.RawShaderMaterial ) { + var vec = pt2.clone().sub(pt1); + return vec.normalize(); - prefix_vertex = ''; - prefix_fragment = ''; +}; - } else { - prefix_vertex = [ +THREE.Curve.prototype.getTangentAt = function ( u ) { - "precision " + parameters.precision + " float;", - "precision " + parameters.precision + " int;", + var t = this.getUtoTmapping( u ); + return this.getTangent( t ); - customDefines, +}; - parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "", - _this.gammaInput ? "#define GAMMA_INPUT" : "", - _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", - "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, - "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, - "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, - "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights, - "#define MAX_SHADOWS " + parameters.maxShadows, - "#define MAX_BONES " + parameters.maxBones, +/************************************************************** + * Utils + **************************************************************/ - parameters.map ? "#define USE_MAP" : "", - parameters.envMap ? "#define USE_ENVMAP" : "", - parameters.lightMap ? "#define USE_LIGHTMAP" : "", - parameters.bumpMap ? "#define USE_BUMPMAP" : "", - parameters.normalMap ? "#define USE_NORMALMAP" : "", - parameters.specularMap ? "#define USE_SPECULARMAP" : "", - parameters.vertexColors ? "#define USE_COLOR" : "", +THREE.Curve.Utils = { - parameters.skinning ? "#define USE_SKINNING" : "", - parameters.useVertexTexture ? "#define BONE_TEXTURE" : "", + tangentQuadraticBezier: function ( t, p0, p1, p2 ) { - parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", - parameters.morphNormals ? "#define USE_MORPHNORMALS" : "", - parameters.wrapAround ? "#define WRAP_AROUND" : "", - parameters.doubleSided ? "#define DOUBLE_SIDED" : "", - parameters.flipSided ? "#define FLIP_SIDED" : "", + return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); - parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", - parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", - parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", - parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", + }, - parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", + // Puay Bing, thanks for helping with this derivative! - parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", - //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "", + tangentCubicBezier: function (t, p0, p1, p2, p3 ) { + return - 3 * p0 * (1 - t) * (1 - t) + + 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) + + 6 * t * p2 * (1-t) - 3 * t * t * p2 + + 3 * t * t * p3; + }, - "uniform mat4 modelMatrix;", - "uniform mat4 modelViewMatrix;", - "uniform mat4 projectionMatrix;", - "uniform mat4 viewMatrix;", - "uniform mat3 normalMatrix;", - "uniform vec3 cameraPosition;", - "attribute vec3 position;", - "attribute vec3 normal;", - "attribute vec2 uv;", - "attribute vec2 uv2;", + tangentSpline: function ( t, p0, p1, p2, p3 ) { - "#ifdef USE_COLOR", + // To check if my formulas are correct - " attribute vec3 color;", + var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1 + var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t + var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2 + var h11 = 3 * t * t - 2 * t; // t3 − t2 - "#endif", + return h00 + h10 + h01 + h11; - "#ifdef USE_MORPHTARGETS", + }, - " attribute vec3 morphTarget0;", - " attribute vec3 morphTarget1;", - " attribute vec3 morphTarget2;", - " attribute vec3 morphTarget3;", + // Catmull-Rom - " #ifdef USE_MORPHNORMALS", + interpolate: function( p0, p1, p2, p3, t ) { - " attribute vec3 morphNormal0;", - " attribute vec3 morphNormal1;", - " attribute vec3 morphNormal2;", - " attribute vec3 morphNormal3;", + var v0 = ( p2 - p0 ) * 0.5; + var v1 = ( p3 - p1 ) * 0.5; + var t2 = t * t; + var t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - " #else", + } - " attribute vec3 morphTarget4;", - " attribute vec3 morphTarget5;", - " attribute vec3 morphTarget6;", - " attribute vec3 morphTarget7;", +}; - " #endif", - "#endif", +// TODO: Transformation for Curves? - "#ifdef USE_SKINNING", +/************************************************************** + * 3D Curves + **************************************************************/ - " attribute vec4 skinIndex;", - " attribute vec4 skinWeight;", +// A Factory method for creating new curve subclasses - "#endif", +THREE.Curve.create = function ( constructor, getPointFunc ) { - "" + constructor.prototype = Object.create( THREE.Curve.prototype ); + constructor.prototype.getPoint = getPointFunc; - ].join( '\n' ); + return constructor; - prefix_fragment = [ +}; - "precision " + parameters.precision + " float;", - "precision " + parameters.precision + " int;", +// File:src/extras/core/CurvePath.js - ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "", +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + **/ - customDefines, +/************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ - "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, - "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, - "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, - "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights, +THREE.CurvePath = function () { - "#define MAX_SHADOWS " + parameters.maxShadows, + this.curves = []; + this.bends = []; + + this.autoClose = false; // Automatically closes the path +}; - parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "", +THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype ); - _this.gammaInput ? "#define GAMMA_INPUT" : "", - _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", +THREE.CurvePath.prototype.add = function ( curve ) { - ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "", - ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "", + this.curves.push( curve ); - parameters.map ? "#define USE_MAP" : "", - parameters.envMap ? "#define USE_ENVMAP" : "", - parameters.lightMap ? "#define USE_LIGHTMAP" : "", - parameters.bumpMap ? "#define USE_BUMPMAP" : "", - parameters.normalMap ? "#define USE_NORMALMAP" : "", - parameters.specularMap ? "#define USE_SPECULARMAP" : "", - parameters.vertexColors ? "#define USE_COLOR" : "", +}; - parameters.metal ? "#define METAL" : "", - parameters.wrapAround ? "#define WRAP_AROUND" : "", - parameters.doubleSided ? "#define DOUBLE_SIDED" : "", - parameters.flipSided ? "#define FLIP_SIDED" : "", +THREE.CurvePath.prototype.checkConnection = function() { + // TODO + // If the ending of curve is not connected to the starting + // or the next curve, then, this is not a real path +}; - parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", - parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", - parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", - parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", +THREE.CurvePath.prototype.closePath = function() { + // TODO Test + // and verify for vector3 (needs to implement equals) + // Add a line curve if start and end of lines are not connected + var startPoint = this.curves[0].getPoint(0); + var endPoint = this.curves[this.curves.length-1].getPoint(1); + + if (! startPoint.equals(endPoint)) { + this.curves.push( new THREE.LineCurve(endPoint, startPoint) ); + } + +}; - parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", - //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "", +// To get accurate point with reference to +// entire path distance at time t, +// following has to be done: - "uniform mat4 viewMatrix;", - "uniform vec3 cameraPosition;", - "" +// 1. Length of each sub path have to be known +// 2. Locate and identify type of curve +// 3. Get t for the curve +// 4. Return curve.getPointAt(t') - ].join( '\n' ); +THREE.CurvePath.prototype.getPoint = function( t ) { - } + var d = t * this.getLength(); + var curveLengths = this.getCurveLengths(); + var i = 0, diff, curve; - var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader ); - var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader ); + // To think about boundaries points. - _gl.attachShader( program, glVertexShader ); - _gl.attachShader( program, glFragmentShader ); + while ( i < curveLengths.length ) { - if ( index0AttributeName !== undefined ) { + if ( curveLengths[ i ] >= d ) { - // Force a particular attribute to index 0. - // because potentially expensive emulation is done by browser if attribute 0 is disabled. - // And, color, for example is often automatically bound to index 0 so disabling it + diff = curveLengths[ i ] - d; + curve = this.curves[ i ]; - _gl.bindAttribLocation( program, 0, index0AttributeName ); + var u = 1 - diff / curve.getLength(); - } + return curve.getPointAt( u ); - _gl.linkProgram( program ); + break; + } - if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) { + i ++; - console.error( 'Could not initialise shader' ); - console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) ); - console.error( 'gl.getError()', _gl.getError() ); + } - } + return null; - if ( _gl.getProgramInfoLog( program ) !== '' ) { + // loop where sum != 0, sum > d , sum+1 maxX ) maxX = p.x; + else if ( p.x < minX ) minX = p.x; + + if ( p.y > maxY ) maxY = p.y; + else if ( p.y < minY ) minY = p.y; + + if ( v3 ) { + + if ( p.z > maxZ ) maxZ = p.z; + else if ( p.z < minZ ) minZ = p.z; } - this.attributes = cacheAttributeLocations( _gl, program, identifiers ); + sum.add( p ); - // + } - this.id = programIdCount ++; - this.code = code; - this.usedTimes = 1; - this.program = program; - this.vertexShader = glVertexShader; - this.fragmentShader = glFragmentShader; + var ret = { - return this; + minX: minX, + minY: minY, + maxX: maxX, + maxY: maxY }; -} )(); + if ( v3 ) { -THREE.WebGLShader = ( function () { + ret.maxZ = maxZ; + ret.minZ = minZ; - var addLineNumbers = function ( string ) { + } - var lines = string.split( '\n' ); + return ret; - for ( var i = 0; i < lines.length; i ++ ) { +}; - lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; +/************************************************************** + * Create Geometries Helpers + **************************************************************/ - } +/// Generate geometry from path points (for Line or Points objects) - return lines.join( '\n' ); +THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) { - }; + var pts = this.getPoints( divisions, true ); + return this.createGeometry( pts ); - return function ( gl, type, string ) { +}; - var shader = gl.createShader( type ); +// Generate geometry from equidistance sampling along the path - gl.shaderSource( shader, string ); - gl.compileShader( shader ); +THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) { - if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { + var pts = this.getSpacedPoints( divisions, true ); + return this.createGeometry( pts ); - console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); +}; - } +THREE.CurvePath.prototype.createGeometry = function( points ) { - if ( gl.getShaderInfoLog( shader ) !== '' ) { + var geometry = new THREE.Geometry(); - console.error( 'THREE.WebGLShader:', 'gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ) ); - console.error( addLineNumbers( string ) ); + for ( var i = 0; i < points.length; i ++ ) { - } + geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) ); - // --enable-privileged-webgl-extension - // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + } - return shader; + return geometry; - }; +}; -} )(); -/** - * @author mrdoob / http://mrdoob.com/ - */ -THREE.RenderableVertex = function () { +/************************************************************** + * Bend / Wrap Helper Methods + **************************************************************/ - this.position = new THREE.Vector3(); - this.positionWorld = new THREE.Vector3(); - this.positionScreen = new THREE.Vector4(); +// Wrap path / Bend modifiers? - this.visible = true; +THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) { + + this.bends.push( bendpath ); }; -THREE.RenderableVertex.prototype.copy = function ( vertex ) { +THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) { - this.positionWorld.copy( vertex.positionWorld ); - this.positionScreen.copy( vertex.positionScreen ); + var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints + var i, il; -}; + if ( ! bends ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + bends = this.bends; -THREE.RenderableFace = function () { + } - this.id = 0; + for ( i = 0, il = bends.length; i < il; i ++ ) { - this.v1 = new THREE.RenderableVertex(); - this.v2 = new THREE.RenderableVertex(); - this.v3 = new THREE.RenderableVertex(); + oldPts = this.getWrapPoints( oldPts, bends[ i ] ); - this.normalModel = new THREE.Vector3(); + } - this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ]; - this.vertexNormalsLength = 0; + return oldPts; - this.color = null; - this.material = null; - this.uvs = [ new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ]; +}; - this.z = 0; +THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) { -}; + var oldPts = this.getSpacedPoints( segments ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + var i, il; -THREE.RenderableObject = function () { + if ( ! bends ) { - this.id = 0; + bends = this.bends; - this.object = null; - this.z = 0; + } + + for ( i = 0, il = bends.length; i < il; i ++ ) { + + oldPts = this.getWrapPoints( oldPts, bends[ i ] ); + + } + + return oldPts; }; -/** - * @author mrdoob / http://mrdoob.com/ - */ +// This returns getPoints() bend/wrapped around the contour of a path. +// Read http://www.planetclegg.com/projects/WarpingTextToSplines.html -THREE.RenderableSprite = function () { +THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) { - this.id = 0; + var bounds = this.getBoundingBox(); - this.object = null; + var i, il, p, oldX, oldY, xNorm; - this.x = 0; - this.y = 0; - this.z = 0; + for ( i = 0, il = oldPts.length; i < il; i ++ ) { - this.rotation = 0; - this.scale = new THREE.Vector2(); + p = oldPts[ i ]; - this.material = null; + oldX = p.x; + oldY = p.y; -}; + xNorm = oldX / bounds.maxX; -/** - * @author mrdoob / http://mrdoob.com/ - */ + // If using actual distance, for length > path, requires line extrusions + //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance -THREE.RenderableLine = function () { + xNorm = path.getUtoTmapping( xNorm, oldX ); - this.id = 0; + // check for out of bounds? - this.v1 = new THREE.RenderableVertex(); - this.v2 = new THREE.RenderableVertex(); + var pathPt = path.getPoint( xNorm ); + var normal = path.getTangent( xNorm ); + normal.set( - normal.y, normal.x ).multiplyScalar( oldY ); - this.vertexColors = [ new THREE.Color(), new THREE.Color() ]; - this.material = null; + p.x = pathPt.x + normal.x; + p.y = pathPt.y + normal.y; - this.z = 0; + } + + return oldPts; }; + +// File:src/extras/core/Gyroscope.js + /** - * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.GeometryUtils = { +THREE.Gyroscope = function () { - // Merge two geometries or geometry and geometry from object (using object's transform) + THREE.Object3D.call( this ); - merge: function ( geometry1, geometry2, materialIndexOffset ) { +}; - console.warn( 'DEPRECATED: GeometryUtils\'s .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); +THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype ); - var matrix; +THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) { - if ( geometry2 instanceof THREE.Mesh ) { + this.matrixAutoUpdate && this.updateMatrix(); - geometry2.matrixAutoUpdate && geometry2.updateMatrix(); + // update matrixWorld - matrix = geometry2.matrix; - geometry2 = geometry2.geometry; + if ( this.matrixWorldNeedsUpdate || force ) { - } + if ( this.parent ) { - geometry1.merge( geometry2, matrix, materialIndexOffset ); + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - }, + this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld ); + this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject ); - // Get random point in triangle (via barycentric coordinates) - // (uniform distribution) - // http://www.cgafaq.info/wiki/Random_Point_In_Triangle + this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld ); - randomPointInTriangle: function () { - var vector = new THREE.Vector3(); + } else { - return function ( vectorA, vectorB, vectorC ) { + this.matrixWorld.copy( this.matrix ); - var point = new THREE.Vector3(); + } - var a = THREE.Math.random16(); - var b = THREE.Math.random16(); - if ( ( a + b ) > 1 ) { + this.matrixWorldNeedsUpdate = false; - a = 1 - a; - b = 1 - b; + force = true; - } + } - var c = 1 - a - b; + // update children - point.copy( vectorA ); - point.multiplyScalar( a ); + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - vector.copy( vectorB ); - vector.multiplyScalar( b ); + this.children[ i ].updateMatrixWorld( force ); - point.add( vector ); + } - vector.copy( vectorC ); - vector.multiplyScalar( c ); +}; - point.add( vector ); +THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3(); +THREE.Gyroscope.prototype.translationObject = new THREE.Vector3(); +THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion(); +THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion(); +THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3(); +THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3(); - return point; - }; +// File:src/extras/core/Path.js - }(), +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Creates free form 2d path using series of points, lines or curves. + * + **/ - // Get random point in face (triangle) - // (uniform distribution) +THREE.Path = function ( points ) { - randomPointInFace: function ( face, geometry, useCachedAreas ) { + THREE.CurvePath.call(this); - var vA, vB, vC; + this.actions = []; - vA = geometry.vertices[ face.a ]; - vB = geometry.vertices[ face.b ]; - vC = geometry.vertices[ face.c ]; + if ( points ) { - return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC ); + this.fromPoints( points ); - }, + } - // Get uniformly distributed random points in mesh - // - create array with cumulative sums of face areas - // - pick random number from 0 to total area - // - find corresponding place in area array by binary search - // - get random point in face +}; - randomPointsInGeometry: function ( geometry, n ) { +THREE.Path.prototype = Object.create( THREE.CurvePath.prototype ); - var face, i, - faces = geometry.faces, - vertices = geometry.vertices, - il = faces.length, - totalArea = 0, - cumulativeAreas = [], - vA, vB, vC, vD; +THREE.PathActions = { - // precompute face areas + MOVE_TO: 'moveTo', + LINE_TO: 'lineTo', + QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve + BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve + CSPLINE_THRU: 'splineThru', // Catmull-rom spline + ARC: 'arc', // Circle + ELLIPSE: 'ellipse' +}; - for ( i = 0; i < il; i ++ ) { +// TODO Clean up PATH API - face = faces[ i ]; +// Create path using straight lines to connect all points +// - vectors: array of Vector2 - vA = vertices[ face.a ]; - vB = vertices[ face.b ]; - vC = vertices[ face.c ]; +THREE.Path.prototype.fromPoints = function ( vectors ) { - face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC ); + this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); - totalArea += face._area; + for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) { - cumulativeAreas[ i ] = totalArea; + this.lineTo( vectors[ v ].x, vectors[ v ].y ); - } + }; - // binary search cumulative areas array +}; - function binarySearchIndices( value ) { +// startPath() endPath()? - function binarySearch( start, end ) { +THREE.Path.prototype.moveTo = function ( x, y ) { - // return closest larger index - // if exact number is not found + var args = Array.prototype.slice.call( arguments ); + this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } ); - if ( end < start ) - return start; +}; - var mid = start + Math.floor( ( end - start ) / 2 ); +THREE.Path.prototype.lineTo = function ( x, y ) { - if ( cumulativeAreas[ mid ] > value ) { + var args = Array.prototype.slice.call( arguments ); - return binarySearch( start, mid - 1 ); + var lastargs = this.actions[ this.actions.length - 1 ].args; - } else if ( cumulativeAreas[ mid ] < value ) { + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; - return binarySearch( mid + 1, end ); + var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) ); + this.curves.push( curve ); - } else { + this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } ); - return mid; +}; - } +THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) { - } + var args = Array.prototype.slice.call( arguments ); - var result = binarySearch( 0, cumulativeAreas.length - 1 ) - return result; + var lastargs = this.actions[ this.actions.length - 1 ].args; - } + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; - // pick random face weighted by face area + var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ), + new THREE.Vector2( aCPx, aCPy ), + new THREE.Vector2( aX, aY ) ); + this.curves.push( curve ); - var r, index, - result = []; + this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } ); - var stats = {}; +}; - for ( i = 0; i < n; i ++ ) { +THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, + aCP2x, aCP2y, + aX, aY ) { - r = THREE.Math.random16() * totalArea; + var args = Array.prototype.slice.call( arguments ); - index = binarySearchIndices( r ); + var lastargs = this.actions[ this.actions.length - 1 ].args; - result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true ); + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; - if ( ! stats[ index ] ) { + var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ), + new THREE.Vector2( aCP1x, aCP1y ), + new THREE.Vector2( aCP2x, aCP2y ), + new THREE.Vector2( aX, aY ) ); + this.curves.push( curve ); - stats[ index ] = 1; + this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } ); - } else { +}; - stats[ index ] += 1; +THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) { - } + var args = Array.prototype.slice.call( arguments ); + var lastargs = this.actions[ this.actions.length - 1 ].args; - } + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; +//--- + var npts = [ new THREE.Vector2( x0, y0 ) ]; + Array.prototype.push.apply( npts, pts ); - return result; + var curve = new THREE.SplineCurve( npts ); + this.curves.push( curve ); - }, + this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } ); - // Get triangle area (half of parallelogram) - // http://mathworld.wolfram.com/TriangleArea.html +}; - triangleArea: function () { +// FUTURE: Change the API or follow canvas API? - var vector1 = new THREE.Vector3(); - var vector2 = new THREE.Vector3(); +THREE.Path.prototype.arc = function ( aX, aY, aRadius, + aStartAngle, aEndAngle, aClockwise ) { - return function ( vectorA, vectorB, vectorC ) { + var lastargs = this.actions[ this.actions.length - 1].args; + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; - vector1.subVectors( vectorB, vectorA ); - vector2.subVectors( vectorC, vectorA ); - vector1.cross( vector2 ); + this.absarc(aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); - return 0.5 * vector1.length(); + }; - }; + THREE.Path.prototype.absarc = function ( aX, aY, aRadius, + aStartAngle, aEndAngle, aClockwise ) { + this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + }; - }(), +THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, + aStartAngle, aEndAngle, aClockwise ) { - // Center geometry so that 0,0,0 is in center of bounding box + var lastargs = this.actions[ this.actions.length - 1].args; + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; - center: function ( geometry ) { + this.absellipse(aX + x0, aY + y0, xRadius, yRadius, + aStartAngle, aEndAngle, aClockwise ); - geometry.computeBoundingBox(); + }; - var bb = geometry.boundingBox; - var offset = new THREE.Vector3(); +THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, + aStartAngle, aEndAngle, aClockwise ) { - offset.addVectors( bb.min, bb.max ); - offset.multiplyScalar( -0.5 ); + var args = Array.prototype.slice.call( arguments ); + var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, + aStartAngle, aEndAngle, aClockwise ); + this.curves.push( curve ); - geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) ); - geometry.computeBoundingBox(); + var lastPoint = curve.getPoint(1); + args.push(lastPoint.x); + args.push(lastPoint.y); - return offset; + this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } ); - } + }; -}; +THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) { -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + if ( ! divisions ) divisions = 40; -THREE.ImageUtils = { + var points = []; - crossOrigin: undefined, + for ( var i = 0; i < divisions; i ++ ) { - loadTexture: function ( url, mapping, onLoad, onError ) { + points.push( this.getPoint( i / divisions ) ); - var loader = new THREE.ImageLoader(); - loader.crossOrigin = this.crossOrigin; + //if( !this.getPoint( i / divisions ) ) throw "DIE"; - var texture = new THREE.Texture( undefined, mapping ); + } - var image = loader.load( url, function () { + // if ( closedPath ) { + // + // points.push( points[ 0 ] ); + // + // } - texture.needsUpdate = true; + return points; - if ( onLoad ) onLoad( texture ); +}; - }, undefined, function ( event ) { +/* Return an array of vectors based on contour of the path */ - if ( onError ) onError( event ); +THREE.Path.prototype.getPoints = function( divisions, closedPath ) { - } ); + if (this.useSpacedPoints) { + console.log('tata'); + return this.getSpacedPoints( divisions, closedPath ); + } - texture.image = image; - texture.sourceFile = url; + divisions = divisions || 12; - return texture; + var points = []; - }, + var i, il, item, action, args; + var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0, + laste, j, + t, tx, ty; - loadCompressedTexture: function ( url, mapping, onLoad, onError ) { + for ( i = 0, il = this.actions.length; i < il; i ++ ) { - var texture = new THREE.CompressedTexture(); - texture.mapping = mapping; + item = this.actions[ i ]; - var request = new XMLHttpRequest(); + action = item.action; + args = item.args; - request.onload = function () { + switch( action ) { - var buffer = request.response; - var dds = THREE.ImageUtils.parseDDS( buffer, true ); + case THREE.PathActions.MOVE_TO: - texture.format = dds.format; + points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) ); - texture.mipmaps = dds.mipmaps; - texture.image.width = dds.width; - texture.image.height = dds.height; + break; - // gl.generateMipmap fails for compressed textures - // mipmaps must be embedded in the DDS file - // or texture filters must not use mipmapping + case THREE.PathActions.LINE_TO: - texture.generateMipmaps = false; + points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) ); - texture.needsUpdate = true; + break; - if ( onLoad ) onLoad( texture ); + case THREE.PathActions.QUADRATIC_CURVE_TO: - } + cpx = args[ 2 ]; + cpy = args[ 3 ]; - request.onerror = onError; + cpx1 = args[ 0 ]; + cpy1 = args[ 1 ]; - request.open( 'GET', url, true ); - request.responseType = "arraybuffer"; - request.send( null ); + if ( points.length > 0 ) { - return texture; + laste = points[ points.length - 1 ]; - }, + cpx0 = laste.x; + cpy0 = laste.y; - loadTextureCube: function ( array, mapping, onLoad, onError ) { + } else { - var images = []; - images.loadCount = 0; + laste = this.actions[ i - 1 ].args; - var loader = new THREE.ImageLoader(); - loader.crossOrigin = this.crossOrigin; - - var texture = new THREE.Texture(); - texture.image = images; - - if ( mapping !== undefined ) texture.mapping = mapping; + cpx0 = laste[ laste.length - 2 ]; + cpy0 = laste[ laste.length - 1 ]; - // no flipping needed for cube textures + } - texture.flipY = false; + for ( j = 1; j <= divisions; j ++ ) { - for ( var i = 0, il = array.length; i < il; ++ i ) { + t = j / divisions; - var cubeImage = loader.load( array[i], function () { + tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx ); + ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy ); - images.loadCount += 1; + points.push( new THREE.Vector2( tx, ty ) ); - if ( images.loadCount === 6 ) { + } - texture.needsUpdate = true; - if ( onLoad ) onLoad( texture ); + break; - } + case THREE.PathActions.BEZIER_CURVE_TO: - } ); - - images[ i ] = cubeImage; - } - - return texture; - - }, - - loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) { - - var images = []; - images.loadCount = 0; + cpx = args[ 4 ]; + cpy = args[ 5 ]; - var texture = new THREE.CompressedTexture(); - texture.image = images; - if ( mapping !== undefined ) texture.mapping = mapping; + cpx1 = args[ 0 ]; + cpy1 = args[ 1 ]; - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) + cpx2 = args[ 2 ]; + cpy2 = args[ 3 ]; - texture.flipY = false; + if ( points.length > 0 ) { - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files + laste = points[ points.length - 1 ]; - texture.generateMipmaps = false; + cpx0 = laste.x; + cpy0 = laste.y; - var generateCubeFaceCallback = function ( rq, img ) { + } else { - return function () { + laste = this.actions[ i - 1 ].args; - var buffer = rq.response; - var dds = THREE.ImageUtils.parseDDS( buffer, true ); + cpx0 = laste[ laste.length - 2 ]; + cpy0 = laste[ laste.length - 1 ]; - img.format = dds.format; + } - img.mipmaps = dds.mipmaps; - img.width = dds.width; - img.height = dds.height; - images.loadCount += 1; + for ( j = 1; j <= divisions; j ++ ) { - if ( images.loadCount === 6 ) { + t = j / divisions; - texture.format = dds.format; - texture.needsUpdate = true; - if ( onLoad ) onLoad( texture ); + tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx ); + ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy ); - } + points.push( new THREE.Vector2( tx, ty ) ); } - } + break; - // compressed cubemap textures as 6 separate DDS files + case THREE.PathActions.CSPLINE_THRU: - if ( array instanceof Array ) { + laste = this.actions[ i - 1 ].args; - for ( var i = 0, il = array.length; i < il; ++ i ) { + var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] ); + var spts = [ last ]; - var cubeImage = {}; - images[ i ] = cubeImage; + var n = divisions * args[ 0 ].length; - var request = new XMLHttpRequest(); + spts = spts.concat( args[ 0 ] ); - request.onload = generateCubeFaceCallback( request, cubeImage ); - request.onerror = onError; + var spline = new THREE.SplineCurve( spts ); - var url = array[ i ]; + for ( j = 1; j <= n; j ++ ) { - request.open( 'GET', url, true ); - request.responseType = "arraybuffer"; - request.send( null ); + points.push( spline.getPointAt( j / n ) ) ; } - // compressed cubemap texture stored in a single DDS file - - } else { - - var url = array; - var request = new XMLHttpRequest(); + break; - request.onload = function( ) { + case THREE.PathActions.ARC: - var buffer = request.response; - var dds = THREE.ImageUtils.parseDDS( buffer, true ); + var aX = args[ 0 ], aY = args[ 1 ], + aRadius = args[ 2 ], + aStartAngle = args[ 3 ], aEndAngle = args[ 4 ], + aClockwise = !! args[ 5 ]; - if ( dds.isCubemap ) { + var deltaAngle = aEndAngle - aStartAngle; + var angle; + var tdivisions = divisions * 2; - var faces = dds.mipmaps.length / dds.mipmapCount; + for ( j = 1; j <= tdivisions; j ++ ) { - for ( var f = 0; f < faces; f ++ ) { + t = j / tdivisions; - images[ f ] = { mipmaps : [] }; + if ( ! aClockwise ) { - for ( var i = 0; i < dds.mipmapCount; i ++ ) { + t = 1 - t; - images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] ); - images[ f ].format = dds.format; - images[ f ].width = dds.width; - images[ f ].height = dds.height; + } - } + angle = aStartAngle + t * deltaAngle; - } + tx = aX + aRadius * Math.cos( angle ); + ty = aY + aRadius * Math.sin( angle ); - texture.format = dds.format; - texture.needsUpdate = true; - if ( onLoad ) onLoad( texture ); + //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty); - } + points.push( new THREE.Vector2( tx, ty ) ); } - request.onerror = onError; - - request.open( 'GET', url, true ); - request.responseType = "arraybuffer"; - request.send( null ); - - } - - return texture; + //console.log(points); - }, + break; + + case THREE.PathActions.ELLIPSE: - loadDDSTexture: function ( url, mapping, onLoad, onError ) { + var aX = args[ 0 ], aY = args[ 1 ], + xRadius = args[ 2 ], + yRadius = args[ 3 ], + aStartAngle = args[ 4 ], aEndAngle = args[ 5 ], + aClockwise = !! args[ 6 ]; - var images = []; - images.loadCount = 0; - var texture = new THREE.CompressedTexture(); - texture.image = images; - if ( mapping !== undefined ) texture.mapping = mapping; + var deltaAngle = aEndAngle - aStartAngle; + var angle; + var tdivisions = divisions * 2; - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) + for ( j = 1; j <= tdivisions; j ++ ) { - texture.flipY = false; + t = j / tdivisions; - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files + if ( ! aClockwise ) { - texture.generateMipmaps = false; + t = 1 - t; - { - var request = new XMLHttpRequest(); + } - request.onload = function( ) { + angle = aStartAngle + t * deltaAngle; - var buffer = request.response; - var dds = THREE.ImageUtils.parseDDS( buffer, true ); + tx = aX + xRadius * Math.cos( angle ); + ty = aY + yRadius * Math.sin( angle ); - if ( dds.isCubemap ) { + //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty); - var faces = dds.mipmaps.length / dds.mipmapCount; + points.push( new THREE.Vector2( tx, ty ) ); - for ( var f = 0; f < faces; f ++ ) { + } - images[ f ] = { mipmaps : [] }; + //console.log(points); - for ( var i = 0; i < dds.mipmapCount; i ++ ) { + break; - images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] ); - images[ f ].format = dds.format; - images[ f ].width = dds.width; - images[ f ].height = dds.height; + } // end switch - } + } - } - } else { - texture.image.width = dds.width; - texture.image.height = dds.height; - texture.mipmaps = dds.mipmaps; - } + // Normalize to remove the closing point by default. + var lastPoint = points[ points.length - 1]; + var EPSILON = 0.0000000001; + if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON && + Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON) + points.splice( points.length - 1, 1); + if ( closedPath ) { - texture.format = dds.format; - texture.needsUpdate = true; - if ( onLoad ) onLoad( texture ); + points.push( points[ 0 ] ); - } + } - request.onerror = onError; + return points; - request.open( 'GET', url, true ); - request.responseType = "arraybuffer"; - request.send( null ); +}; - } +// +// Breaks path into shapes +// +// Assumptions (if parameter isCCW==true the opposite holds): +// - solid shapes are defined clockwise (CW) +// - holes are defined counterclockwise (CCW) +// +// If parameter noHoles==true: +// - all subPaths are regarded as solid shapes +// - definition order CW/CCW has no relevance +// - return texture; +THREE.Path.prototype.toShapes = function( isCCW, noHoles ) { - }, + function extractSubpaths( inActions ) { - parseDDS: function ( buffer, loadMipmaps ) { + var i, il, item, action, args; - var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 }; + var subPaths = [], lastPath = new THREE.Path(); - // Adapted from @toji's DDS utils - // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js + for ( i = 0, il = inActions.length; i < il; i ++ ) { - // All values and structures referenced from: - // http://msdn.microsoft.com/en-us/library/bb943991.aspx/ + item = inActions[ i ]; - var DDS_MAGIC = 0x20534444; + args = item.args; + action = item.action; - var DDSD_CAPS = 0x1, - DDSD_HEIGHT = 0x2, - DDSD_WIDTH = 0x4, - DDSD_PITCH = 0x8, - DDSD_PIXELFORMAT = 0x1000, - DDSD_MIPMAPCOUNT = 0x20000, - DDSD_LINEARSIZE = 0x80000, - DDSD_DEPTH = 0x800000; + if ( action == THREE.PathActions.MOVE_TO ) { - var DDSCAPS_COMPLEX = 0x8, - DDSCAPS_MIPMAP = 0x400000, - DDSCAPS_TEXTURE = 0x1000; + if ( lastPath.actions.length != 0 ) { - var DDSCAPS2_CUBEMAP = 0x200, - DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, - DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, - DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, - DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, - DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, - DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, - DDSCAPS2_VOLUME = 0x200000; + subPaths.push( lastPath ); + lastPath = new THREE.Path(); - var DDPF_ALPHAPIXELS = 0x1, - DDPF_ALPHA = 0x2, - DDPF_FOURCC = 0x4, - DDPF_RGB = 0x40, - DDPF_YUV = 0x200, - DDPF_LUMINANCE = 0x20000; + } - function fourCCToInt32( value ) { + } - return value.charCodeAt(0) + - (value.charCodeAt(1) << 8) + - (value.charCodeAt(2) << 16) + - (value.charCodeAt(3) << 24); + lastPath[ action ].apply( lastPath, args ); } - function int32ToFourCC( value ) { + if ( lastPath.actions.length != 0 ) { - return String.fromCharCode( - value & 0xff, - (value >> 8) & 0xff, - (value >> 16) & 0xff, - (value >> 24) & 0xff - ); - } + subPaths.push( lastPath ); - function loadARGBMip( buffer, dataOffset, width, height ) { - var dataLength = width*height*4; - var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength ); - var byteArray = new Uint8Array( dataLength ); - var dst = 0; - var src = 0; - for ( var y = 0; y < height; y++ ) { - for ( var x = 0; x < width; x++ ) { - var b = srcBuffer[src]; src++; - var g = srcBuffer[src]; src++; - var r = srcBuffer[src]; src++; - var a = srcBuffer[src]; src++; - byteArray[dst] = r; dst++; //r - byteArray[dst] = g; dst++; //g - byteArray[dst] = b; dst++; //b - byteArray[dst] = a; dst++; //a - } - } - return byteArray; } - var FOURCC_DXT1 = fourCCToInt32("DXT1"); - var FOURCC_DXT3 = fourCCToInt32("DXT3"); - var FOURCC_DXT5 = fourCCToInt32("DXT5"); + // console.log(subPaths); - var headerLengthInt = 31; // The header length in 32 bit ints + return subPaths; + } - // Offsets into the header array + function toShapesNoHoles( inSubpaths ) { - var off_magic = 0; + var shapes = []; - var off_size = 1; - var off_flags = 2; - var off_height = 3; - var off_width = 4; + for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) { - var off_mipmapCount = 7; + var tmpPath = inSubpaths[ i ]; - var off_pfFlags = 20; - var off_pfFourCC = 21; - var off_RGBBitCount = 22; - var off_RBitMask = 23; - var off_GBitMask = 24; - var off_BBitMask = 25; - var off_ABitMask = 26; + var tmpShape = new THREE.Shape(); + tmpShape.actions = tmpPath.actions; + tmpShape.curves = tmpPath.curves; - var off_caps = 27; - var off_caps2 = 28; - var off_caps3 = 29; - var off_caps4 = 30; + shapes.push( tmpShape ); + } - // Parse header + //console.log("shape", shapes); - var header = new Int32Array( buffer, 0, headerLengthInt ); + return shapes; + }; - if ( header[ off_magic ] !== DDS_MAGIC ) { + function isPointInsidePolygon( inPt, inPolygon ) { + var EPSILON = 0.0000000001; - console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" ); - return dds; + var polyLen = inPolygon.length; - } + // inPt on polygon contour => immediate success or + // toggling of inside/outside at every single! intersection point of an edge + // with the horizontal line through inPt, left of inPt + // not counting lowerY endpoints of edges and whole edges on that line + var inside = false; + for( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { + var edgeLowPt = inPolygon[ p ]; + var edgeHighPt = inPolygon[ q ]; - if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) { + var edgeDx = edgeHighPt.x - edgeLowPt.x; + var edgeDy = edgeHighPt.y - edgeLowPt.y; - console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" ); - return dds; + if ( Math.abs(edgeDy) > EPSILON ) { // not parallel + if ( edgeDy < 0 ) { + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + } + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + if ( inPt.y == edgeLowPt.y ) { + if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ? + // continue; // no intersection or edgeLowPt => doesn't count !!! + } else { + var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); + if ( perpEdge == 0 ) return true; // inPt is on contour ? + if ( perpEdge < 0 ) continue; + inside = ! inside; // true intersection left of inPt + } + } else { // parallel or colinear + if ( inPt.y != edgeLowPt.y ) continue; // parallel + // egde lies on the same horizontal line as inPt + if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || + ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour ! + // continue; + } } - var blockBytes; + return inside; + } - var fourCC = header[ off_pfFourCC ]; - var isRGBAUncompressed = false; + var subPaths = extractSubpaths( this.actions ); + if ( subPaths.length == 0 ) return []; - switch ( fourCC ) { + if ( noHoles === true ) return toShapesNoHoles( subPaths ); - case FOURCC_DXT1: - blockBytes = 8; - dds.format = THREE.RGB_S3TC_DXT1_Format; - break; + var solid, tmpPath, tmpShape, shapes = []; - case FOURCC_DXT3: + if ( subPaths.length == 1) { - blockBytes = 16; - dds.format = THREE.RGBA_S3TC_DXT3_Format; - break; + tmpPath = subPaths[0]; + tmpShape = new THREE.Shape(); + tmpShape.actions = tmpPath.actions; + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; - case FOURCC_DXT5: + } - blockBytes = 16; - dds.format = THREE.RGBA_S3TC_DXT5_Format; - break; + var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; - default: + // console.log("Holes first", holesFirst); + + var betterShapeHoles = []; + var newShapes = []; + var newShapeHoles = []; + var mainIdx = 0; + var tmpPoints; - if( header[off_RGBBitCount] ==32 - && header[off_RBitMask]&0xff0000 - && header[off_GBitMask]&0xff00 - && header[off_BBitMask]&0xff - && header[off_ABitMask]&0xff000000 ) { - isRGBAUncompressed = true; - blockBytes = 64; - dds.format = THREE.RGBAFormat; - } else { - console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) ); - return dds; - } - } + newShapes[mainIdx] = undefined; + newShapeHoles[mainIdx] = []; - dds.mipmapCount = 1; + var i, il; - if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) { + for ( i = 0, il = subPaths.length; i < il; i ++ ) { - dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] ); + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = THREE.Shape.Utils.isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; - } + if ( solid ) { - //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc. + if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx ++; - dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false; + newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints }; + newShapes[mainIdx].s.actions = tmpPath.actions; + newShapes[mainIdx].s.curves = tmpPath.curves; + + if ( holesFirst ) mainIdx ++; + newShapeHoles[mainIdx] = []; - dds.width = header[ off_width ]; - dds.height = header[ off_height ]; + //console.log('cw', i); - var dataOffset = header[ off_size ] + 4; + } else { - // Extract mipmaps buffers + newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } ); - var width = dds.width; - var height = dds.height; + //console.log('ccw', i); - var faces = dds.isCubemap ? 6 : 1; + } - for ( var face = 0; face < faces; face ++ ) { + } - for ( var i = 0; i < dds.mipmapCount; i ++ ) { + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[0] ) return toShapesNoHoles( subPaths ); - if( isRGBAUncompressed ) { - var byteArray = loadARGBMip( buffer, dataOffset, width, height ); - var dataLength = byteArray.length; - } else { - var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes; - var byteArray = new Uint8Array( buffer, dataOffset, dataLength ); - } - - var mipmap = { "data": byteArray, "width": width, "height": height }; - dds.mipmaps.push( mipmap ); - dataOffset += dataLength; - - width = Math.max( width * 0.5, 1 ); - height = Math.max( height * 0.5, 1 ); + if ( newShapes.length > 1 ) { + var ambigious = false; + var toChange = []; + for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + betterShapeHoles[sIdx] = []; + } + for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + var sh = newShapes[sIdx]; + var sho = newShapeHoles[sIdx]; + for (var hIdx = 0; hIdx < sho.length; hIdx ++ ) { + var ho = sho[hIdx]; + var hole_unassigned = true; + for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) { + if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); + if ( hole_unassigned ) { + hole_unassigned = false; + betterShapeHoles[s2Idx].push( ho ); + } else { + ambigious = true; + } + } + } + if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); } } - - width = dds.width; - height = dds.height; - } + // console.log("ambigious: ", ambigious); + if ( toChange.length > 0 ) { + // console.log("to change: ", toChange); + if (! ambigious) newShapeHoles = betterShapeHoles; + } + } - return dds; - - }, - - getNormalMap: function ( image, depth ) { - - // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/ + var tmpHoles, j, jl; + for ( i = 0, il = newShapes.length; i < il; i ++ ) { + tmpShape = newShapes[i].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[i]; + for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + tmpShape.holes.push( tmpHoles[j].h ); + } + } - var cross = function ( a, b ) { + //console.log("shape", shapes); - return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ]; + return shapes; - } +}; - var subtract = function ( a, b ) { +// File:src/extras/core/Shape.js - return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ]; +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Defines a 2d shape plane using paths. + **/ - } +// STEP 1 Create a path. +// STEP 2 Turn path into shape. +// STEP 3 ExtrudeGeometry takes in Shape/Shapes +// STEP 3a - Extract points from each shape, turn to vertices +// STEP 3b - Triangulate each shape, add faces. - var normalize = function ( a ) { +THREE.Shape = function () { - var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] ); - return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ]; + THREE.Path.apply( this, arguments ); + this.holes = []; - } +}; - depth = depth | 1; +THREE.Shape.prototype = Object.create( THREE.Path.prototype ); - var width = image.width; - var height = image.height; +// Convenience method to return ExtrudeGeometry - var canvas = document.createElement( 'canvas' ); - canvas.width = width; - canvas.height = height; +THREE.Shape.prototype.extrude = function ( options ) { - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0 ); + var extruded = new THREE.ExtrudeGeometry( this, options ); + return extruded; - var data = context.getImageData( 0, 0, width, height ).data; - var imageData = context.createImageData( width, height ); - var output = imageData.data; +}; - for ( var x = 0; x < width; x ++ ) { +// Convenience method to return ShapeGeometry - for ( var y = 0; y < height; y ++ ) { +THREE.Shape.prototype.makeGeometry = function ( options ) { - var ly = y - 1 < 0 ? 0 : y - 1; - var uy = y + 1 > height - 1 ? height - 1 : y + 1; - var lx = x - 1 < 0 ? 0 : x - 1; - var ux = x + 1 > width - 1 ? width - 1 : x + 1; + var geometry = new THREE.ShapeGeometry( this, options ); + return geometry; - var points = []; - var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ]; - points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] ); - points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] ); - points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] ); - points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] ); - points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] ); - points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] ); - points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] ); - points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] ); +}; - var normals = []; - var num_points = points.length; +// Get points of holes - for ( var i = 0; i < num_points; i ++ ) { +THREE.Shape.prototype.getPointsHoles = function ( divisions ) { - var v1 = points[ i ]; - var v2 = points[ ( i + 1 ) % num_points ]; - v1 = subtract( v1, origin ); - v2 = subtract( v2, origin ); - normals.push( normalize( cross( v1, v2 ) ) ); + var i, il = this.holes.length, holesPts = []; - } + for ( i = 0; i < il; i ++ ) { - var normal = [ 0, 0, 0 ]; + holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends ); - for ( var i = 0; i < normals.length; i ++ ) { + } - normal[ 0 ] += normals[ i ][ 0 ]; - normal[ 1 ] += normals[ i ][ 1 ]; - normal[ 2 ] += normals[ i ][ 2 ]; + return holesPts; - } +}; - normal[ 0 ] /= normals.length; - normal[ 1 ] /= normals.length; - normal[ 2 ] /= normals.length; +// Get points of holes (spaced by regular distance) - var idx = ( y * width + x ) * 4; +THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) { - output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0; - output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0; - output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0; - output[ idx + 3 ] = 255; + var i, il = this.holes.length, holesPts = []; - } + for ( i = 0; i < il; i ++ ) { - } + holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends ); - context.putImageData( imageData, 0, 0 ); + } - return canvas; + return holesPts; - }, +}; - generateDataTexture: function ( width, height, color ) { - var size = width * height; - var data = new Uint8Array( 3 * size ); +// Get points of shape and holes (keypoints based on segments parameter) - var r = Math.floor( color.r * 255 ); - var g = Math.floor( color.g * 255 ); - var b = Math.floor( color.b * 255 ); +THREE.Shape.prototype.extractAllPoints = function ( divisions ) { - for ( var i = 0; i < size; i ++ ) { + return { - data[ i * 3 ] = r; - data[ i * 3 + 1 ] = g; - data[ i * 3 + 2 ] = b; + shape: this.getTransformedPoints( divisions ), + holes: this.getPointsHoles( divisions ) - } + }; - var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat ); - texture.needsUpdate = true; +}; - return texture; +THREE.Shape.prototype.extractPoints = function ( divisions ) { + if (this.useSpacedPoints) { + return this.extractAllSpacedPoints(divisions); } + return this.extractAllPoints(divisions); + }; -/** - * @author alteredq / http://alteredqualia.com/ - */ +// +// THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) { +// +// return { +// +// shape: this.transform( bend, divisions ), +// holes: this.getPointsHoles( divisions, bend ) +// +// }; +// +// }; -THREE.SceneUtils = { +// Get points of shape and holes (spaced by regular distance) - createMultiMaterialObject: function ( geometry, materials ) { +THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) { - var group = new THREE.Object3D(); + return { - for ( var i = 0, l = materials.length; i < l; i ++ ) { + shape: this.getTransformedSpacedPoints( divisions ), + holes: this.getSpacedPointsHoles( divisions ) - group.add( new THREE.Mesh( geometry, materials[ i ] ) ); + }; - } +}; - return group; +/************************************************************** + * Utils + **************************************************************/ - }, +THREE.Shape.Utils = { - detach : function ( child, parent, scene ) { + triangulateShape: function ( contour, holes ) { - child.applyMatrix( parent.matrixWorld ); - parent.remove( child ); - scene.add( child ); + function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { + // inOtherPt needs to be colinear to the inSegment + if ( inSegPt1.x != inSegPt2.x ) { + if ( inSegPt1.x < inSegPt2.x ) { + return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); + } else { + return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); + } + } else { + if ( inSegPt1.y < inSegPt2.y ) { + return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); + } else { + return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); + } + } + } - }, + function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { + var EPSILON = 0.0000000001; - attach: function ( child, scene, parent ) { + var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; + var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; - var matrixWorldInverse = new THREE.Matrix4(); - matrixWorldInverse.getInverse( parent.matrixWorld ); - child.applyMatrix( matrixWorldInverse ); + var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; + var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; - scene.remove( child ); - parent.add( child ); + var limit = seg1dy * seg2dx - seg1dx * seg2dy; + var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; - } + if ( Math.abs(limit) > EPSILON ) { // not parallel -}; - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author alteredq / http://alteredqualia.com/ - * - * For Text operations in three.js (See TextGeometry) - * - * It uses techniques used in: - * - * typeface.js and canvastext - * For converting fonts and rendering with javascript - * http://typeface.neocracy.org - * - * Triangulation ported from AS3 - * Simple Polygon Triangulation - * http://actionsnippet.com/?p=1462 - * - * A Method to triangulate shapes with holes - * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/ - * - */ - -THREE.FontUtils = { - - faces : {}, - - // Just for now. face[weight][style] - - face : "helvetiker", - weight: "normal", - style : "normal", - size : 150, - divisions : 10, - - getFace : function() { - - return this.faces[ this.face ][ this.weight ][ this.style ]; - - }, - - loadFace : function( data ) { - - var family = data.familyName.toLowerCase(); - - var ThreeFont = this; - - ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {}; - - ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {}; - ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data; - - var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data; - - return data; - - }, - - drawText : function( text ) { - - var characterPts = [], allPts = []; - - // RenderText - - var i, p, - face = this.getFace(), - scale = this.size / face.resolution, - offset = 0, - chars = String( text ).split( '' ), - length = chars.length; - - var fontPaths = []; - - for ( i = 0; i < length; i ++ ) { - - var path = new THREE.Path(); - - var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path ); - offset += ret.offset; - - fontPaths.push( ret.path ); - - } - - // get the width - - var width = offset / 2; - // - // for ( p = 0; p < allPts.length; p++ ) { - // - // allPts[ p ].x -= width; - // - // } - - //var extract = this.extractPoints( allPts, characterPts ); - //extract.contour = allPts; - - //extract.paths = fontPaths; - //extract.offset = width; - - return { paths : fontPaths, offset : width }; - - }, - - - - - extractGlyphPoints : function( c, face, scale, offset, path ) { - - var pts = []; - - var i, i2, divisions, - outline, action, length, - scaleX, scaleY, - x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, - laste, - glyph = face.glyphs[ c ] || face.glyphs[ '?' ]; - - if ( !glyph ) return; - - if ( glyph.o ) { - - outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); - length = outline.length; - - scaleX = scale; - scaleY = scale; - - for ( i = 0; i < length; ) { - - action = outline[ i ++ ]; - - //console.log( action ); - - switch( action ) { - - case 'm': - - // Move To - - x = outline[ i++ ] * scaleX + offset; - y = outline[ i++ ] * scaleY; - - path.moveTo( x, y ); - break; - - case 'l': - - // Line To - - x = outline[ i++ ] * scaleX + offset; - y = outline[ i++ ] * scaleY; - path.lineTo(x,y); - break; - - case 'q': - - // QuadraticCurveTo - - cpx = outline[ i++ ] * scaleX + offset; - cpy = outline[ i++ ] * scaleY; - cpx1 = outline[ i++ ] * scaleX + offset; - cpy1 = outline[ i++ ] * scaleY; - - path.quadraticCurveTo(cpx1, cpy1, cpx, cpy); - - laste = pts[ pts.length - 1 ]; - - if ( laste ) { - - cpx0 = laste.x; - cpy0 = laste.y; - - for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) { - - var t = i2 / divisions; - var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx ); - var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy ); - } - - } - - break; - - case 'b': - - // Cubic Bezier Curve - - cpx = outline[ i++ ] * scaleX + offset; - cpy = outline[ i++ ] * scaleY; - cpx1 = outline[ i++ ] * scaleX + offset; - cpy1 = outline[ i++ ] * -scaleY; - cpx2 = outline[ i++ ] * scaleX + offset; - cpy2 = outline[ i++ ] * -scaleY; - - path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 ); - - laste = pts[ pts.length - 1 ]; - - if ( laste ) { - - cpx0 = laste.x; - cpy0 = laste.y; - - for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) { - - var t = i2 / divisions; - var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx ); - var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy ); - - } - - } - - break; - - } - - } - } - - - - return { offset: glyph.ha*scale, path:path}; - } - -}; - - -THREE.FontUtils.generateShapes = function( text, parameters ) { - - // Parameters - - parameters = parameters || {}; - - var size = parameters.size !== undefined ? parameters.size : 100; - var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4; - - var font = parameters.font !== undefined ? parameters.font : "helvetiker"; - var weight = parameters.weight !== undefined ? parameters.weight : "normal"; - var style = parameters.style !== undefined ? parameters.style : "normal"; - - THREE.FontUtils.size = size; - THREE.FontUtils.divisions = curveSegments; - - THREE.FontUtils.face = font; - THREE.FontUtils.weight = weight; - THREE.FontUtils.style = style; - - // Get a Font data json object - - var data = THREE.FontUtils.drawText( text ); - - var paths = data.paths; - var shapes = []; - - for ( var p = 0, pl = paths.length; p < pl; p ++ ) { - - Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); - - } - - return shapes; - -}; - - -/** - * This code is a quick port of code written in C++ which was submitted to - * flipcode.com by John W. Ratcliff // July 22, 2000 - * See original code and more information here: - * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml - * - * ported to actionscript by Zevan Rosser - * www.actionsnippet.com - * - * ported to javascript by Joshua Koo - * http://www.lab4games.net/zz85/blog - * - */ - - -( function( namespace ) { - - var EPSILON = 0.0000000001; - - // takes in an contour array and returns - - var process = function( contour, indices ) { - - var n = contour.length; - - if ( n < 3 ) return null; - - var result = [], - verts = [], - vertIndices = []; - - /* we want a counter-clockwise polygon in verts */ - - var u, v, w; - - if ( area( contour ) > 0.0 ) { - - for ( v = 0; v < n; v++ ) verts[ v ] = v; - - } else { - - for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v; - - } - - var nv = n; - - /* remove nv - 2 vertices, creating 1 triangle every time */ - - var count = 2 * nv; /* error detection */ - - for( v = nv - 1; nv > 2; ) { - - /* if we loop, it is probably a non-simple polygon */ - - if ( ( count-- ) <= 0 ) { - - //** Triangulate: ERROR - probable bad polygon! - - //throw ( "Warning, unable to triangulate polygon!" ); - //return null; - // Sometimes warning is fine, especially polygons are triangulated in reverse. - console.log( "Warning, unable to triangulate polygon!" ); - - if ( indices ) return vertIndices; - return result; - - } - - /* three consecutive vertices in current polygon, */ - - u = v; if ( nv <= u ) u = 0; /* previous */ - v = u + 1; if ( nv <= v ) v = 0; /* new v */ - w = v + 1; if ( nv <= w ) w = 0; /* next */ - - if ( snip( contour, u, v, w, nv, verts ) ) { - - var a, b, c, s, t; - - /* true names of the vertices */ - - a = verts[ u ]; - b = verts[ v ]; - c = verts[ w ]; - - /* output Triangle */ - - result.push( [ contour[ a ], - contour[ b ], - contour[ c ] ] ); - - - vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); - - /* remove v from the remaining polygon */ - - for( s = v, t = v + 1; t < nv; s++, t++ ) { - - verts[ s ] = verts[ t ]; - - } - - nv--; - - /* reset error detection counter */ - - count = 2 * nv; - - } - - } - - if ( indices ) return vertIndices; - return result; - - }; - - // calculate area of the contour polygon - - var area = function ( contour ) { - - var n = contour.length; - var a = 0.0; - - for( var p = n - 1, q = 0; q < n; p = q++ ) { - - a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; - - } - - return a * 0.5; - - }; - - var snip = function ( contour, u, v, w, n, verts ) { - - var p; - var ax, ay, bx, by; - var cx, cy, px, py; - - ax = contour[ verts[ u ] ].x; - ay = contour[ verts[ u ] ].y; - - bx = contour[ verts[ v ] ].x; - by = contour[ verts[ v ] ].y; - - cx = contour[ verts[ w ] ].x; - cy = contour[ verts[ w ] ].y; - - if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false; - - var aX, aY, bX, bY, cX, cY; - var apx, apy, bpx, bpy, cpx, cpy; - var cCROSSap, bCROSScp, aCROSSbp; - - aX = cx - bx; aY = cy - by; - bX = ax - cx; bY = ay - cy; - cX = bx - ax; cY = by - ay; - - for ( p = 0; p < n; p++ ) { - - px = contour[ verts[ p ] ].x - py = contour[ verts[ p ] ].y - - if ( ( (px === ax) && (py === ay) ) || - ( (px === bx) && (py === by) ) || - ( (px === cx) && (py === cy) ) ) continue; - - apx = px - ax; apy = py - ay; - bpx = px - bx; bpy = py - by; - cpx = px - cx; cpy = py - cy; - - // see if p is inside triangle abc - - aCROSSbp = aX*bpy - aY*bpx; - cCROSSap = cX*apy - cY*apx; - bCROSScp = bX*cpy - bY*cpx; - - if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false; - - } - - return true; - - }; - - - namespace.Triangulate = process; - namespace.Triangulate.area = area; - - return namespace; - -})(THREE.FontUtils); - -// To use the typeface.js face files, hook up the API -self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace }; -THREE.typeface_js = self._typeface_js; - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Extensible curve object - * - * Some common of Curve methods - * .getPoint(t), getTangent(t) - * .getPointAt(u), getTagentAt(u) - * .getPoints(), .getSpacedPoints() - * .getLength() - * .updateArcLengths() - * - * This following classes subclasses THREE.Curve: - * - * -- 2d classes -- - * THREE.LineCurve - * THREE.QuadraticBezierCurve - * THREE.CubicBezierCurve - * THREE.SplineCurve - * THREE.ArcCurve - * THREE.EllipseCurve - * - * -- 3d classes -- - * THREE.LineCurve3 - * THREE.QuadraticBezierCurve3 - * THREE.CubicBezierCurve3 - * THREE.SplineCurve3 - * THREE.ClosedSplineCurve3 - * - * A series of curves can be represented as a THREE.CurvePath - * - **/ - -/************************************************************** - * Abstract Curve base class - **************************************************************/ - -THREE.Curve = function () { - -}; - -// Virtual base class method to overwrite and implement in subclasses -// - t [0 .. 1] - -THREE.Curve.prototype.getPoint = function ( t ) { - - console.log( "Warning, getPoint() not implemented!" ); - return null; - -}; - -// Get point at relative position in curve according to arc length -// - u [0 .. 1] - -THREE.Curve.prototype.getPointAt = function ( u ) { - - var t = this.getUtoTmapping( u ); - return this.getPoint( t ); - -}; - -// Get sequence of points using getPoint( t ) - -THREE.Curve.prototype.getPoints = function ( divisions ) { - - if ( !divisions ) divisions = 5; - - var d, pts = []; - - for ( d = 0; d <= divisions; d ++ ) { - - pts.push( this.getPoint( d / divisions ) ); - - } - - return pts; - -}; - -// Get sequence of points using getPointAt( u ) - -THREE.Curve.prototype.getSpacedPoints = function ( divisions ) { - - if ( !divisions ) divisions = 5; - - var d, pts = []; - - for ( d = 0; d <= divisions; d ++ ) { - - pts.push( this.getPointAt( d / divisions ) ); - - } - - return pts; - -}; - -// Get total curve arc length - -THREE.Curve.prototype.getLength = function () { - - var lengths = this.getLengths(); - return lengths[ lengths.length - 1 ]; - -}; - -// Get list of cumulative segment lengths - -THREE.Curve.prototype.getLengths = function ( divisions ) { - - if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200; - - if ( this.cacheArcLengths - && ( this.cacheArcLengths.length == divisions + 1 ) - && !this.needsUpdate) { - - //console.log( "cached", this.cacheArcLengths ); - return this.cacheArcLengths; - - } - - this.needsUpdate = false; - - var cache = []; - var current, last = this.getPoint( 0 ); - var p, sum = 0; - - cache.push( 0 ); - - for ( p = 1; p <= divisions; p ++ ) { - - current = this.getPoint ( p / divisions ); - sum += current.distanceTo( last ); - cache.push( sum ); - last = current; - - } - - this.cacheArcLengths = cache; - - return cache; // { sums: cache, sum:sum }; Sum is in the last element. - -}; - - -THREE.Curve.prototype.updateArcLengths = function() { - this.needsUpdate = true; - this.getLengths(); -}; - -// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance - -THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) { - - var arcLengths = this.getLengths(); - - var i = 0, il = arcLengths.length; - - var targetArcLength; // The targeted u distance value to get - - if ( distance ) { - - targetArcLength = distance; - - } else { - - targetArcLength = u * arcLengths[ il - 1 ]; - - } - - //var time = Date.now(); - - // binary search for the index with largest value smaller than target u distance - - var low = 0, high = il - 1, comparison; - - while ( low <= high ) { - - i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats - - comparison = arcLengths[ i ] - targetArcLength; - - if ( comparison < 0 ) { - - low = i + 1; - continue; - - } else if ( comparison > 0 ) { - - high = i - 1; - continue; - - } else { - - high = i; - break; - - // DONE - - } - - } - - i = high; - - //console.log('b' , i, low, high, Date.now()- time); - - if ( arcLengths[ i ] == targetArcLength ) { - - var t = i / ( il - 1 ); - return t; - - } - - // we could get finer grain at lengths, or use simple interpolatation between two points - - var lengthBefore = arcLengths[ i ]; - var lengthAfter = arcLengths[ i + 1 ]; - - var segmentLength = lengthAfter - lengthBefore; - - // determine where we are between the 'before' and 'after' points - - var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - - // add that fractional amount to t - - var t = ( i + segmentFraction ) / ( il -1 ); - - return t; - -}; - -// Returns a unit vector tangent at t -// In case any sub curve does not implement its tangent derivation, -// 2 points a small delta apart will be used to find its gradient -// which seems to give a reasonable approximation - -THREE.Curve.prototype.getTangent = function( t ) { - - var delta = 0.0001; - var t1 = t - delta; - var t2 = t + delta; - - // Capping in case of danger - - if ( t1 < 0 ) t1 = 0; - if ( t2 > 1 ) t2 = 1; - - var pt1 = this.getPoint( t1 ); - var pt2 = this.getPoint( t2 ); - - var vec = pt2.clone().sub(pt1); - return vec.normalize(); - -}; - - -THREE.Curve.prototype.getTangentAt = function ( u ) { - - var t = this.getUtoTmapping( u ); - return this.getTangent( t ); - -}; - - - - - -/************************************************************** - * Utils - **************************************************************/ - -THREE.Curve.Utils = { - - tangentQuadraticBezier: function ( t, p0, p1, p2 ) { - - return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); - - }, - - // Puay Bing, thanks for helping with this derivative! - - tangentCubicBezier: function (t, p0, p1, p2, p3 ) { - - return -3 * p0 * (1 - t) * (1 - t) + - 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) + - 6 * t * p2 * (1-t) - 3 * t * t * p2 + - 3 * t * t * p3; - }, - - - tangentSpline: function ( t, p0, p1, p2, p3 ) { - - // To check if my formulas are correct - - var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1 - var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t - var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2 - var h11 = 3 * t * t - 2 * t; // t3 − t2 - - return h00 + h10 + h01 + h11; - - }, - - // Catmull-Rom - - interpolate: function( p0, p1, p2, p3, t ) { - - var v0 = ( p2 - p0 ) * 0.5; - var v1 = ( p3 - p1 ) * 0.5; - var t2 = t * t; - var t3 = t * t2; - return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - - } - -}; - - -// TODO: Transformation for Curves? - -/************************************************************** - * 3D Curves - **************************************************************/ - -// A Factory method for creating new curve subclasses - -THREE.Curve.create = function ( constructor, getPointFunc ) { - - constructor.prototype = Object.create( THREE.Curve.prototype ); - constructor.prototype.getPoint = getPointFunc; - - return constructor; - -}; - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - **/ - -/************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ - -THREE.CurvePath = function () { - - this.curves = []; - this.bends = []; - - this.autoClose = false; // Automatically closes the path -}; - -THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype ); - -THREE.CurvePath.prototype.add = function ( curve ) { - - this.curves.push( curve ); - -}; - -THREE.CurvePath.prototype.checkConnection = function() { - // TODO - // If the ending of curve is not connected to the starting - // or the next curve, then, this is not a real path -}; - -THREE.CurvePath.prototype.closePath = function() { - // TODO Test - // and verify for vector3 (needs to implement equals) - // Add a line curve if start and end of lines are not connected - var startPoint = this.curves[0].getPoint(0); - var endPoint = this.curves[this.curves.length-1].getPoint(1); - - if (!startPoint.equals(endPoint)) { - this.curves.push( new THREE.LineCurve(endPoint, startPoint) ); - } - -}; - -// To get accurate point with reference to -// entire path distance at time t, -// following has to be done: - -// 1. Length of each sub path have to be known -// 2. Locate and identify type of curve -// 3. Get t for the curve -// 4. Return curve.getPointAt(t') - -THREE.CurvePath.prototype.getPoint = function( t ) { - - var d = t * this.getLength(); - var curveLengths = this.getCurveLengths(); - var i = 0, diff, curve; - - // To think about boundaries points. - - while ( i < curveLengths.length ) { - - if ( curveLengths[ i ] >= d ) { - - diff = curveLengths[ i ] - d; - curve = this.curves[ i ]; - - var u = 1 - diff / curve.getLength(); - - return curve.getPointAt( u ); - - break; - } - - i ++; - - } - - return null; - - // loop where sum != 0, sum > d , sum+1 maxX ) maxX = p.x; - else if ( p.x < minX ) minX = p.x; - - if ( p.y > maxY ) maxY = p.y; - else if ( p.y < minY ) minY = p.y; - - if ( v3 ) { - - if ( p.z > maxZ ) maxZ = p.z; - else if ( p.z < minZ ) minZ = p.z; - - } - - sum.add( p ); - - } - - var ret = { - - minX: minX, - minY: minY, - maxX: maxX, - maxY: maxY - - }; - - if ( v3 ) { - - ret.maxZ = maxZ; - ret.minZ = minZ; - - } - - return ret; - -}; - -/************************************************************** - * Create Geometries Helpers - **************************************************************/ - -/// Generate geometry from path points (for Line or ParticleSystem objects) - -THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) { - - var pts = this.getPoints( divisions, true ); - return this.createGeometry( pts ); - -}; - -// Generate geometry from equidistance sampling along the path - -THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) { - - var pts = this.getSpacedPoints( divisions, true ); - return this.createGeometry( pts ); - -}; - -THREE.CurvePath.prototype.createGeometry = function( points ) { - - var geometry = new THREE.Geometry(); - - for ( var i = 0; i < points.length; i ++ ) { - - geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) ); - - } - - return geometry; - -}; - - -/************************************************************** - * Bend / Wrap Helper Methods - **************************************************************/ - -// Wrap path / Bend modifiers? - -THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) { - - this.bends.push( bendpath ); - -}; - -THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) { - - var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints - var i, il; - - if ( !bends ) { - - bends = this.bends; - - } - - for ( i = 0, il = bends.length; i < il; i ++ ) { - - oldPts = this.getWrapPoints( oldPts, bends[ i ] ); - - } - - return oldPts; - -}; - -THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) { - - var oldPts = this.getSpacedPoints( segments ); - - var i, il; - - if ( !bends ) { - - bends = this.bends; - - } - - for ( i = 0, il = bends.length; i < il; i ++ ) { - - oldPts = this.getWrapPoints( oldPts, bends[ i ] ); - - } - - return oldPts; - -}; - -// This returns getPoints() bend/wrapped around the contour of a path. -// Read http://www.planetclegg.com/projects/WarpingTextToSplines.html - -THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) { - - var bounds = this.getBoundingBox(); - - var i, il, p, oldX, oldY, xNorm; - - for ( i = 0, il = oldPts.length; i < il; i ++ ) { - - p = oldPts[ i ]; - - oldX = p.x; - oldY = p.y; - - xNorm = oldX / bounds.maxX; - - // If using actual distance, for length > path, requires line extrusions - //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance - - xNorm = path.getUtoTmapping( xNorm, oldX ); - - // check for out of bounds? - - var pathPt = path.getPoint( xNorm ); - var normal = path.getTangent( xNorm ); - normal.set( -normal.y, normal.x ).multiplyScalar( oldY ); - - p.x = pathPt.x + normal.x; - p.y = pathPt.y + normal.y; - - } - - return oldPts; - -}; - - -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Gyroscope = function () { - - THREE.Object3D.call( this ); - -}; - -THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) { - - this.matrixAutoUpdate && this.updateMatrix(); - - // update matrixWorld - - if ( this.matrixWorldNeedsUpdate || force ) { - - if ( this.parent ) { - - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - - this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld ); - this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject ); - - this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld ); - - - } else { - - this.matrixWorld.copy( this.matrix ); - - } - - - this.matrixWorldNeedsUpdate = false; - - force = true; - - } - - // update children - - for ( var i = 0, l = this.children.length; i < l; i ++ ) { - - this.children[ i ].updateMatrixWorld( force ); - - } - -}; - -THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3(); -THREE.Gyroscope.prototype.translationObject = new THREE.Vector3(); -THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion(); -THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion(); -THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3(); -THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3(); - - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Creates free form 2d path using series of points, lines or curves. - * - **/ - -THREE.Path = function ( points ) { - - THREE.CurvePath.call(this); - - this.actions = []; - - if ( points ) { - - this.fromPoints( points ); - - } - -}; - -THREE.Path.prototype = Object.create( THREE.CurvePath.prototype ); - -THREE.PathActions = { - - MOVE_TO: 'moveTo', - LINE_TO: 'lineTo', - QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve - BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve - CSPLINE_THRU: 'splineThru', // Catmull-rom spline - ARC: 'arc', // Circle - ELLIPSE: 'ellipse' -}; - -// TODO Clean up PATH API - -// Create path using straight lines to connect all points -// - vectors: array of Vector2 - -THREE.Path.prototype.fromPoints = function ( vectors ) { - - this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); - - for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) { - - this.lineTo( vectors[ v ].x, vectors[ v ].y ); - - }; - -}; - -// startPath() endPath()? - -THREE.Path.prototype.moveTo = function ( x, y ) { - - var args = Array.prototype.slice.call( arguments ); - this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } ); - -}; - -THREE.Path.prototype.lineTo = function ( x, y ) { - - var args = Array.prototype.slice.call( arguments ); - - var lastargs = this.actions[ this.actions.length - 1 ].args; - - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; - - var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) ); - this.curves.push( curve ); - - this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } ); - -}; - -THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) { - - var args = Array.prototype.slice.call( arguments ); - - var lastargs = this.actions[ this.actions.length - 1 ].args; - - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; - - var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ), - new THREE.Vector2( aCPx, aCPy ), - new THREE.Vector2( aX, aY ) ); - this.curves.push( curve ); - - this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } ); - -}; - -THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY ) { - - var args = Array.prototype.slice.call( arguments ); - - var lastargs = this.actions[ this.actions.length - 1 ].args; - - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; - - var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ), - new THREE.Vector2( aCP1x, aCP1y ), - new THREE.Vector2( aCP2x, aCP2y ), - new THREE.Vector2( aX, aY ) ); - this.curves.push( curve ); - - this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } ); - -}; - -THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) { - - var args = Array.prototype.slice.call( arguments ); - var lastargs = this.actions[ this.actions.length - 1 ].args; - - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; -//--- - var npts = [ new THREE.Vector2( x0, y0 ) ]; - Array.prototype.push.apply( npts, pts ); - - var curve = new THREE.SplineCurve( npts ); - this.curves.push( curve ); - - this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } ); - -}; - -// FUTURE: Change the API or follow canvas API? - -THREE.Path.prototype.arc = function ( aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise ) { - - var lastargs = this.actions[ this.actions.length - 1].args; - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; - - this.absarc(aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); - - }; - - THREE.Path.prototype.absarc = function ( aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise ) { - this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); - }; - -THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ) { - - var lastargs = this.actions[ this.actions.length - 1].args; - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; - - this.absellipse(aX + x0, aY + y0, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ); - - }; - - -THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ) { - - var args = Array.prototype.slice.call( arguments ); - var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ); - this.curves.push( curve ); - - var lastPoint = curve.getPoint(1); - args.push(lastPoint.x); - args.push(lastPoint.y); - - this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } ); - - }; - -THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) { - - if ( ! divisions ) divisions = 40; - - var points = []; - - for ( var i = 0; i < divisions; i ++ ) { - - points.push( this.getPoint( i / divisions ) ); - - //if( !this.getPoint( i / divisions ) ) throw "DIE"; - - } - - // if ( closedPath ) { - // - // points.push( points[ 0 ] ); - // - // } - - return points; - -}; - -/* Return an array of vectors based on contour of the path */ - -THREE.Path.prototype.getPoints = function( divisions, closedPath ) { - - if (this.useSpacedPoints) { - console.log('tata'); - return this.getSpacedPoints( divisions, closedPath ); - } - - divisions = divisions || 12; - - var points = []; - - var i, il, item, action, args; - var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0, - laste, j, - t, tx, ty; - - for ( i = 0, il = this.actions.length; i < il; i ++ ) { - - item = this.actions[ i ]; - - action = item.action; - args = item.args; - - switch( action ) { - - case THREE.PathActions.MOVE_TO: - - points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) ); - - break; - - case THREE.PathActions.LINE_TO: - - points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) ); - - break; - - case THREE.PathActions.QUADRATIC_CURVE_TO: - - cpx = args[ 2 ]; - cpy = args[ 3 ]; - - cpx1 = args[ 0 ]; - cpy1 = args[ 1 ]; - - if ( points.length > 0 ) { - - laste = points[ points.length - 1 ]; - - cpx0 = laste.x; - cpy0 = laste.y; - - } else { - - laste = this.actions[ i - 1 ].args; - - cpx0 = laste[ laste.length - 2 ]; - cpy0 = laste[ laste.length - 1 ]; - - } - - for ( j = 1; j <= divisions; j ++ ) { - - t = j / divisions; - - tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx ); - ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy ); - - points.push( new THREE.Vector2( tx, ty ) ); - - } - - break; - - case THREE.PathActions.BEZIER_CURVE_TO: - - cpx = args[ 4 ]; - cpy = args[ 5 ]; - - cpx1 = args[ 0 ]; - cpy1 = args[ 1 ]; - - cpx2 = args[ 2 ]; - cpy2 = args[ 3 ]; - - if ( points.length > 0 ) { - - laste = points[ points.length - 1 ]; - - cpx0 = laste.x; - cpy0 = laste.y; - - } else { - - laste = this.actions[ i - 1 ].args; - - cpx0 = laste[ laste.length - 2 ]; - cpy0 = laste[ laste.length - 1 ]; - - } - - - for ( j = 1; j <= divisions; j ++ ) { - - t = j / divisions; - - tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx ); - ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy ); - - points.push( new THREE.Vector2( tx, ty ) ); - - } - - break; - - case THREE.PathActions.CSPLINE_THRU: - - laste = this.actions[ i - 1 ].args; - - var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] ); - var spts = [ last ]; - - var n = divisions * args[ 0 ].length; - - spts = spts.concat( args[ 0 ] ); - - var spline = new THREE.SplineCurve( spts ); - - for ( j = 1; j <= n; j ++ ) { - - points.push( spline.getPointAt( j / n ) ) ; - - } - - break; - - case THREE.PathActions.ARC: - - var aX = args[ 0 ], aY = args[ 1 ], - aRadius = args[ 2 ], - aStartAngle = args[ 3 ], aEndAngle = args[ 4 ], - aClockwise = !!args[ 5 ]; - - var deltaAngle = aEndAngle - aStartAngle; - var angle; - var tdivisions = divisions * 2; - - for ( j = 1; j <= tdivisions; j ++ ) { - - t = j / tdivisions; - - if ( ! aClockwise ) { - - t = 1 - t; - - } - - angle = aStartAngle + t * deltaAngle; - - tx = aX + aRadius * Math.cos( angle ); - ty = aY + aRadius * Math.sin( angle ); - - //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty); - - points.push( new THREE.Vector2( tx, ty ) ); - - } - - //console.log(points); - - break; - - case THREE.PathActions.ELLIPSE: - - var aX = args[ 0 ], aY = args[ 1 ], - xRadius = args[ 2 ], - yRadius = args[ 3 ], - aStartAngle = args[ 4 ], aEndAngle = args[ 5 ], - aClockwise = !!args[ 6 ]; - - - var deltaAngle = aEndAngle - aStartAngle; - var angle; - var tdivisions = divisions * 2; - - for ( j = 1; j <= tdivisions; j ++ ) { - - t = j / tdivisions; - - if ( ! aClockwise ) { - - t = 1 - t; - - } - - angle = aStartAngle + t * deltaAngle; - - tx = aX + xRadius * Math.cos( angle ); - ty = aY + yRadius * Math.sin( angle ); - - //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty); - - points.push( new THREE.Vector2( tx, ty ) ); - - } - - //console.log(points); - - break; - - } // end switch - - } - - - - // Normalize to remove the closing point by default. - var lastPoint = points[ points.length - 1]; - var EPSILON = 0.0000000001; - if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON && - Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON) - points.splice( points.length - 1, 1); - if ( closedPath ) { - - points.push( points[ 0 ] ); - - } - - return points; - -}; - -// -// Breaks path into shapes -// -// Assumptions (if parameter isCCW==true the opposite holds): -// - solid shapes are defined clockwise (CW) -// - holes are defined counterclockwise (CCW) -// -// If parameter noHoles==true: -// - all subPaths are regarded as solid shapes -// - definition order CW/CCW has no relevance -// - -THREE.Path.prototype.toShapes = function( isCCW, noHoles ) { - - function extractSubpaths( inActions ) { - - var i, il, item, action, args; - - var subPaths = [], lastPath = new THREE.Path(); - - for ( i = 0, il = inActions.length; i < il; i ++ ) { - - item = inActions[ i ]; - - args = item.args; - action = item.action; - - if ( action == THREE.PathActions.MOVE_TO ) { - - if ( lastPath.actions.length != 0 ) { - - subPaths.push( lastPath ); - lastPath = new THREE.Path(); - - } - - } - - lastPath[ action ].apply( lastPath, args ); - - } - - if ( lastPath.actions.length != 0 ) { - - subPaths.push( lastPath ); - - } - - // console.log(subPaths); - - return subPaths; - } - - function toShapesNoHoles( inSubpaths ) { - - var shapes = []; - - for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) { - - var tmpPath = inSubpaths[ i ]; - - var tmpShape = new THREE.Shape(); - tmpShape.actions = tmpPath.actions; - tmpShape.curves = tmpPath.curves; - - shapes.push( tmpShape ); - } - - //console.log("shape", shapes); - - return shapes; - }; - - function isPointInsidePolygon( inPt, inPolygon ) { - var EPSILON = 0.0000000001; - - var polyLen = inPolygon.length; - - // inPt on polygon contour => immediate success or - // toggling of inside/outside at every single! intersection point of an edge - // with the horizontal line through inPt, left of inPt - // not counting lowerY endpoints of edges and whole edges on that line - var inside = false; - for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) { - var edgeLowPt = inPolygon[ p ]; - var edgeHighPt = inPolygon[ q ]; - - var edgeDx = edgeHighPt.x - edgeLowPt.x; - var edgeDy = edgeHighPt.y - edgeLowPt.y; - - if ( Math.abs(edgeDy) > EPSILON ) { // not parallel - if ( edgeDy < 0 ) { - edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx; - edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy; - } - if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; - - if ( inPt.y == edgeLowPt.y ) { - if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ? - // continue; // no intersection or edgeLowPt => doesn't count !!! - } else { - var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); - if ( perpEdge == 0 ) return true; // inPt is on contour ? - if ( perpEdge < 0 ) continue; - inside = !inside; // true intersection left of inPt - } - } else { // parallel or colinear - if ( inPt.y != edgeLowPt.y ) continue; // parallel - // egde lies on the same horizontal line as inPt - if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || - ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour ! - // continue; - } - } - - return inside; - } - - - var subPaths = extractSubpaths( this.actions ); - if ( subPaths.length == 0 ) return []; - - if ( noHoles === true ) return toShapesNoHoles( subPaths ); - - - var solid, tmpPath, tmpShape, shapes = []; - - if ( subPaths.length == 1) { - - tmpPath = subPaths[0]; - tmpShape = new THREE.Shape(); - tmpShape.actions = tmpPath.actions; - tmpShape.curves = tmpPath.curves; - shapes.push( tmpShape ); - return shapes; - - } - - var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() ); - holesFirst = isCCW ? !holesFirst : holesFirst; - - // console.log("Holes first", holesFirst); - - var betterShapeHoles = []; - var newShapes = []; - var newShapeHoles = []; - var mainIdx = 0; - var tmpPoints; - - newShapes[mainIdx] = undefined; - newShapeHoles[mainIdx] = []; - - var i, il; - - for ( i = 0, il = subPaths.length; i < il; i ++ ) { - - tmpPath = subPaths[ i ]; - tmpPoints = tmpPath.getPoints(); - solid = THREE.Shape.Utils.isClockWise( tmpPoints ); - solid = isCCW ? !solid : solid; - - if ( solid ) { - - if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++; - - newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints }; - newShapes[mainIdx].s.actions = tmpPath.actions; - newShapes[mainIdx].s.curves = tmpPath.curves; - - if ( holesFirst ) mainIdx++; - newShapeHoles[mainIdx] = []; - - //console.log('cw', i); - - } else { - - newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } ); - - //console.log('ccw', i); - - } - - } - - // only Holes? -> probably all Shapes with wrong orientation - if ( !newShapes[0] ) return toShapesNoHoles( subPaths ); - - - if ( newShapes.length > 1 ) { - var ambigious = false; - var toChange = []; - - for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) { - betterShapeHoles[sIdx] = []; - } - for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) { - var sh = newShapes[sIdx]; - var sho = newShapeHoles[sIdx]; - for (var hIdx = 0; hIdx < sho.length; hIdx++ ) { - var ho = sho[hIdx]; - var hole_unassigned = true; - for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) { - if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) { - if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); - if ( hole_unassigned ) { - hole_unassigned = false; - betterShapeHoles[s2Idx].push( ho ); - } else { - ambigious = true; - } - } - } - if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); } - } - } - // console.log("ambigious: ", ambigious); - if ( toChange.length > 0 ) { - // console.log("to change: ", toChange); - if (! ambigious) newShapeHoles = betterShapeHoles; - } - } - - var tmpHoles, j, jl; - for ( i = 0, il = newShapes.length; i < il; i ++ ) { - tmpShape = newShapes[i].s; - shapes.push( tmpShape ); - tmpHoles = newShapeHoles[i]; - for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) { - tmpShape.holes.push( tmpHoles[j].h ); - } - } - - //console.log("shape", shapes); - - return shapes; - -}; - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Defines a 2d shape plane using paths. - **/ - -// STEP 1 Create a path. -// STEP 2 Turn path into shape. -// STEP 3 ExtrudeGeometry takes in Shape/Shapes -// STEP 3a - Extract points from each shape, turn to vertices -// STEP 3b - Triangulate each shape, add faces. - -THREE.Shape = function () { - - THREE.Path.apply( this, arguments ); - this.holes = []; - -}; - -THREE.Shape.prototype = Object.create( THREE.Path.prototype ); - -// Convenience method to return ExtrudeGeometry - -THREE.Shape.prototype.extrude = function ( options ) { - - var extruded = new THREE.ExtrudeGeometry( this, options ); - return extruded; - -}; - -// Convenience method to return ShapeGeometry - -THREE.Shape.prototype.makeGeometry = function ( options ) { - - var geometry = new THREE.ShapeGeometry( this, options ); - return geometry; - -}; - -// Get points of holes - -THREE.Shape.prototype.getPointsHoles = function ( divisions ) { - - var i, il = this.holes.length, holesPts = []; - - for ( i = 0; i < il; i ++ ) { - - holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends ); - - } - - return holesPts; - -}; - -// Get points of holes (spaced by regular distance) - -THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) { - - var i, il = this.holes.length, holesPts = []; - - for ( i = 0; i < il; i ++ ) { - - holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends ); - - } - - return holesPts; - -}; - - -// Get points of shape and holes (keypoints based on segments parameter) - -THREE.Shape.prototype.extractAllPoints = function ( divisions ) { - - return { - - shape: this.getTransformedPoints( divisions ), - holes: this.getPointsHoles( divisions ) - - }; - -}; - -THREE.Shape.prototype.extractPoints = function ( divisions ) { - - if (this.useSpacedPoints) { - return this.extractAllSpacedPoints(divisions); - } - - return this.extractAllPoints(divisions); - -}; - -// -// THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) { -// -// return { -// -// shape: this.transform( bend, divisions ), -// holes: this.getPointsHoles( divisions, bend ) -// -// }; -// -// }; - -// Get points of shape and holes (spaced by regular distance) - -THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) { - - return { - - shape: this.getTransformedSpacedPoints( divisions ), - holes: this.getSpacedPointsHoles( divisions ) - - }; - -}; - -/************************************************************** - * Utils - **************************************************************/ - -THREE.Shape.Utils = { - - triangulateShape: function ( contour, holes ) { - - function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { - // inOtherPt needs to be colinear to the inSegment - if ( inSegPt1.x != inSegPt2.x ) { - if ( inSegPt1.x < inSegPt2.x ) { - return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); - } else { - return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); - } - } else { - if ( inSegPt1.y < inSegPt2.y ) { - return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); - } else { - return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); - } - } - } - - function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { - var EPSILON = 0.0000000001; - - var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; - var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; - - var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; - var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; - - var limit = seg1dy * seg2dx - seg1dx * seg2dy; - var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; - - if ( Math.abs(limit) > EPSILON ) { // not parallel - - var perpSeg2; - if ( limit > 0 ) { - if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; - } else { - if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; - } + var perpSeg2; + if ( limit > 0 ) { + if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; + perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; + if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; + } else { + if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; + perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; + if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; + } // i.e. to reduce rounding errors // intersection at endpoint of segment#1? @@ -30581,1742 +28147,1437 @@ THREE.Shape.Utils = { return [ inSeg1Pt1 ]; } if ( perpSeg2 == limit ) { - if ( ( inExcludeAdjacentSegs ) && - ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return []; - return [ inSeg1Pt2 ]; - } - // intersection at endpoint of segment#2? - if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ]; - if ( perpSeg1 == limit ) return [ inSeg2Pt2 ]; - - // return real intersection point - var factorSeg1 = perpSeg2 / limit; - return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, - y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; - - } else { // parallel or colinear - if ( ( perpSeg1 != 0 ) || - ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return []; - - // they are collinear or degenerate - var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point? - var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point? - // both segments are points - if ( seg1Pt && seg2Pt ) { - if ( (inSeg1Pt1.x != inSeg2Pt1.x) || - (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points - return [ inSeg1Pt1 ]; // they are the same point - } - // segment#1 is a single point - if ( seg1Pt ) { - if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 - return [ inSeg1Pt1 ]; - } - // segment#2 is a single point - if ( seg2Pt ) { - if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 - return [ inSeg2Pt1 ]; - } - - // they are collinear segments, which might overlap - var seg1min, seg1max, seg1minVal, seg1maxVal; - var seg2min, seg2max, seg2minVal, seg2maxVal; - if (seg1dx != 0) { // the segments are NOT on a vertical line - if ( inSeg1Pt1.x < inSeg1Pt2.x ) { - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; - } else { - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; - } - if ( inSeg2Pt1.x < inSeg2Pt2.x ) { - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; - } else { - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; - } - } else { // the segments are on a vertical line - if ( inSeg1Pt1.y < inSeg1Pt2.y ) { - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; - } else { - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; - } - if ( inSeg2Pt1.y < inSeg2Pt2.y ) { - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; - } else { - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; - } - } - if ( seg1minVal <= seg2minVal ) { - if ( seg1maxVal < seg2minVal ) return []; - if ( seg1maxVal == seg2minVal ) { - if ( inExcludeAdjacentSegs ) return []; - return [ seg2min ]; - } - if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; - return [ seg2min, seg2max ]; - } else { - if ( seg1minVal > seg2maxVal ) return []; - if ( seg1minVal == seg2maxVal ) { - if ( inExcludeAdjacentSegs ) return []; - return [ seg1min ]; - } - if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; - return [ seg1min, seg2max ]; - } - } - } - - function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { - // The order of legs is important - - var EPSILON = 0.0000000001; - - // translation of all points, so that Vertex is at (0,0) - var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y; - var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y; - var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y; - - // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. - var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; - var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; - - if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg. - - var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; - // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); - - if ( from2toAngle > 0 ) { // main angle < 180 deg. - return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); - } else { // main angle > 180 deg. - return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); - } - } else { // angle == 180 deg. - // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); - return ( from2otherAngle > 0 ); - } - } - - - function removeHoles( contour, holes ) { - - var shape = contour.concat(); // work on this shape - var hole; - - function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { - // Check if hole point lies within angle around shape point - var lastShapeIdx = shape.length - 1; - - var prevShapeIdx = inShapeIdx - 1; - if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; - - var nextShapeIdx = inShapeIdx + 1; - if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; - - var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] ); - if (! insideAngle ) { - // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); - return false; - } - - // Check if shape point lies within angle around hole point - var lastHoleIdx = hole.length - 1; - - var prevHoleIdx = inHoleIdx - 1; - if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; - - var nextHoleIdx = inHoleIdx + 1; - if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; - - insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] ); - if (! insideAngle ) { - // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); - return false; - } - - return true; - } - - function intersectsShapeEdge( inShapePt, inHolePt ) { - // checks for intersections with shape edges - var sIdx, nextIdx, intersection; - for ( sIdx = 0; sIdx < shape.length; sIdx++ ) { - nextIdx = sIdx+1; nextIdx %= shape.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true ); - if ( intersection.length > 0 ) return true; - } - - return false; - } - - var indepHoles = []; - - function intersectsHoleEdge( inShapePt, inHolePt ) { - // checks for intersections with hole edges - var ihIdx, chkHole, - hIdx, nextIdx, intersection; - for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) { - chkHole = holes[indepHoles[ihIdx]]; - for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) { - nextIdx = hIdx+1; nextIdx %= chkHole.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true ); - if ( intersection.length > 0 ) return true; - } - } - return false; - } - - var holeIndex, shapeIndex, - shapePt, holePt, - holeIdx, cutKey, failedCuts = [], - tmpShape1, tmpShape2, - tmpHole1, tmpHole2; - - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - - indepHoles.push( h ); - - } - - var minShapeIndex = 0; - var counter = indepHoles.length * 2; - while ( indepHoles.length > 0 ) { - counter --; - if ( counter < 0 ) { - console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); - break; - } - - // search for shape-vertex and hole-vertex, - // which can be connected without intersections - for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex++ ) { - - shapePt = shape[ shapeIndex ]; - holeIndex = -1; - - // search for hole which can be reached without intersections - for ( var h = 0; h < indepHoles.length; h ++ ) { - holeIdx = indepHoles[h]; - - // prevent multiple checks - cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; - if ( failedCuts[cutKey] !== undefined ) continue; - - hole = holes[holeIdx]; - for ( var h2 = 0; h2 < hole.length; h2 ++ ) { - holePt = hole[ h2 ]; - if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; - if ( intersectsShapeEdge( shapePt, holePt ) ) continue; - if ( intersectsHoleEdge( shapePt, holePt ) ) continue; - - holeIndex = h2; - indepHoles.splice(h,1); - - tmpShape1 = shape.slice( 0, shapeIndex+1 ); - tmpShape2 = shape.slice( shapeIndex ); - tmpHole1 = hole.slice( holeIndex ); - tmpHole2 = hole.slice( 0, holeIndex+1 ); - - shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); - - minShapeIndex = shapeIndex; - - // Debug only, to show the selected cuts - // glob_CutLines.push( [ shapePt, holePt ] ); - - break; - } - if ( holeIndex >= 0 ) break; // hole-vertex found - - failedCuts[cutKey] = true; // remember failure - } - if ( holeIndex >= 0 ) break; // hole-vertex found + if ( ( inExcludeAdjacentSegs ) && + ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return []; + return [ inSeg1Pt2 ]; } - } - - return shape; /* shape with no holes */ - } - - - var i, il, f, face, - key, index, - allPointsMap = {}; - - // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first. - - var allpoints = contour.concat(); - - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - - Array.prototype.push.apply( allpoints, holes[h] ); - - } - - //console.log( "allpoints",allpoints, allpoints.length ); - - // prepare all points map - - for ( i = 0, il = allpoints.length; i < il; i ++ ) { - - key = allpoints[ i ].x + ":" + allpoints[ i ].y; - - if ( allPointsMap[ key ] !== undefined ) { - - console.log( "Duplicate point", key ); - - } - - allPointsMap[ key ] = i; - - } - - // remove holes by cutting paths to holes and adding them to the shape - var shapeWithoutHoles = removeHoles( contour, holes ); - - var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape - //console.log( "triangles",triangles, triangles.length ); - - // check all face vertices against all points map - - for ( i = 0, il = triangles.length; i < il; i ++ ) { - - face = triangles[ i ]; - - for ( f = 0; f < 3; f ++ ) { - - key = face[ f ].x + ":" + face[ f ].y; - - index = allPointsMap[ key ]; + // intersection at endpoint of segment#2? + if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ]; + if ( perpSeg1 == limit ) return [ inSeg2Pt2 ]; - if ( index !== undefined ) { + // return real intersection point + var factorSeg1 = perpSeg2 / limit; + return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, + y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; - face[ f ] = index; + } else { // parallel or colinear + if ( ( perpSeg1 != 0 ) || + ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return []; + // they are collinear or degenerate + var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point? + var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point? + // both segments are points + if ( seg1Pt && seg2Pt ) { + if ( (inSeg1Pt1.x != inSeg2Pt1.x) || + (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points + return [ inSeg1Pt1 ]; // they are the same point + } + // segment#1 is a single point + if ( seg1Pt ) { + if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 + return [ inSeg1Pt1 ]; + } + // segment#2 is a single point + if ( seg2Pt ) { + if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 + return [ inSeg2Pt1 ]; } - } - - } - - return triangles.concat(); - - }, - - isClockWise: function ( pts ) { - - return THREE.FontUtils.Triangulate.area( pts ) < 0; - - }, - - // Bezier Curves formulas obtained from - // http://en.wikipedia.org/wiki/B%C3%A9zier_curve - - // Quad Bezier Functions - - b2p0: function ( t, p ) { - - var k = 1 - t; - return k * k * p; - - }, - - b2p1: function ( t, p ) { - - return 2 * ( 1 - t ) * t * p; - - }, - - b2p2: function ( t, p ) { - - return t * t * p; - - }, - - b2: function ( t, p0, p1, p2 ) { - - return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 ); - - }, - - // Cubic Bezier Functions - - b3p0: function ( t, p ) { - - var k = 1 - t; - return k * k * k * p; - - }, - - b3p1: function ( t, p ) { - - var k = 1 - t; - return 3 * k * k * t * p; - - }, - - b3p2: function ( t, p ) { - - var k = 1 - t; - return 3 * k * t * t * p; - - }, - - b3p3: function ( t, p ) { - - return t * t * t * p; - - }, - - b3: function ( t, p0, p1, p2, p3 ) { - - return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 ); - - } - -}; - - -/************************************************************** - * Line - **************************************************************/ - -THREE.LineCurve = function ( v1, v2 ) { - - this.v1 = v1; - this.v2 = v2; - -}; - -THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype ); - -THREE.LineCurve.prototype.getPoint = function ( t ) { - - var point = this.v2.clone().sub(this.v1); - point.multiplyScalar( t ).add( this.v1 ); - - return point; - -}; - -// Line curve is linear, so we can overwrite default getPointAt - -THREE.LineCurve.prototype.getPointAt = function ( u ) { - - return this.getPoint( u ); - -}; - -THREE.LineCurve.prototype.getTangent = function( t ) { - - var tangent = this.v2.clone().sub(this.v1); - - return tangent.normalize(); + // they are collinear segments, which might overlap + var seg1min, seg1max, seg1minVal, seg1maxVal; + var seg2min, seg2max, seg2minVal, seg2maxVal; + if (seg1dx != 0) { // the segments are NOT on a vertical line + if ( inSeg1Pt1.x < inSeg1Pt2.x ) { + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; + } else { + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; + } + if ( inSeg2Pt1.x < inSeg2Pt2.x ) { + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; + } else { + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; + } + } else { // the segments are on a vertical line + if ( inSeg1Pt1.y < inSeg1Pt2.y ) { + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; + } else { + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; + } + if ( inSeg2Pt1.y < inSeg2Pt2.y ) { + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; + } else { + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; + } + } + if ( seg1minVal <= seg2minVal ) { + if ( seg1maxVal < seg2minVal ) return []; + if ( seg1maxVal == seg2minVal ) { + if ( inExcludeAdjacentSegs ) return []; + return [ seg2min ]; + } + if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; + return [ seg2min, seg2max ]; + } else { + if ( seg1minVal > seg2maxVal ) return []; + if ( seg1minVal == seg2maxVal ) { + if ( inExcludeAdjacentSegs ) return []; + return [ seg1min ]; + } + if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; + return [ seg1min, seg2max ]; + } + } + } -}; -/************************************************************** - * Quadratic Bezier curve - **************************************************************/ + function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { + // The order of legs is important + var EPSILON = 0.0000000001; -THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) { + // translation of all points, so that Vertex is at (0,0) + var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y; + var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y; + var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. + var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; + var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; -}; + if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg. -THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype ); + var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; + // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); + if ( from2toAngle > 0 ) { // main angle < 180 deg. + return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); + } else { // main angle > 180 deg. + return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); + } + } else { // angle == 180 deg. + // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); + return ( from2otherAngle > 0 ); + } + } -THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) { - var tx, ty; + function removeHoles( contour, holes ) { - tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x ); - ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y ); + var shape = contour.concat(); // work on this shape + var hole; - return new THREE.Vector2( tx, ty ); + function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { + // Check if hole point lies within angle around shape point + var lastShapeIdx = shape.length - 1; -}; + var prevShapeIdx = inShapeIdx - 1; + if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; + var nextShapeIdx = inShapeIdx + 1; + if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; -THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) { + var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] ); + if (! insideAngle ) { + // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); + return false; + } - var tx, ty; + // Check if shape point lies within angle around hole point + var lastHoleIdx = hole.length - 1; - tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ); - ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ); + var prevHoleIdx = inHoleIdx - 1; + if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; - // returns unit vector + var nextHoleIdx = inHoleIdx + 1; + if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; - var tangent = new THREE.Vector2( tx, ty ); - tangent.normalize(); + insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] ); + if (! insideAngle ) { + // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); + return false; + } - return tangent; + return true; + } -}; -/************************************************************** - * Cubic Bezier curve - **************************************************************/ + function intersectsShapeEdge( inShapePt, inHolePt ) { + // checks for intersections with shape edges + var sIdx, nextIdx, intersection; + for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) { + nextIdx = sIdx+1; nextIdx %= shape.length; + intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true ); + if ( intersection.length > 0 ) return true; + } -THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) { + return false; + } - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + var indepHoles = []; -}; + function intersectsHoleEdge( inShapePt, inHolePt ) { + // checks for intersections with hole edges + var ihIdx, chkHole, + hIdx, nextIdx, intersection; + for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) { + chkHole = holes[indepHoles[ihIdx]]; + for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) { + nextIdx = hIdx+1; nextIdx %= chkHole.length; + intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true ); + if ( intersection.length > 0 ) return true; + } + } + return false; + } -THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype ); + var holeIndex, shapeIndex, + shapePt, holePt, + holeIdx, cutKey, failedCuts = [], + tmpShape1, tmpShape2, + tmpHole1, tmpHole2; -THREE.CubicBezierCurve.prototype.getPoint = function ( t ) { + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - var tx, ty; + indepHoles.push( h ); - tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); - ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); + } - return new THREE.Vector2( tx, ty ); + var minShapeIndex = 0; + var counter = indepHoles.length * 2; + while ( indepHoles.length > 0 ) { + counter --; + if ( counter < 0 ) { + console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); + break; + } -}; + // search for shape-vertex and hole-vertex, + // which can be connected without intersections + for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) { -THREE.CubicBezierCurve.prototype.getTangent = function( t ) { + shapePt = shape[ shapeIndex ]; + holeIndex = - 1; - var tx, ty; + // search for hole which can be reached without intersections + for ( var h = 0; h < indepHoles.length; h ++ ) { + holeIdx = indepHoles[h]; - tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); - ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); + // prevent multiple checks + cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; + if ( failedCuts[cutKey] !== undefined ) continue; - var tangent = new THREE.Vector2( tx, ty ); - tangent.normalize(); + hole = holes[holeIdx]; + for ( var h2 = 0; h2 < hole.length; h2 ++ ) { + holePt = hole[ h2 ]; + if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; + if ( intersectsShapeEdge( shapePt, holePt ) ) continue; + if ( intersectsHoleEdge( shapePt, holePt ) ) continue; - return tangent; + holeIndex = h2; + indepHoles.splice(h,1); -}; -/************************************************************** - * Spline curve - **************************************************************/ + tmpShape1 = shape.slice( 0, shapeIndex+1 ); + tmpShape2 = shape.slice( shapeIndex ); + tmpHole1 = hole.slice( holeIndex ); + tmpHole2 = hole.slice( 0, holeIndex+1 ); -THREE.SplineCurve = function ( points /* array of Vector2 */ ) { + shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); - this.points = (points == undefined) ? [] : points; + minShapeIndex = shapeIndex; -}; + // Debug only, to show the selected cuts + // glob_CutLines.push( [ shapePt, holePt ] ); -THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype ); + break; + } + if ( holeIndex >= 0 ) break; // hole-vertex found -THREE.SplineCurve.prototype.getPoint = function ( t ) { + failedCuts[cutKey] = true; // remember failure + } + if ( holeIndex >= 0 ) break; // hole-vertex found + } + } - var v = new THREE.Vector2(); - var c = []; - var points = this.points, point, intPoint, weight; - point = ( points.length - 1 ) * t; + return shape; /* shape with no holes */ + } - intPoint = Math.floor( point ); - weight = point - intPoint; - c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1; - c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2; + var i, il, f, face, + key, index, + allPointsMap = {}; - v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight ); - v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight ); + // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first. - return v; + var allpoints = contour.concat(); -}; -/************************************************************** - * Ellipse curve - **************************************************************/ + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { -THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) { + Array.prototype.push.apply( allpoints, holes[h] ); - this.aX = aX; - this.aY = aY; + } - this.xRadius = xRadius; - this.yRadius = yRadius; + //console.log( "allpoints",allpoints, allpoints.length ); - this.aStartAngle = aStartAngle; - this.aEndAngle = aEndAngle; + // prepare all points map - this.aClockwise = aClockwise; + for ( i = 0, il = allpoints.length; i < il; i ++ ) { -}; + key = allpoints[ i ].x + ":" + allpoints[ i ].y; -THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype ); + if ( allPointsMap[ key ] !== undefined ) { -THREE.EllipseCurve.prototype.getPoint = function ( t ) { + console.log( "Duplicate point", key ); - var angle; - var deltaAngle = this.aEndAngle - this.aStartAngle; + } - if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2; - if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2; + allPointsMap[ key ] = i; - if ( this.aClockwise === true ) { + } - angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle ); + // remove holes by cutting paths to holes and adding them to the shape + var shapeWithoutHoles = removeHoles( contour, holes ); - } else { + var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape + //console.log( "triangles",triangles, triangles.length ); - angle = this.aStartAngle + t * deltaAngle; + // check all face vertices against all points map - } + for ( i = 0, il = triangles.length; i < il; i ++ ) { - var tx = this.aX + this.xRadius * Math.cos( angle ); - var ty = this.aY + this.yRadius * Math.sin( angle ); + face = triangles[ i ]; - return new THREE.Vector2( tx, ty ); + for ( f = 0; f < 3; f ++ ) { -}; + key = face[ f ].x + ":" + face[ f ].y; -/************************************************************** - * Arc curve - **************************************************************/ + index = allPointsMap[ key ]; -THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + if ( index !== undefined ) { - THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); -}; + face[ f ] = index; -THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype ); -/************************************************************** - * Line3D - **************************************************************/ + } -THREE.LineCurve3 = THREE.Curve.create( + } - function ( v1, v2 ) { + } - this.v1 = v1; - this.v2 = v2; + return triangles.concat(); }, - function ( t ) { - - var r = new THREE.Vector3(); + isClockWise: function ( pts ) { + return THREE.FontUtils.Triangulate.area( pts ) < 0; - r.subVectors( this.v2, this.v1 ); // diff - r.multiplyScalar( t ); - r.add( this.v1 ); + }, - return r; + // Bezier Curves formulas obtained from + // http://en.wikipedia.org/wiki/B%C3%A9zier_curve - } + // Quad Bezier Functions -); + b2p0: function ( t, p ) { -/************************************************************** - * Quadratic Bezier 3D curve - **************************************************************/ + var k = 1 - t; + return k * k * p; -THREE.QuadraticBezierCurve3 = THREE.Curve.create( + }, - function ( v0, v1, v2 ) { + b2p1: function ( t, p ) { - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + return 2 * ( 1 - t ) * t * p; }, - function ( t ) { + b2p2: function ( t, p ) { - var tx, ty, tz; + return t * t * p; - tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x ); - ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y ); - tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z ); + }, - return new THREE.Vector3( tx, ty, tz ); + b2: function ( t, p0, p1, p2 ) { - } + return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 ); -); -/************************************************************** - * Cubic Bezier 3D curve - **************************************************************/ + }, -THREE.CubicBezierCurve3 = THREE.Curve.create( + // Cubic Bezier Functions - function ( v0, v1, v2, v3 ) { + b3p0: function ( t, p ) { - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + var k = 1 - t; + return k * k * k * p; }, - function ( t ) { - - var tx, ty, tz; - - tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); - ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); - tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ); + b3p1: function ( t, p ) { - return new THREE.Vector3( tx, ty, tz ); + var k = 1 - t; + return 3 * k * k * t * p; - } + }, -); -/************************************************************** - * Spline 3D curve - **************************************************************/ + b3p2: function ( t, p ) { + var k = 1 - t; + return 3 * k * t * t * p; -THREE.SplineCurve3 = THREE.Curve.create( + }, - function ( points /* array of Vector3 */) { + b3p3: function ( t, p ) { - this.points = (points == undefined) ? [] : points; + return t * t * t * p; }, - function ( t ) { + b3: function ( t, p0, p1, p2, p3 ) { - var v = new THREE.Vector3(); - var c = []; - var points = this.points, point, intPoint, weight; - point = ( points.length - 1 ) * t; + return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 ); - intPoint = Math.floor( point ); - weight = point - intPoint; + } - c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1; - c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2; +}; - var pt0 = points[ c[0] ], - pt1 = points[ c[1] ], - pt2 = points[ c[2] ], - pt3 = points[ c[3] ]; - v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight); - v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight); - v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight); +// File:src/extras/curves/LineCurve.js - return v; +/************************************************************** + * Line + **************************************************************/ - } +THREE.LineCurve = function ( v1, v2 ) { -); + this.v1 = v1; + this.v2 = v2; +}; -// THREE.SplineCurve3.prototype.getTangent = function(t) { -// var v = new THREE.Vector3(); -// var c = []; -// var points = this.points, point, intPoint, weight; -// point = ( points.length - 1 ) * t; +THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype ); -// intPoint = Math.floor( point ); -// weight = point - intPoint; +THREE.LineCurve.prototype.getPoint = function ( t ) { -// c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1; -// c[ 1 ] = intPoint; -// c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1; -// c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2; + var point = this.v2.clone().sub(this.v1); + point.multiplyScalar( t ).add( this.v1 ); -// var pt0 = points[ c[0] ], -// pt1 = points[ c[1] ], -// pt2 = points[ c[2] ], -// pt3 = points[ c[3] ]; + return point; -// // t = weight; -// v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x ); -// v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y ); -// v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z ); +}; -// return v; +// Line curve is linear, so we can overwrite default getPointAt -// } -/************************************************************** - * Closed Spline 3D curve - **************************************************************/ +THREE.LineCurve.prototype.getPointAt = function ( u ) { + return this.getPoint( u ); -THREE.ClosedSplineCurve3 = THREE.Curve.create( +}; - function ( points /* array of Vector3 */) { +THREE.LineCurve.prototype.getTangent = function( t ) { - this.points = (points == undefined) ? [] : points; + var tangent = this.v2.clone().sub(this.v1); - }, + return tangent.normalize(); - function ( t ) { +}; - var v = new THREE.Vector3(); - var c = []; - var points = this.points, point, intPoint, weight; - point = ( points.length - 0 ) * t; - // This needs to be from 0-length +1 +// File:src/extras/curves/QuadraticBezierCurve.js - intPoint = Math.floor( point ); - weight = point - intPoint; +/************************************************************** + * Quadratic Bezier curve + **************************************************************/ - intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; - c[ 0 ] = ( intPoint - 1 ) % points.length; - c[ 1 ] = ( intPoint ) % points.length; - c[ 2 ] = ( intPoint + 1 ) % points.length; - c[ 3 ] = ( intPoint + 2 ) % points.length; - v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight ); - v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight ); - v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight ); +THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) { - return v; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - } +}; -); -/** - * @author mikael emtinger / http://gomo.se/ - */ +THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.AnimationHandler = ( function () { - var playing = []; - var library = {}; - var that = {}; +THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) { - that.update = function ( deltaTimeMS ) { + var tx, ty; - for ( var i = 0; i < playing.length; i ++ ) { + tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x ); + ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y ); - playing[ i ].update( deltaTimeMS ); + return new THREE.Vector2( tx, ty ); - } +}; - }; - that.addToUpdate = function ( animation ) { +THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) { - if ( playing.indexOf( animation ) === -1 ) { + var tx, ty; - playing.push( animation ); + tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ); + ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ); - } + // returns unit vector - }; + var tangent = new THREE.Vector2( tx, ty ); + tangent.normalize(); + + return tangent; - that.removeFromUpdate = function ( animation ) { +}; - var index = playing.indexOf( animation ); +// File:src/extras/curves/CubicBezierCurve.js - if ( index !== -1 ) { +/************************************************************** + * Cubic Bezier curve + **************************************************************/ - playing.splice( index, 1 ); +THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) { - } + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - }; +}; - that.add = function ( data ) { +THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype ); - if ( library[ data.name ] !== undefined ) { +THREE.CubicBezierCurve.prototype.getPoint = function ( t ) { - console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." ); + var tx, ty; - } + tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); + ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); - library[ data.name ] = data; - initData( data ); + return new THREE.Vector2( tx, ty ); - }; +}; - that.remove = function ( name ) { +THREE.CubicBezierCurve.prototype.getTangent = function( t ) { - if ( library[ name ] === undefined ) { + var tx, ty; - console.log( "THREE.AnimationHandler.add: Warning! " + name + " doesn't exists in library. Doing nothing." ); + tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); + ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); - } + var tangent = new THREE.Vector2( tx, ty ); + tangent.normalize(); - library[ name ] = undefined; + return tangent; - }; +}; - that.get = function ( name ) { +// File:src/extras/curves/SplineCurve.js - if ( typeof name === "string" ) { +/************************************************************** + * Spline curve + **************************************************************/ - if ( library[ name ] ) { +THREE.SplineCurve = function ( points /* array of Vector2 */ ) { - return library[ name ]; + this.points = (points == undefined) ? [] : points; - } else { +}; - return null; +THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype ); - } +THREE.SplineCurve.prototype.getPoint = function ( t ) { - } else { + var v = new THREE.Vector2(); + var c = []; + var points = this.points, point, intPoint, weight; + point = ( points.length - 1 ) * t; - // todo: add simple tween library + intPoint = Math.floor( point ); + weight = point - intPoint; - } + c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1; + c[ 1 ] = intPoint; + c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1; + c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2; - }; + v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight ); + v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight ); - that.parse = function ( root ) { + return v; - // setup hierarchy +}; - var hierarchy = []; +// File:src/extras/curves/EllipseCurve.js - if ( root instanceof THREE.SkinnedMesh ) { +/************************************************************** + * Ellipse curve + **************************************************************/ - for ( var b = 0; b < root.skeleton.bones.length; b++ ) { +THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) { - hierarchy.push( root.skeleton.bones[ b ] ); + this.aX = aX; + this.aY = aY; - } + this.xRadius = xRadius; + this.yRadius = yRadius; - } else { + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; - parseRecurseHierarchy( root, hierarchy ); + this.aClockwise = aClockwise; - } +}; - return hierarchy; +THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype ); - }; +THREE.EllipseCurve.prototype.getPoint = function ( t ) { - var parseRecurseHierarchy = function ( root, hierarchy ) { + var angle; + var deltaAngle = this.aEndAngle - this.aStartAngle; - hierarchy.push( root ); + if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2; + if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2; - for ( var c = 0; c < root.children.length; c++ ) - parseRecurseHierarchy( root.children[ c ], hierarchy ); + if ( this.aClockwise === true ) { - } + angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle ); - var initData = function ( data ) { + } else { - if ( data.initialized === true ) - return; + angle = this.aStartAngle + t * deltaAngle; + } - // loop through all keys + var tx = this.aX + this.xRadius * Math.cos( angle ); + var ty = this.aY + this.yRadius * Math.sin( angle ); - for ( var h = 0; h < data.hierarchy.length; h ++ ) { + return new THREE.Vector2( tx, ty ); - for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { +}; - // remove minus times +// File:src/extras/curves/ArcCurve.js - if ( data.hierarchy[ h ].keys[ k ].time < 0 ) { +/************************************************************** + * Arc curve + **************************************************************/ - data.hierarchy[ h ].keys[ k ].time = 0; +THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - } + THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); +}; - // create quaternions +THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype ); - if ( data.hierarchy[ h ].keys[ k ].rot !== undefined && - !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) { +// File:src/extras/curves/LineCurve3.js - var quat = data.hierarchy[ h ].keys[ k ].rot; - data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat ); +/************************************************************** + * Line3D + **************************************************************/ - } +THREE.LineCurve3 = THREE.Curve.create( - } + function ( v1, v2 ) { - // prepare morph target keys + this.v1 = v1; + this.v2 = v2; - if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) { + }, - // get all used + function ( t ) { - var usedMorphTargets = {}; + var r = new THREE.Vector3(); - for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { - for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) { + r.subVectors( this.v2, this.v1 ); // diff + r.multiplyScalar( t ); + r.add( this.v1 ); - var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ]; - usedMorphTargets[ morphTargetName ] = -1; + return r; - } + } - } +); - data.hierarchy[ h ].usedMorphTargets = usedMorphTargets; +// File:src/extras/curves/QuadraticBezierCurve3.js +/************************************************************** + * Quadratic Bezier 3D curve + **************************************************************/ - // set all used on all frames +THREE.QuadraticBezierCurve3 = THREE.Curve.create( - for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { + function ( v0, v1, v2 ) { - var influences = {}; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - for ( var morphTargetName in usedMorphTargets ) { + }, - for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) { + function ( t ) { - if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) { + var tx, ty, tz; - influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ]; - break; + tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x ); + ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y ); + tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z ); - } + return new THREE.Vector3( tx, ty, tz ); - } + } - if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) { +); - influences[ morphTargetName ] = 0; +// File:src/extras/curves/CubicBezierCurve3.js - } +/************************************************************** + * Cubic Bezier 3D curve + **************************************************************/ - } +THREE.CubicBezierCurve3 = THREE.Curve.create( - data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences; + function ( v0, v1, v2, v3 ) { - } + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - } + }, + function ( t ) { - // remove all keys that are on the same time + var tx, ty, tz; - for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) { + tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); + ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); + tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ); - if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) { + return new THREE.Vector3( tx, ty, tz ); - data.hierarchy[ h ].keys.splice( k, 1 ); - k --; + } - } +); - } +// File:src/extras/curves/SplineCurve3.js +/************************************************************** + * Spline 3D curve + **************************************************************/ - // set index - for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { +THREE.SplineCurve3 = THREE.Curve.create( - data.hierarchy[ h ].keys[ k ].index = k; + function ( points /* array of Vector3 */) { - } + this.points = (points == undefined) ? [] : points; - } + }, - data.initialized = true; + function ( t ) { - }; + var v = new THREE.Vector3(); + var c = []; + var points = this.points, point, intPoint, weight; + point = ( points.length - 1 ) * t; + intPoint = Math.floor( point ); + weight = point - intPoint; - // interpolation types + c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1; + c[ 1 ] = intPoint; + c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1; + c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2; - that.LINEAR = 0; - that.CATMULLROM = 1; - that.CATMULLROM_FORWARD = 2; + var pt0 = points[ c[0] ], + pt1 = points[ c[1] ], + pt2 = points[ c[2] ], + pt3 = points[ c[3] ]; - return that; + v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight); + v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight); + v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight); -}() ); + return v; -/** - * @author mikael emtinger / http://gomo.se/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + } -THREE.Animation = function ( root, name ) { +); - this.root = root; - this.data = THREE.AnimationHandler.get( name ); - this.hierarchy = THREE.AnimationHandler.parse( root ); - this.currentTime = 0; - this.timeScale = 1; +// THREE.SplineCurve3.prototype.getTangent = function(t) { +// var v = new THREE.Vector3(); +// var c = []; +// var points = this.points, point, intPoint, weight; +// point = ( points.length - 1 ) * t; - this.isPlaying = false; - this.isPaused = true; - this.loop = true; - this.weight = 0; +// intPoint = Math.floor( point ); +// weight = point - intPoint; - this.interpolationType = THREE.AnimationHandler.LINEAR; +// c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1; +// c[ 1 ] = intPoint; +// c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1; +// c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2; -}; +// var pt0 = points[ c[0] ], +// pt1 = points[ c[1] ], +// pt2 = points[ c[2] ], +// pt3 = points[ c[3] ]; +// // t = weight; +// v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x ); +// v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y ); +// v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z ); -THREE.Animation.prototype.keyTypes = [ "pos", "rot", "scl" ]; +// return v; +// } -THREE.Animation.prototype.play = function ( startTime, weight ) { +// File:src/extras/curves/ClosedSplineCurve3.js - this.currentTime = startTime !== undefined ? startTime : 0; - this.weight = weight !== undefined ? weight: 1; +/************************************************************** + * Closed Spline 3D curve + **************************************************************/ - this.isPlaying = true; - this.isPaused = false; - this.reset(); +THREE.ClosedSplineCurve3 = THREE.Curve.create( - THREE.AnimationHandler.addToUpdate( this ); + function ( points /* array of Vector3 */) { -}; + this.points = (points == undefined) ? [] : points; + }, -THREE.Animation.prototype.pause = function() { + function ( t ) { - if ( this.isPaused === true ) { + var v = new THREE.Vector3(); + var c = []; + var points = this.points, point, intPoint, weight; + point = ( points.length - 0 ) * t; + // This needs to be from 0-length +1 - THREE.AnimationHandler.addToUpdate( this ); + intPoint = Math.floor( point ); + weight = point - intPoint; - } else { + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; + c[ 0 ] = ( intPoint - 1 ) % points.length; + c[ 1 ] = ( intPoint ) % points.length; + c[ 2 ] = ( intPoint + 1 ) % points.length; + c[ 3 ] = ( intPoint + 2 ) % points.length; - THREE.AnimationHandler.removeFromUpdate( this ); + v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight ); + v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight ); + v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight ); - } + return v; - this.isPaused = !this.isPaused; + } -}; +); +// File:src/extras/animation/AnimationHandler.js -THREE.Animation.prototype.stop = function() { +/** + * @author mikael emtinger / http://gomo.se/ + */ - this.isPlaying = false; - this.isPaused = false; - THREE.AnimationHandler.removeFromUpdate( this ); +THREE.AnimationHandler = { -}; + LINEAR: 0, + CATMULLROM: 1, + CATMULLROM_FORWARD: 2, -THREE.Animation.prototype.reset = function () { + // - for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { + add: function () { console.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); }, + get: function () { console.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); }, + remove: function () { console.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); }, - var object = this.hierarchy[ h ]; + // - object.matrixAutoUpdate = true; + animations: [], - if ( object.animationCache === undefined ) { + init: function ( data ) { - object.animationCache = {}; + if ( data.initialized === true ) return; - } + // loop through all keys - if ( object.animationCache[this.data.name] === undefined ) { + for ( var h = 0; h < data.hierarchy.length; h ++ ) { - object.animationCache[this.data.name] = {}; - object.animationCache[this.data.name].prevKey = { pos: 0, rot: 0, scl: 0 }; - object.animationCache[this.data.name].nextKey = { pos: 0, rot: 0, scl: 0 }; - object.animationCache[this.data.name].originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix; + for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { - } + // remove minus times - var animationCache = object.animationCache[this.data.name]; + if ( data.hierarchy[ h ].keys[ k ].time < 0 ) { - // Get keys to match our current time + data.hierarchy[ h ].keys[ k ].time = 0; - for ( var t = 0; t < 3; t ++ ) { + } - var type = this.keyTypes[ t ]; + // create quaternions - var prevKey = this.data.hierarchy[ h ].keys[ 0 ]; - var nextKey = this.getNextKeyWith( type, h, 1 ); + if ( data.hierarchy[ h ].keys[ k ].rot !== undefined && + ! ( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) { - while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { + var quat = data.hierarchy[ h ].keys[ k ].rot; + data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat ); - prevKey = nextKey; - nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 ); + } } - animationCache.prevKey[ type ] = prevKey; - animationCache.nextKey[ type ] = nextKey; + // prepare morph target keys - } + if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) { - } + // get all used -}; + var usedMorphTargets = {}; + for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { -THREE.Animation.prototype.update = (function(){ + for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) { - var points = []; - var target = new THREE.Vector3(); - var newVector = new THREE.Vector3(); - var newQuat = new THREE.Quaternion(); + var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ]; + usedMorphTargets[ morphTargetName ] = - 1; - // Catmull-Rom spline + } - var interpolateCatmullRom = function ( points, scale ) { + } - var c = [], v3 = [], - point, intPoint, weight, w2, w3, - pa, pb, pc, pd; + data.hierarchy[ h ].usedMorphTargets = usedMorphTargets; - point = ( points.length - 1 ) * scale; - intPoint = Math.floor( point ); - weight = point - intPoint; - c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1; - c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2; + // set all used on all frames - pa = points[ c[ 0 ] ]; - pb = points[ c[ 1 ] ]; - pc = points[ c[ 2 ] ]; - pd = points[ c[ 3 ] ]; + for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { - w2 = weight * weight; - w3 = weight * w2; + var influences = {}; - v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 ); - v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 ); - v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 ); + for ( var morphTargetName in usedMorphTargets ) { - return v3; + for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) { - }; + if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) { - var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) { + influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ]; + break; - var v0 = ( p2 - p0 ) * 0.5, - v1 = ( p3 - p1 ) * 0.5; + } - return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; + } - }; + if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) { - return function ( delta ) { - if ( this.isPlaying === false ) return; + influences[ morphTargetName ] = 0; - this.currentTime += delta * this.timeScale; + } - if ( this.weight === 0 ) - return; + } - // + data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences; - var vector; - var duration = this.data.length; + } - if ( this.loop === true && this.currentTime > duration ) { + } - this.currentTime %= duration; - this.reset(); - } else if ( this.loop === false && this.currentTime > duration ) { + // remove all keys that are on the same time - this.stop(); - return; + for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) { - } + if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) { - for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { + data.hierarchy[ h ].keys.splice( k, 1 ); + k --; - var object = this.hierarchy[ h ]; - var animationCache = object.animationCache[this.data.name]; + } - // loop through pos/rot/scl + } - for ( var t = 0; t < 3; t ++ ) { - // get keys + // set index - var type = this.keyTypes[ t ]; - var prevKey = animationCache.prevKey[ type ]; - var nextKey = animationCache.nextKey[ type ]; + for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { - if ( nextKey.time <= this.currentTime ) { + data.hierarchy[ h ].keys[ k ].index = k; - prevKey = this.data.hierarchy[ h ].keys[ 0 ]; - nextKey = this.getNextKeyWith( type, h, 1 ); + } - while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { + } - prevKey = nextKey; - nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 ); + data.initialized = true; - } + return data; - animationCache.prevKey[ type ] = prevKey; - animationCache.nextKey[ type ] = nextKey; + }, - } + parse: function ( root ) { - object.matrixAutoUpdate = true; - object.matrixWorldNeedsUpdate = true; + var parseRecurseHierarchy = function ( root, hierarchy ) { - var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time ); + hierarchy.push( root ); - var prevXYZ = prevKey[ type ]; - var nextXYZ = nextKey[ type ]; + for ( var c = 0; c < root.children.length; c ++ ) + parseRecurseHierarchy( root.children[ c ], hierarchy ); - if ( scale < 0 ) scale = 0; - if ( scale > 1 ) scale = 1; + }; - // interpolate + // setup hierarchy - if ( type === "pos" ) { + var hierarchy = []; - vector = object.position; + if ( root instanceof THREE.SkinnedMesh ) { - if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) { + for ( var b = 0; b < root.skeleton.bones.length; b ++ ) { - newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale; - newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale; - newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale; + hierarchy.push( root.skeleton.bones[ b ] ); - // blend - if (object instanceof THREE.Bone) { + } - var proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight ); - vector.lerp( newVector, proportionalWeight ); - object.accumulatedPosWeight += this.weight; + } else { - } else - vector = newVector; + parseRecurseHierarchy( root, hierarchy ); - } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || - this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { + } - points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ]; - points[ 1 ] = prevXYZ; - points[ 2 ] = nextXYZ; - points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ]; + return hierarchy; - scale = scale * 0.33 + 0.33; + }, - var currentPoint = interpolateCatmullRom( points, scale ); + play: function ( animation ) { - if ( object instanceof THREE.Bone ) { + if ( this.animations.indexOf( animation ) === - 1 ) { - var proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight ); - object.accumulatedPosWeight += this.weight; + this.animations.push( animation ); - } - else - var proportionalWeight = 1; + } - // blend - vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight; - vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight; - vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight; + }, - if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { + stop: function ( animation ) { - var forwardPoint = interpolateCatmullRom( points, scale * 1.01 ); + var index = this.animations.indexOf( animation ); - target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] ); - target.sub( vector ); - target.y = 0; - target.normalize(); + if ( index !== - 1 ) { - var angle = Math.atan2( target.x, target.z ); - object.rotation.set( 0, angle, 0 ); + this.animations.splice( index, 1 ); - } + } - } + }, - } else if ( type === "rot" ) { + update: function ( deltaTimeMS ) { - THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale ); + for ( var i = 0; i < this.animations.length; i ++ ) { - // Avoid paying the cost of an additional slerp if we don't have to - if ( !( object instanceof THREE.Bone ) ) { + this.animations[ i ].update( deltaTimeMS ); - object.quaternion.copy(newQuat); + } - } - else if ( object.accumulatedRotWeight === 0) { + } - object.quaternion.copy(newQuat); - object.accumulatedRotWeight = this.weight; +}; - } - else { +// File:src/extras/animation/Animation.js - var proportionalWeight = this.weight / ( this.weight + object.accumulatedRotWeight ); - THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight ); - object.accumulatedRotWeight += this.weight; +/** + * @author mikael emtinger / http://gomo.se/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - } +THREE.Animation = function ( root, data ) { + + this.root = root; + this.data = THREE.AnimationHandler.init( data ); + this.hierarchy = THREE.AnimationHandler.parse( root ); - } else if ( type === "scl" ) { + this.currentTime = 0; + this.timeScale = 1; - vector = object.scale; + this.isPlaying = false; + this.loop = true; + this.weight = 0; - newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale; - newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale; - newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale; + this.interpolationType = THREE.AnimationHandler.LINEAR; - if ( object instanceof THREE.Bone ) { +}; - var proportionalWeight = this.weight / ( this.weight + object.accumulatedSclWeight); - vector.lerp( newVector, proportionalWeight ); - object.accumulatedSclWeight += this.weight; - } else - vector = newVector; +THREE.Animation.prototype.keyTypes = [ "pos", "rot", "scl" ]; - } - } +THREE.Animation.prototype.play = function ( startTime, weight ) { - } + this.currentTime = startTime !== undefined ? startTime : 0; + this.weight = weight !== undefined ? weight: 1; - return true; + this.isPlaying = true; - }; + this.reset(); -})(); + THREE.AnimationHandler.play( this ); +}; +THREE.Animation.prototype.stop = function() { + this.isPlaying = false; -// Get next key with + THREE.AnimationHandler.stop( this ); -THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) { +}; - var keys = this.data.hierarchy[ h ].keys; +THREE.Animation.prototype.reset = function () { - if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || - this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { + for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { - key = key < keys.length - 1 ? key : keys.length - 1; + var object = this.hierarchy[ h ]; - } else { + object.matrixAutoUpdate = true; - key = key % keys.length; + if ( object.animationCache === undefined ) { - } + object.animationCache = {}; - for ( ; key < keys.length; key++ ) { + } - if ( keys[ key ][ type ] !== undefined ) { + if ( object.animationCache[this.data.name] === undefined ) { - return keys[ key ]; + object.animationCache[this.data.name] = {}; + object.animationCache[this.data.name].prevKey = { pos: 0, rot: 0, scl: 0 }; + object.animationCache[this.data.name].nextKey = { pos: 0, rot: 0, scl: 0 }; + object.animationCache[this.data.name].originalMatrix = object.matrix; } - } + var animationCache = object.animationCache[this.data.name]; - return this.data.hierarchy[ h ].keys[ 0 ]; + // Get keys to match our current time -}; + for ( var t = 0; t < 3; t ++ ) { -// Get previous key with + var type = this.keyTypes[ t ]; -THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) { + var prevKey = this.data.hierarchy[ h ].keys[ 0 ]; + var nextKey = this.getNextKeyWith( type, h, 1 ); - var keys = this.data.hierarchy[ h ].keys; + while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { - if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || - this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { + prevKey = nextKey; + nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 ); - key = key > 0 ? key : 0; + } - } else { + animationCache.prevKey[ type ] = prevKey; + animationCache.nextKey[ type ] = nextKey; - key = key >= 0 ? key : key + keys.length; + } } +}; - for ( ; key >= 0; key -- ) { - if ( keys[ key ][ type ] !== undefined ) { +THREE.Animation.prototype.update = (function(){ - return keys[ key ]; + var points = []; + var target = new THREE.Vector3(); + var newVector = new THREE.Vector3(); + var newQuat = new THREE.Quaternion(); - } + // Catmull-Rom spline - } + var interpolateCatmullRom = function ( points, scale ) { - return this.data.hierarchy[ h ].keys[ keys.length - 1 ]; + var c = [], v3 = [], + point, intPoint, weight, w2, w3, + pa, pb, pc, pd; -}; + point = ( points.length - 1 ) * scale; + intPoint = Math.floor( point ); + weight = point - intPoint; -/** - * @author mikael emtinger / http://gomo.se/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author khang duong - * @author erik kitson - */ + c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; + c[ 1 ] = intPoint; + c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1; + c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2; -THREE.KeyFrameAnimation = function ( root, data ) { + pa = points[ c[ 0 ] ]; + pb = points[ c[ 1 ] ]; + pc = points[ c[ 2 ] ]; + pd = points[ c[ 3 ] ]; - this.root = root; - this.data = THREE.AnimationHandler.get( data ); - this.hierarchy = THREE.AnimationHandler.parse( root ); - this.currentTime = 0; - this.timeScale = 0.001; - this.isPlaying = false; - this.isPaused = true; - this.loop = true; + w2 = weight * weight; + w3 = weight * w2; - // initialize to first keyframes + v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 ); + v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 ); + v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 ); - for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { + return v3; - var keys = this.data.hierarchy[h].keys, - sids = this.data.hierarchy[h].sids, - obj = this.hierarchy[h]; + }; - if ( keys.length && sids ) { + var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) { - for ( var s = 0; s < sids.length; s++ ) { + var v0 = ( p2 - p0 ) * 0.5, + v1 = ( p3 - p1 ) * 0.5; - var sid = sids[ s ], - next = this.getNextKeyWith( sid, h, 0 ); + return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; - if ( next ) { + }; - next.apply( sid ); + return function ( delta ) { - } + if ( this.isPlaying === false ) return; - } + this.currentTime += delta * this.timeScale; - obj.matrixAutoUpdate = false; - this.data.hierarchy[h].node.updateMatrix(); - obj.matrixWorldNeedsUpdate = true; + if ( this.weight === 0 ) + return; - } + // - } + var duration = this.data.length; -}; + if ( this.loop === true && this.currentTime > duration ) { -// Play + this.currentTime %= duration; + this.reset(); -THREE.KeyFrameAnimation.prototype.play = function ( startTime ) { + } else if ( this.loop === false && this.currentTime > duration ) { - this.currentTime = startTime !== undefined ? startTime : 0; + this.stop(); + return; - if ( this.isPlaying === false ) { + } - this.isPlaying = true; + for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { - // reset key cache + var object = this.hierarchy[ h ]; + var animationCache = object.animationCache[this.data.name]; - var h, hl = this.hierarchy.length, - object, - node; + // loop through pos/rot/scl - for ( h = 0; h < hl; h++ ) { + for ( var t = 0; t < 3; t ++ ) { - object = this.hierarchy[ h ]; - node = this.data.hierarchy[ h ]; + // get keys - if ( node.animationCache === undefined ) { + var type = this.keyTypes[ t ]; + var prevKey = animationCache.prevKey[ type ]; + var nextKey = animationCache.nextKey[ type ]; - node.animationCache = {}; - node.animationCache.prevKey = null; - node.animationCache.nextKey = null; - node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix; + if ( nextKey.time <= this.currentTime ) { - } + prevKey = this.data.hierarchy[ h ].keys[ 0 ]; + nextKey = this.getNextKeyWith( type, h, 1 ); - var keys = this.data.hierarchy[h].keys; + while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { - if (keys.length) { + prevKey = nextKey; + nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 ); - node.animationCache.prevKey = keys[ 0 ]; - node.animationCache.nextKey = keys[ 1 ]; + } - this.startTime = Math.min( keys[0].time, this.startTime ); - this.endTime = Math.max( keys[keys.length - 1].time, this.endTime ); + animationCache.prevKey[ type ] = prevKey; + animationCache.nextKey[ type ] = nextKey; - } + } - } + object.matrixAutoUpdate = true; + object.matrixWorldNeedsUpdate = true; - this.update( 0 ); + var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time ); - } + var prevXYZ = prevKey[ type ]; + var nextXYZ = nextKey[ type ]; - this.isPaused = false; + if ( scale < 0 ) scale = 0; + if ( scale > 1 ) scale = 1; - THREE.AnimationHandler.addToUpdate( this ); + // interpolate -}; + if ( type === "pos" ) { + if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) { + newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale; + newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale; + newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale; -// Pause + // blend + if ( object instanceof THREE.Bone ) { -THREE.KeyFrameAnimation.prototype.pause = function() { + var proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight ); + object.position.lerp( newVector, proportionalWeight ); + object.accumulatedPosWeight += this.weight; - if( this.isPaused ) { + } else { - THREE.AnimationHandler.addToUpdate( this ); + object.position.copy( newVector ); - } else { + } - THREE.AnimationHandler.removeFromUpdate( this ); + } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || + this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - } + points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ]; + points[ 1 ] = prevXYZ; + points[ 2 ] = nextXYZ; + points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ]; - this.isPaused = !this.isPaused; + scale = scale * 0.33 + 0.33; -}; + var currentPoint = interpolateCatmullRom( points, scale ); + var proportionalWeight = 1; + + if ( object instanceof THREE.Bone ) { + proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight ); + object.accumulatedPosWeight += this.weight; -// Stop + } -THREE.KeyFrameAnimation.prototype.stop = function() { + // blend - this.isPlaying = false; - this.isPaused = false; + var vector = object.position; + + vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight; + vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight; + vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight; - THREE.AnimationHandler.removeFromUpdate( this ); + if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - // reset JIT matrix and remove cache + var forwardPoint = interpolateCatmullRom( points, scale * 1.01 ); - for ( var h = 0; h < this.data.hierarchy.length; h++ ) { - - var obj = this.hierarchy[ h ]; - var node = this.data.hierarchy[ h ]; + target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] ); + target.sub( vector ); + target.y = 0; + target.normalize(); - if ( node.animationCache !== undefined ) { + var angle = Math.atan2( target.x, target.z ); + object.rotation.set( 0, angle, 0 ); - var original = node.animationCache.originalMatrix; + } - if( obj instanceof THREE.Bone ) { + } - original.copy( obj.skinMatrix ); - obj.skinMatrix = original; + } else if ( type === "rot" ) { - } else { + THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale ); - original.copy( obj.matrix ); - obj.matrix = original; + // Avoid paying the cost of an additional slerp if we don't have to + if ( ! ( object instanceof THREE.Bone ) ) { - } + object.quaternion.copy(newQuat); - delete node.animationCache; + } else if ( object.accumulatedRotWeight === 0 ) { - } + object.quaternion.copy(newQuat); + object.accumulatedRotWeight = this.weight; - } + } else { -}; + var proportionalWeight = this.weight / ( this.weight + object.accumulatedRotWeight ); + THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight ); + object.accumulatedRotWeight += this.weight; + } -// Update + } else if ( type === "scl" ) { -THREE.KeyFrameAnimation.prototype.update = function ( delta ) { + newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale; + newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale; + newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale; - if ( this.isPlaying === false ) return; + if ( object instanceof THREE.Bone ) { - this.currentTime += delta * this.timeScale; + var proportionalWeight = this.weight / ( this.weight + object.accumulatedSclWeight); + object.scale.lerp( newVector, proportionalWeight ); + object.accumulatedSclWeight += this.weight; - // + } else { - var duration = this.data.length; + object.scale.copy( newVector ); - if ( this.loop === true && this.currentTime > duration ) { + } - this.currentTime %= duration; + } - } + } - this.currentTime = Math.min( this.currentTime, duration ); + } - for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) { + return true; - var object = this.hierarchy[ h ]; - var node = this.data.hierarchy[ h ]; + }; - var keys = node.keys, - animationCache = node.animationCache; +})(); - if ( keys.length ) { - var prevKey = animationCache.prevKey; - var nextKey = animationCache.nextKey; - if ( nextKey.time <= this.currentTime ) { - while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { +// Get next key with - prevKey = nextKey; - nextKey = keys[ prevKey.index + 1 ]; +THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) { - } + var keys = this.data.hierarchy[ h ].keys; - animationCache.prevKey = prevKey; - animationCache.nextKey = nextKey; + if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || + this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - } + key = key < keys.length - 1 ? key : keys.length - 1; - if ( nextKey.time >= this.currentTime ) { + } else { - prevKey.interpolate( nextKey, this.currentTime ); + key = key % keys.length; - } else { + } - prevKey.interpolate( nextKey, nextKey.time ); + for ( ; key < keys.length; key ++ ) { - } + if ( keys[ key ][ type ] !== undefined ) { - this.data.hierarchy[ h ].node.updateMatrix(); - object.matrixWorldNeedsUpdate = true; + return keys[ key ]; } } + return this.data.hierarchy[ h ].keys[ 0 ]; + }; -// Get next key with +// Get previous key with -THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) { +THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) { var keys = this.data.hierarchy[ h ].keys; - key = key % keys.length; - for ( ; key < keys.length; key++ ) { + if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || + this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - if ( keys[ key ].hasTarget( sid ) ) { + key = key > 0 ? key : 0; - return keys[ key ]; + } else { - } + key = key >= 0 ? key : key + keys.length; } - return keys[ 0 ]; - -}; - -// Get previous key with - -THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) { - - var keys = this.data.hierarchy[ h ].keys; - key = key >= 0 ? key : key + keys.length; - for ( ; key >= 0; key-- ) { + for ( ; key >= 0; key -- ) { - if ( keys[ key ].hasTarget( sid ) ) { + if ( keys[ key ][ type ] !== undefined ) { return keys[ key ]; @@ -32324,395 +29585,332 @@ THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) { } - return keys[ keys.length - 1 ]; + return this.data.hierarchy[ h ].keys[ keys.length - 1 ]; }; +// File:src/extras/animation/KeyFrameAnimation.js + /** - * @author mrdoob / http://mrdoob.com + * @author mikael emtinger / http://gomo.se/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author khang duong + * @author erik kitson */ -THREE.MorphAnimation = function ( mesh ) { +THREE.KeyFrameAnimation = function ( data ) { - this.mesh = mesh; - this.frames = mesh.morphTargetInfluences.length; + this.root = data.node; + this.data = THREE.AnimationHandler.init( data ); + this.hierarchy = THREE.AnimationHandler.parse( this.root ); this.currentTime = 0; - this.duration = 1000; - this.loop = true; - + this.timeScale = 0.001; this.isPlaying = false; + this.isPaused = true; + this.loop = true; -}; - -THREE.MorphAnimation.prototype = { - - play: function () { - - this.isPlaying = true; - - }, - - pause: function () { - - this.isPlaying = false; - }, - - update: ( function () { - - var lastFrame = 0; - var currentFrame = 0; - - return function ( delta ) { - - if ( this.isPlaying === false ) return; - - this.currentTime += delta; + // initialize to first keyframes - if ( this.loop === true && this.currentTime > this.duration ) { + for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { - this.currentTime %= this.duration; + var keys = this.data.hierarchy[h].keys, + sids = this.data.hierarchy[h].sids, + obj = this.hierarchy[h]; - } + if ( keys.length && sids ) { - this.currentTime = Math.min( this.currentTime, this.duration ); + for ( var s = 0; s < sids.length; s ++ ) { - var interpolation = this.duration / this.frames; - var frame = Math.floor( this.currentTime / interpolation ); + var sid = sids[ s ], + next = this.getNextKeyWith( sid, h, 0 ); - if ( frame != currentFrame ) { + if ( next ) { - this.mesh.morphTargetInfluences[ lastFrame ] = 0; - this.mesh.morphTargetInfluences[ currentFrame ] = 1; - this.mesh.morphTargetInfluences[ frame ] = 0; + next.apply( sid ); - lastFrame = currentFrame; - currentFrame = frame; + } } - this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation; - this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ]; + obj.matrixAutoUpdate = false; + this.data.hierarchy[h].node.updateMatrix(); + obj.matrixWorldNeedsUpdate = true; } - } )() + } }; -/** - * Camera for rendering cube maps - * - renders scene into axis-aligned cube - * - * @author alteredq / http://alteredqualia.com/ - */ -THREE.CubeCamera = function ( near, far, cubeResolution ) { +THREE.KeyFrameAnimation.prototype.play = function ( startTime ) { - THREE.Object3D.call( this ); + this.currentTime = startTime !== undefined ? startTime : 0; - var fov = 90, aspect = 1; + if ( this.isPlaying === false ) { - var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPX.up.set( 0, -1, 0 ); - cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) ); - this.add( cameraPX ); + this.isPlaying = true; - var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNX.up.set( 0, -1, 0 ); - cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) ); - this.add( cameraNX ); + // reset key cache - var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPY.up.set( 0, 0, 1 ); - cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) ); - this.add( cameraPY ); + var h, hl = this.hierarchy.length, + object, + node; - var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNY.up.set( 0, 0, -1 ); - cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) ); - this.add( cameraNY ); + for ( h = 0; h < hl; h ++ ) { - var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPZ.up.set( 0, -1, 0 ); - cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) ); - this.add( cameraPZ ); + object = this.hierarchy[ h ]; + node = this.data.hierarchy[ h ]; - var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNZ.up.set( 0, -1, 0 ); - cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) ); - this.add( cameraNZ ); + if ( node.animationCache === undefined ) { - this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } ); + node.animationCache = {}; + node.animationCache.prevKey = null; + node.animationCache.nextKey = null; + node.animationCache.originalMatrix = object.matrix; - this.updateCubeMap = function ( renderer, scene ) { + } - var renderTarget = this.renderTarget; - var generateMipmaps = renderTarget.generateMipmaps; + var keys = this.data.hierarchy[h].keys; - renderTarget.generateMipmaps = false; + if (keys.length) { - renderTarget.activeCubeFace = 0; - renderer.render( scene, cameraPX, renderTarget ); + node.animationCache.prevKey = keys[ 0 ]; + node.animationCache.nextKey = keys[ 1 ]; - renderTarget.activeCubeFace = 1; - renderer.render( scene, cameraNX, renderTarget ); + this.startTime = Math.min( keys[0].time, this.startTime ); + this.endTime = Math.max( keys[keys.length - 1].time, this.endTime ); - renderTarget.activeCubeFace = 2; - renderer.render( scene, cameraPY, renderTarget ); + } - renderTarget.activeCubeFace = 3; - renderer.render( scene, cameraNY, renderTarget ); + } - renderTarget.activeCubeFace = 4; - renderer.render( scene, cameraPZ, renderTarget ); + this.update( 0 ); - renderTarget.generateMipmaps = generateMipmaps; + } - renderTarget.activeCubeFace = 5; - renderer.render( scene, cameraNZ, renderTarget ); + this.isPaused = false; - }; + THREE.AnimationHandler.play( this ); }; -THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype ); -/** - * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog - * - * A general perpose camera, for setting FOV, Lens Focal Length, - * and switching between perspective and orthographic views easily. - * Use this only if you do not wish to manage - * both a Orthographic and Perspective Camera - * - */ +THREE.KeyFrameAnimation.prototype.stop = function() { + this.isPlaying = false; + this.isPaused = false; -THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) { + THREE.AnimationHandler.stop( this ); - THREE.Camera.call( this ); + // reset JIT matrix and remove cache - this.fov = fov; + for ( var h = 0; h < this.data.hierarchy.length; h ++ ) { + + var obj = this.hierarchy[ h ]; + var node = this.data.hierarchy[ h ]; - this.left = -width / 2; - this.right = width / 2 - this.top = height / 2; - this.bottom = -height / 2; + if ( node.animationCache !== undefined ) { - // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects + var original = node.animationCache.originalMatrix; - this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar ); - this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far ); + original.copy( obj.matrix ); + obj.matrix = original; - this.zoom = 1; + delete node.animationCache; - this.toPerspective(); + } - var aspect = width/height; + } }; -THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype ); -THREE.CombinedCamera.prototype.toPerspective = function () { +// Update + +THREE.KeyFrameAnimation.prototype.update = function ( delta ) { + + if ( this.isPlaying === false ) return; + + this.currentTime += delta * this.timeScale; - // Switches to the Perspective Camera + // - this.near = this.cameraP.near; - this.far = this.cameraP.far; + var duration = this.data.length; - this.cameraP.fov = this.fov / this.zoom ; + if ( this.loop === true && this.currentTime > duration ) { - this.cameraP.updateProjectionMatrix(); + this.currentTime %= duration; - this.projectionMatrix = this.cameraP.projectionMatrix; + } - this.inPerspectiveMode = true; - this.inOrthographicMode = false; + this.currentTime = Math.min( this.currentTime, duration ); -}; + for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { + + var object = this.hierarchy[ h ]; + var node = this.data.hierarchy[ h ]; -THREE.CombinedCamera.prototype.toOrthographic = function () { + var keys = node.keys, + animationCache = node.animationCache; - // Switches to the Orthographic camera estimating viewport from Perspective - var fov = this.fov; - var aspect = this.cameraP.aspect; - var near = this.cameraP.near; - var far = this.cameraP.far; + if ( keys.length ) { + + var prevKey = animationCache.prevKey; + var nextKey = animationCache.nextKey; - // The size that we set is the mid plane of the viewing frustum + if ( nextKey.time <= this.currentTime ) { - var hyperfocus = ( near + far ) / 2; + while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { - var halfHeight = Math.tan( fov / 2 ) * hyperfocus; - var planeHeight = 2 * halfHeight; - var planeWidth = planeHeight * aspect; - var halfWidth = planeWidth / 2; + prevKey = nextKey; + nextKey = keys[ prevKey.index + 1 ]; - halfHeight /= this.zoom; - halfWidth /= this.zoom; + } - this.cameraO.left = -halfWidth; - this.cameraO.right = halfWidth; - this.cameraO.top = halfHeight; - this.cameraO.bottom = -halfHeight; + animationCache.prevKey = prevKey; + animationCache.nextKey = nextKey; - // this.cameraO.left = -farHalfWidth; - // this.cameraO.right = farHalfWidth; - // this.cameraO.top = farHalfHeight; - // this.cameraO.bottom = -farHalfHeight; + } - // this.cameraO.left = this.left / this.zoom; - // this.cameraO.right = this.right / this.zoom; - // this.cameraO.top = this.top / this.zoom; - // this.cameraO.bottom = this.bottom / this.zoom; + if ( nextKey.time >= this.currentTime ) { - this.cameraO.updateProjectionMatrix(); + prevKey.interpolate( nextKey, this.currentTime ); - this.near = this.cameraO.near; - this.far = this.cameraO.far; - this.projectionMatrix = this.cameraO.projectionMatrix; + } else { - this.inPerspectiveMode = false; - this.inOrthographicMode = true; + prevKey.interpolate( nextKey, nextKey.time ); -}; + } + this.data.hierarchy[ h ].node.updateMatrix(); + object.matrixWorldNeedsUpdate = true; -THREE.CombinedCamera.prototype.setSize = function( width, height ) { + } - this.cameraP.aspect = width / height; - this.left = -width / 2; - this.right = width / 2 - this.top = height / 2; - this.bottom = -height / 2; + } }; +// Get next key with -THREE.CombinedCamera.prototype.setFov = function( fov ) { +THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) { - this.fov = fov; + var keys = this.data.hierarchy[ h ].keys; + key = key % keys.length; - if ( this.inPerspectiveMode ) { + for ( ; key < keys.length; key ++ ) { - this.toPerspective(); + if ( keys[ key ].hasTarget( sid ) ) { - } else { + return keys[ key ]; - this.toOrthographic(); + } } + return keys[ 0 ]; + }; -// For mantaining similar API with PerspectiveCamera +// Get previous key with + +THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) { -THREE.CombinedCamera.prototype.updateProjectionMatrix = function() { + var keys = this.data.hierarchy[ h ].keys; + key = key >= 0 ? key : key + keys.length; - if ( this.inPerspectiveMode ) { + for ( ; key >= 0; key -- ) { - this.toPerspective(); + if ( keys[ key ].hasTarget( sid ) ) { - } else { + return keys[ key ]; - this.toPerspective(); - this.toOrthographic(); + } } + return keys[ keys.length - 1 ]; + }; -/* -* Uses Focal Length (in mm) to estimate and set FOV -* 35mm (fullframe) camera is used if frame size is not specified; -* Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html -*/ -THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) { +// File:src/extras/animation/MorphAnimation.js - if ( frameHeight === undefined ) frameHeight = 24; +/** + * @author mrdoob / http://mrdoob.com + */ - var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) ); +THREE.MorphAnimation = function ( mesh ) { - this.setFov( fov ); + this.mesh = mesh; + this.frames = mesh.morphTargetInfluences.length; + this.currentTime = 0; + this.duration = 1000; + this.loop = true; - return fov; -}; + this.isPlaying = false; +}; -THREE.CombinedCamera.prototype.setZoom = function( zoom ) { +THREE.MorphAnimation.prototype = { - this.zoom = zoom; + play: function () { - if ( this.inPerspectiveMode ) { + this.isPlaying = true; - this.toPerspective(); + }, - } else { + pause: function () { - this.toOrthographic(); + this.isPlaying = false; - } + }, -}; + update: ( function () { -THREE.CombinedCamera.prototype.toFrontView = function() { + var lastFrame = 0; + var currentFrame = 0; - this.rotation.x = 0; - this.rotation.y = 0; - this.rotation.z = 0; + return function ( delta ) { - // should we be modifing the matrix instead? + if ( this.isPlaying === false ) return; - this.rotationAutoUpdate = false; + this.currentTime += delta; -}; + if ( this.loop === true && this.currentTime > this.duration ) { -THREE.CombinedCamera.prototype.toBackView = function() { + this.currentTime %= this.duration; - this.rotation.x = 0; - this.rotation.y = Math.PI; - this.rotation.z = 0; - this.rotationAutoUpdate = false; + } -}; + this.currentTime = Math.min( this.currentTime, this.duration ); -THREE.CombinedCamera.prototype.toLeftView = function() { + var interpolation = this.duration / this.frames; + var frame = Math.floor( this.currentTime / interpolation ); - this.rotation.x = 0; - this.rotation.y = - Math.PI / 2; - this.rotation.z = 0; - this.rotationAutoUpdate = false; + if ( frame != currentFrame ) { -}; + this.mesh.morphTargetInfluences[ lastFrame ] = 0; + this.mesh.morphTargetInfluences[ currentFrame ] = 1; + this.mesh.morphTargetInfluences[ frame ] = 0; -THREE.CombinedCamera.prototype.toRightView = function() { + lastFrame = currentFrame; + currentFrame = frame; - this.rotation.x = 0; - this.rotation.y = Math.PI / 2; - this.rotation.z = 0; - this.rotationAutoUpdate = false; + } -}; + this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation; + this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ]; -THREE.CombinedCamera.prototype.toTopView = function() { + } - this.rotation.x = - Math.PI / 2; - this.rotation.y = 0; - this.rotation.z = 0; - this.rotationAutoUpdate = false; + } )() }; -THREE.CombinedCamera.prototype.toBottomView = function() { - - this.rotation.x = Math.PI / 2; - this.rotation.y = 0; - this.rotation.z = 0; - this.rotationAutoUpdate = false; - -}; +// File:src/extras/geometries/BoxGeometry.js /** * @author mrdoob / http://mrdoob.com/ @@ -32797,9 +29995,9 @@ THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegmen } - for ( iy = 0; iy < gridY; iy++ ) { + for ( iy = 0; iy < gridY; iy ++ ) { - for ( ix = 0; ix < gridX; ix++ ) { + for ( ix = 0; ix < gridX; ix ++ ) { var a = ix + gridX1 * iy; var b = ix + gridX1 * ( iy + 1 ); @@ -32839,6 +30037,8 @@ THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegmen THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/geometries/CircleGeometry.js + /** * @author hughes */ @@ -32896,12 +30096,22 @@ THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) { THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype ); -// DEPRECATED +// File:src/extras/geometries/CubeGeometry.js + +/** + * @author mrdoob / http://mrdoob.com/ + */ + THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { - console.warn( 'DEPRECATED: THREE.CubeGeometry is deprecated. Use THREE.BoxGeometry instead.' ); - return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ); + + console.warn( 'THEE.CubeGeometry has been renamed to THREE.BoxGeometry.' ); + return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ); + }; + +// File:src/extras/geometries/CylinderGeometry.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -33068,6 +30278,8 @@ THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegme THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/geometries/ExtrudeGeometry.js + /** * @author zz85 / http://www.lab4games.net/zz85/blog * @@ -33105,8 +30317,6 @@ THREE.ExtrudeGeometry = function ( shapes, options ) { shapes = shapes instanceof Array ? shapes : [ shapes ]; - this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox(); - this.addShapeList( shapes, options ); this.computeFaceNormals(); @@ -33155,11 +30365,6 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { // Use default WorldUVGenerator if no UV generators are specified. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator; - var shapebb = this.shapebb; - //shapebb = shape.getBoundingBox(); - - - var splineTube, binormal, normal, position2; if ( extrudePath ) { @@ -33206,7 +30411,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { var vertices = shapePoints.shape; var holes = shapePoints.holes; - var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ; + var reverse = ! THREE.Shape.Utils.isClockWise( vertices ) ; if ( reverse ) { @@ -33248,7 +30453,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { function scalePt2 ( pt, vec, size ) { - if ( !vec ) console.log( "die" ); + if ( ! vec ) console.log( "die" ); return vec.clone().multiplyScalar( size ).add( pt ); @@ -33331,8 +30536,8 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { if ( v_prev_x > EPSILON ) { if ( v_next_x > EPSILON ) { direction_eq = true; } } else { - if ( v_prev_x < -EPSILON ) { - if ( v_next_x < -EPSILON ) { direction_eq = true; } + if ( v_prev_x < - EPSILON ) { + if ( v_next_x < - EPSILON ) { direction_eq = true; } } else { if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; } } @@ -33340,7 +30545,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { if ( direction_eq ) { // console.log("Warning: lines are a straight sequence"); - v_trans_x = -v_prev_y; + v_trans_x = - v_prev_y; v_trans_y = v_prev_x; shrink_by = Math.sqrt( v_prev_lensq ); } else { @@ -33423,16 +30628,16 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { // expand holes - for ( h = 0, hl = holes.length; h < hl; h++ ) { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { ahole = holes[ h ]; oneHoleMovements = holesMovements[ h ]; - for ( i = 0, il = ahole.length; i < il; i++ ) { + for ( i = 0, il = ahole.length; i < il; i ++ ) { vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - v( vert.x, vert.y, -z ); + v( vert.x, vert.y, - z ); } @@ -33448,7 +30653,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - if ( !extrudeByPath ) { + if ( ! extrudeByPath ) { v( vert.x, vert.y, 0 ); @@ -33478,7 +30683,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - if ( !extrudeByPath ) { + if ( ! extrudeByPath ) { v( vert.x, vert.y, amount / steps * s ); @@ -33530,7 +30735,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - if ( !extrudeByPath ) { + if ( ! extrudeByPath ) { v( vert.x, vert.y, amount + z ); @@ -33591,7 +30796,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { // Bottom faces - for ( i = 0; i < flen; i++ ) { + for ( i = 0; i < flen; i ++ ) { face = faces[ i ]; f3( face[ 2 ], face[ 1 ], face[ 0 ], true ); @@ -33775,6 +30980,8 @@ THREE.ExtrudeGeometry.__v4 = new THREE.Vector2(); THREE.ExtrudeGeometry.__v5 = new THREE.Vector2(); THREE.ExtrudeGeometry.__v6 = new THREE.Vector2(); +// File:src/extras/geometries/ShapeGeometry.js + /** * @author jonobr1 / http://jonobr1.com * @@ -33797,8 +31004,6 @@ THREE.ShapeGeometry = function ( shapes, options ) { if ( shapes instanceof Array === false ) shapes = [ shapes ]; - this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox(); - this.addShapeList( shapes, options ); this.computeFaceNormals(); @@ -33812,7 +31017,7 @@ THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype ); */ THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { - for ( var i = 0, l = shapes.length; i < l; i++ ) { + for ( var i = 0, l = shapes.length; i < l; i ++ ) { this.addShape( shapes[ i ], options ); @@ -33833,8 +31038,6 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { var material = options.material; var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; - var shapebb = this.shapebb; - // var i, l, hole, s; @@ -33845,7 +31048,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { var vertices = shapePoints.shape; var holes = shapePoints.holes; - var reverse = !THREE.Shape.Utils.isClockWise( vertices ); + var reverse = ! THREE.Shape.Utils.isClockWise( vertices ); if ( reverse ) { @@ -33853,7 +31056,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { // Maybe we should also check if holes are in the opposite direction, just to be safe... - for ( i = 0, l = holes.length; i < l; i++ ) { + for ( i = 0, l = holes.length; i < l; i ++ ) { hole = holes[ i ]; @@ -33875,7 +31078,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { var contour = vertices; - for ( i = 0, l = holes.length; i < l; i++ ) { + for ( i = 0, l = holes.length; i < l; i ++ ) { hole = holes[ i ]; vertices = vertices.concat( hole ); @@ -33888,7 +31091,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { var face, flen = faces.length; var cont, clen = contour.length; - for ( i = 0; i < vlen; i++ ) { + for ( i = 0; i < vlen; i ++ ) { vert = vertices[ i ]; @@ -33896,7 +31099,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { } - for ( i = 0; i < flen; i++ ) { + for ( i = 0; i < flen; i ++ ) { face = faces[ i ]; @@ -33911,6 +31114,8 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { }; +// File:src/extras/geometries/LatheGeometry.js + /** * @author astrodud / http://astrodud.isgreat.org/ * @author zz85 / https://github.com/zz85 @@ -34007,6 +31212,8 @@ THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) { THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/geometries/PlaneGeometry.js + /** * @author mrdoob / http://mrdoob.com/ * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as @@ -34088,6 +31295,8 @@ THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/geometries/RingGeometry.js + /** * @author Kaleb Murphy */ @@ -34103,17 +31312,16 @@ THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegm thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; - phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8; + phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8; var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring + for ( i = 0; i < phiSegments + 1; i ++ ) { // concentric circles inside ring - for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle + for ( o = 0; o < thetaSegments + 1; o ++ ) { // number of segments per circle var vertex = new THREE.Vector3(); var segment = thetaStart + o / thetaSegments * thetaLength; - vertex.x = radius * Math.cos( segment ); vertex.y = radius * Math.sin( segment ); @@ -34129,22 +31337,22 @@ THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegm for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring - var thetaSegment = i * thetaSegments; + var thetaSegment = i * (thetaSegments + 1); - for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle + for ( o = 0; o < thetaSegments ; o ++ ) { // number of segments per circle var segment = o + thetaSegment; - var v1 = segment + i; - var v2 = segment + thetaSegments + i; - var v3 = segment + thetaSegments + 1 + i; + var v1 = segment; + var v2 = segment + thetaSegments + 1; + var v3 = segment + thetaSegments + 2; this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) ); this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]); - v1 = segment + i; - v2 = segment + thetaSegments + 1 + i; - v3 = segment + 1 + i; + v1 = segment; + v2 = segment + thetaSegments + 2; + v3 = segment + 1; this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) ); this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]); @@ -34160,6 +31368,9 @@ THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegm THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype ); + +// File:src/extras/geometries/SphereGeometry.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -34271,6 +31482,8 @@ THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStar THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/geometries/TextGeometry.js + /** * @author zz85 / http://www.lab4games.net/zz85/blog * @author alteredq / http://alteredqualia.com/ @@ -34331,6 +31544,8 @@ THREE.TextGeometry = function ( text, parameters ) { THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype ); +// File:src/extras/geometries/TorusGeometry.js + /** * @author oosmoxiecode * @author mrdoob / http://mrdoob.com/ @@ -34408,6 +31623,8 @@ THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/geometries/TorusKnotGeometry.js + /** * @author oosmoxiecode * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473 @@ -34519,6 +31736,8 @@ THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegmen THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/geometries/TubeGeometry.js + /** * @author WestLangley / https://github.com/WestLangley * @author zz85 / https://github.com/zz85 @@ -34588,7 +31807,7 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed ) // consruct the grid - for ( i = 0; i < numpoints; i++ ) { + for ( i = 0; i < numpoints; i ++ ) { grid[ i ] = []; @@ -34600,11 +31819,11 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed ) normal = normals[ i ]; binormal = binormals[ i ]; - for ( j = 0; j < radialSegments; j++ ) { + for ( j = 0; j < radialSegments; j ++ ) { v = j / radialSegments * 2 * Math.PI; - cx = -radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. + cx = - radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. cy = radius * Math.sin( v ); pos2.copy( pos ); @@ -34620,9 +31839,9 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed ) // construct the mesh - for ( i = 0; i < segments; i++ ) { + for ( i = 0; i < segments; i ++ ) { - for ( j = 0; j < radialSegments; j++ ) { + for ( j = 0; j < radialSegments; j ++ ) { ip = ( closed ) ? (i + 1) % segments : i + 1; jp = (j + 1) % radialSegments; @@ -34684,7 +31903,7 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { // compute the tangent vectors for each segment on the path - for ( i = 0; i < numpoints; i++ ) { + for ( i = 0; i < numpoints; i ++ ) { u = i / ( numpoints - 1 ); @@ -34695,6 +31914,7 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { initialNormal3(); + /* function initialNormal1(lastBinormal) { // fixed start binormal. Has dangers of 0 vectors normals[ 0 ] = new THREE.Vector3(); @@ -34716,6 +31936,7 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); } + */ function initialNormal3() { // select an initial normal vector perpenicular to the first tangent vector, @@ -34751,7 +31972,7 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { // compute the slowly-varying normal and binormal vectors for each segment on the path - for ( i = 1; i < numpoints; i++ ) { + for ( i = 1; i < numpoints; i ++ ) { normals[ i ] = normals[ i-1 ].clone(); @@ -34763,7 +31984,7 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { vec.normalize(); - theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors + theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); @@ -34778,16 +31999,16 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { if ( closed ) { - theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) ); + theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), - 1, 1 ) ); theta /= ( numpoints - 1 ); if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) { - theta = -theta; + theta = - theta; } - for ( i = 1; i < numpoints; i++ ) { + for ( i = 1; i < numpoints; i ++ ) { // twist a little... normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); @@ -34798,6 +32019,8 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { } }; +// File:src/extras/geometries/PolyhedronGeometry.js + /** * @author clockworkgeek / https://github.com/clockworkgeek * @author timothypratley / https://github.com/timothypratley @@ -34996,7 +32219,7 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { function azimuth( vector ) { - return Math.atan2( vector.z, -vector.x ); + return Math.atan2( vector.z, - vector.x ); } @@ -35005,7 +32228,7 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { function inclination( vector ) { - return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); } @@ -35025,6 +32248,8 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/geometries/IcosahedronGeometry.js + /** * @author timothypratley / https://github.com/timothypratley */ @@ -35039,9 +32264,9 @@ THREE.IcosahedronGeometry = function ( radius, detail ) { var t = ( 1 + Math.sqrt( 5 ) ) / 2; var vertices = [ - -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, - 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, - t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1 + - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0, + 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, + t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1 ]; var indices = [ @@ -35057,6 +32282,8 @@ THREE.IcosahedronGeometry = function ( radius, detail ) { THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/geometries/OctahedronGeometry.js + /** * @author timothypratley / https://github.com/timothypratley */ @@ -35069,7 +32296,7 @@ THREE.OctahedronGeometry = function ( radius, detail ) { }; var vertices = [ - 1, 0, 0, -1, 0, 0, 0, 1, 0, 0,-1, 0, 0, 0, 1, 0, 0,-1 + 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0,- 1, 0, 0, 0, 1, 0, 0,- 1 ]; var indices = [ @@ -35081,6 +32308,8 @@ THREE.OctahedronGeometry = function ( radius, detail ) { THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/geometries/TetrahedronGeometry.js + /** * @author timothypratley / https://github.com/timothypratley */ @@ -35088,7 +32317,7 @@ THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); THREE.TetrahedronGeometry = function ( radius, detail ) { var vertices = [ - 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1 + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 ]; var indices = [ @@ -35101,6 +32330,8 @@ THREE.TetrahedronGeometry = function ( radius, detail ) { THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/geometries/ParametricGeometry.js + /** * @author zz85 / https://github.com/zz85 * Parametric Surfaces Geometry @@ -35178,6 +32409,8 @@ THREE.ParametricGeometry = function ( func, slices, stacks ) { THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype ); +// File:src/extras/helpers/AxisHelper.js + /** * @author sroucheray / http://sroucheray.org/ * @author mrdoob / http://mrdoob.com/ @@ -35187,19 +32420,21 @@ THREE.AxisHelper = function ( size ) { size = size || 1; - var geometry = new THREE.Geometry(); + var vertices = new Float32Array( [ + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size + ] ); - geometry.vertices.push( - new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ), - new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ), - new THREE.Vector3(), new THREE.Vector3( 0, 0, size ) - ); + var colors = new Float32Array( [ + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 + ] ); - geometry.colors.push( - new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ), - new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ), - new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff ) - ); + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); @@ -35209,6 +32444,8 @@ THREE.AxisHelper = function ( size ) { THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype ); +// File:src/extras/helpers/ArrowHelper.js + /** * @author WestLangley / http://github.com/WestLangley * @author zz85 / http://github.com/zz85 @@ -35225,42 +32462,45 @@ THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype ); * headWidth - Number */ -THREE.ArrowHelper = function ( dir, origin, length, color, headLength, headWidth ) { +THREE.ArrowHelper = ( function () { - // dir is assumed to be normalized + var lineGeometry = new THREE.Geometry(); + lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); - THREE.Object3D.call( this ); + var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 ); + coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) ); - if ( color === undefined ) color = 0xffff00; - if ( length === undefined ) length = 1; - if ( headLength === undefined ) headLength = 0.2 * length; - if ( headWidth === undefined ) headWidth = 0.2 * headLength; + return function ( dir, origin, length, color, headLength, headWidth ) { - this.position = origin; + // dir is assumed to be normalized - var lineGeometry = new THREE.Geometry(); - lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) ); - lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) ); + THREE.Object3D.call( this ); - this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) ); - this.line.matrixAutoUpdate = false; - this.add( this.line ); + if ( color === undefined ) color = 0xffff00; + if ( length === undefined ) length = 1; + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; - var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 ); - coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) ); + this.position.copy( origin ); - this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) ); - this.cone.matrixAutoUpdate = false; - this.add( this.cone ); + this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); - this.setDirection( dir ); - this.setLength( length, headLength, headWidth ); + this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); -}; + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); + + } + +}() ); THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.ArrowHelper.prototype.setDirection = function () { +THREE.ArrowHelper.prototype.setDirection = ( function () { var axis = new THREE.Vector3(); var radians; @@ -35289,7 +32529,7 @@ THREE.ArrowHelper.prototype.setDirection = function () { }; -}(); +}() ); THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { @@ -35312,50 +32552,16 @@ THREE.ArrowHelper.prototype.setColor = function ( color ) { }; +// File:src/extras/helpers/BoxHelper.js + /** * @author mrdoob / http://mrdoob.com/ */ THREE.BoxHelper = function ( object ) { - // 5____4 - // 1/___0/| - // | 6__|_7 - // 2/___3/ - - var vertices = [ - new THREE.Vector3( 1, 1, 1 ), - new THREE.Vector3( - 1, 1, 1 ), - new THREE.Vector3( - 1, - 1, 1 ), - new THREE.Vector3( 1, - 1, 1 ), - - new THREE.Vector3( 1, 1, - 1 ), - new THREE.Vector3( - 1, 1, - 1 ), - new THREE.Vector3( - 1, - 1, - 1 ), - new THREE.Vector3( 1, - 1, - 1 ) - ]; - - this.vertices = vertices; - - // TODO: Wouldn't be nice if Line had .segments? - - var geometry = new THREE.Geometry(); - geometry.vertices.push( - vertices[ 0 ], vertices[ 1 ], - vertices[ 1 ], vertices[ 2 ], - vertices[ 2 ], vertices[ 3 ], - vertices[ 3 ], vertices[ 0 ], - - vertices[ 4 ], vertices[ 5 ], - vertices[ 5 ], vertices[ 6 ], - vertices[ 6 ], vertices[ 7 ], - vertices[ 7 ], vertices[ 4 ], - - vertices[ 0 ], vertices[ 4 ], - vertices[ 1 ], vertices[ 5 ], - vertices[ 2 ], vertices[ 6 ], - vertices[ 3 ], vertices[ 7 ] - ); + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( 72 ), 3 ) ); THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces ); @@ -35381,25 +32587,76 @@ THREE.BoxHelper.prototype.update = function ( object ) { var min = geometry.boundingBox.min; var max = geometry.boundingBox.max; - var vertices = this.vertices; - vertices[ 0 ].set( max.x, max.y, max.z ); - vertices[ 1 ].set( min.x, max.y, max.z ); - vertices[ 2 ].set( min.x, min.y, max.z ); - vertices[ 3 ].set( max.x, min.y, max.z ); - vertices[ 4 ].set( max.x, max.y, min.z ); - vertices[ 5 ].set( min.x, max.y, min.z ); - vertices[ 6 ].set( min.x, min.y, min.z ); - vertices[ 7 ].set( max.x, min.y, min.z ); + /* + 5____4 + 1/___0/| + | 6__|_7 + 2/___3/ + + 0: max.x, max.y, max.z + 1: min.x, max.y, max.z + 2: min.x, min.y, max.z + 3: max.x, min.y, max.z + 4: max.x, max.y, min.z + 5: min.x, max.y, min.z + 6: min.x, min.y, min.z + 7: max.x, min.y, min.z + */ + + var vertices = this.geometry.attributes.position.array; + + vertices[ 0 ] = max.x; vertices[ 1 ] = max.y; vertices[ 2 ] = max.z; + vertices[ 3 ] = min.x; vertices[ 4 ] = max.y; vertices[ 5 ] = max.z; + + vertices[ 6 ] = min.x; vertices[ 7 ] = max.y; vertices[ 8 ] = max.z; + vertices[ 9 ] = min.x; vertices[ 10 ] = min.y; vertices[ 11 ] = max.z; + + vertices[ 12 ] = min.x; vertices[ 13 ] = min.y; vertices[ 14 ] = max.z; + vertices[ 15 ] = max.x; vertices[ 16 ] = min.y; vertices[ 17 ] = max.z; + + vertices[ 18 ] = max.x; vertices[ 19 ] = min.y; vertices[ 20 ] = max.z; + vertices[ 21 ] = max.x; vertices[ 22 ] = max.y; vertices[ 23 ] = max.z; + + // + + vertices[ 24 ] = max.x; vertices[ 25 ] = max.y; vertices[ 26 ] = min.z; + vertices[ 27 ] = min.x; vertices[ 28 ] = max.y; vertices[ 29 ] = min.z; + + vertices[ 30 ] = min.x; vertices[ 31 ] = max.y; vertices[ 32 ] = min.z; + vertices[ 33 ] = min.x; vertices[ 34 ] = min.y; vertices[ 35 ] = min.z; + + vertices[ 36 ] = min.x; vertices[ 37 ] = min.y; vertices[ 38 ] = min.z; + vertices[ 39 ] = max.x; vertices[ 40 ] = min.y; vertices[ 41 ] = min.z; + + vertices[ 42 ] = max.x; vertices[ 43 ] = min.y; vertices[ 44 ] = min.z; + vertices[ 45 ] = max.x; vertices[ 46 ] = max.y; vertices[ 47 ] = min.z; + + // + + vertices[ 48 ] = max.x; vertices[ 49 ] = max.y; vertices[ 50 ] = max.z; + vertices[ 51 ] = max.x; vertices[ 52 ] = max.y; vertices[ 53 ] = min.z; + + vertices[ 54 ] = min.x; vertices[ 55 ] = max.y; vertices[ 56 ] = max.z; + vertices[ 57 ] = min.x; vertices[ 58 ] = max.y; vertices[ 59 ] = min.z; + + vertices[ 60 ] = min.x; vertices[ 61 ] = min.y; vertices[ 62 ] = max.z; + vertices[ 63 ] = min.x; vertices[ 64 ] = min.y; vertices[ 65 ] = min.z; + + vertices[ 66 ] = max.x; vertices[ 67 ] = min.y; vertices[ 68 ] = max.z; + vertices[ 69 ] = max.x; vertices[ 70 ] = min.y; vertices[ 71 ] = min.z; + + this.geometry.attributes.position.needsUpdate = true; this.geometry.computeBoundingSphere(); - this.geometry.verticesNeedUpdate = true; this.matrixAutoUpdate = false; this.matrixWorld = object.matrixWorld; }; +// File:src/extras/helpers/BoundingBoxHelper.js + /** * @author WestLangley / http://github.com/WestLangley */ @@ -35430,6 +32687,8 @@ THREE.BoundingBoxHelper.prototype.update = function () { }; +// File:src/extras/helpers/CameraHelper.js + /** * @author alteredq / http://alteredqualia.com/ * @@ -35556,40 +32815,40 @@ THREE.CameraHelper.prototype.update = function () { // center / target - setPoint( "c", 0, 0, -1 ); + setPoint( "c", 0, 0, - 1 ); setPoint( "t", 0, 0, 1 ); // near - setPoint( "n1", -w, -h, -1 ); - setPoint( "n2", w, -h, -1 ); - setPoint( "n3", -w, h, -1 ); - setPoint( "n4", w, h, -1 ); + setPoint( "n1", - w, - h, - 1 ); + setPoint( "n2", w, - h, - 1 ); + setPoint( "n3", - w, h, - 1 ); + setPoint( "n4", w, h, - 1 ); // far - setPoint( "f1", -w, -h, 1 ); - setPoint( "f2", w, -h, 1 ); - setPoint( "f3", -w, h, 1 ); + setPoint( "f1", - w, - h, 1 ); + setPoint( "f2", w, - h, 1 ); + setPoint( "f3", - w, h, 1 ); setPoint( "f4", w, h, 1 ); // up - setPoint( "u1", w * 0.7, h * 1.1, -1 ); - setPoint( "u2", -w * 0.7, h * 1.1, -1 ); - setPoint( "u3", 0, h * 2, -1 ); + setPoint( "u1", w * 0.7, h * 1.1, - 1 ); + setPoint( "u2", - w * 0.7, h * 1.1, - 1 ); + setPoint( "u3", 0, h * 2, - 1 ); // cross - setPoint( "cf1", -w, 0, 1 ); + setPoint( "cf1", - w, 0, 1 ); setPoint( "cf2", w, 0, 1 ); - setPoint( "cf3", 0, -h, 1 ); + setPoint( "cf3", 0, - h, 1 ); setPoint( "cf4", 0, h, 1 ); - setPoint( "cn1", -w, 0, -1 ); - setPoint( "cn2", w, 0, -1 ); - setPoint( "cn3", 0, -h, -1 ); - setPoint( "cn4", 0, h, -1 ); + setPoint( "cn1", - w, 0, - 1 ); + setPoint( "cn2", w, 0, - 1 ); + setPoint( "cn3", 0, - h, - 1 ); + setPoint( "cn4", 0, h, - 1 ); function setPoint( point, x, y, z ) { @@ -35616,6 +32875,8 @@ THREE.CameraHelper.prototype.update = function () { }(); +// File:src/extras/helpers/DirectionalLightHelper.js + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ @@ -35699,6 +32960,8 @@ THREE.DirectionalLightHelper.prototype.update = function () { }(); +// File:src/extras/helpers/EdgesHelper.js + /** * @author WestLangley / http://github.com/WestLangley */ @@ -35749,7 +33012,7 @@ THREE.EdgesHelper = function ( object, hex ) { } - geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) ); + geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2 * 3, 3 ) ); var coords = geometry.attributes.position.array; @@ -35784,6 +33047,8 @@ THREE.EdgesHelper = function ( object, hex ) { THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype ); +// File:src/extras/helpers/FaceNormalsHelper.js + /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley @@ -35859,6 +33124,8 @@ THREE.FaceNormalsHelper.prototype.update = function () { }; +// File:src/extras/helpers/GridHelper.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -35899,6 +33166,8 @@ THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) { } +// File:src/extras/helpers/HemisphereLightHelper.js + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ @@ -35958,6 +33227,8 @@ THREE.HemisphereLightHelper.prototype.update = function () { }(); +// File:src/extras/helpers/PointLightHelper.js + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ @@ -36031,21 +33302,24 @@ THREE.PointLightHelper.prototype.update = function () { }; +// File:src/extras/helpers/SkeletonHelper.js + /** * @author Sean Griffin / http://twitter.com/sgrif * @author Michael Guerrero / http://realitymeltdown.com * @author mrdoob / http://mrdoob.com/ + * @author ikerr / http://verold.com */ THREE.SkeletonHelper = function ( object ) { - var skeleton = object.skeleton; + this.bones = this.getBoneList( object ); var geometry = new THREE.Geometry(); - for ( var i = 0; i < skeleton.bones.length; i ++ ) { + for ( var i = 0; i < this.bones.length; i ++ ) { - var bone = skeleton.bones[ i ]; + var bone = this.bones[ i ]; if ( bone.parent instanceof THREE.Bone ) { @@ -36058,11 +33332,11 @@ THREE.SkeletonHelper = function ( object ) { } - var material = new THREE.LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, transparent: true } ); + var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } ); THREE.Line.call( this, geometry, material, THREE.LinePieces ); - this.skeleton = skeleton; + this.root = object; this.matrixWorld = object.matrixWorld; this.matrixAutoUpdate = false; @@ -36074,20 +33348,47 @@ THREE.SkeletonHelper = function ( object ) { THREE.SkeletonHelper.prototype = Object.create( THREE.Line.prototype ); +THREE.SkeletonHelper.prototype.getBoneList = function( object ) { + + var boneList = []; + + if ( object instanceof THREE.Bone ) { + + boneList.push( object ); + + } + + for ( var i = 0; i < object.children.length; i ++ ) { + + boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) ); + + } + + return boneList; + +}; + THREE.SkeletonHelper.prototype.update = function () { var geometry = this.geometry; + var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld ); + + var boneMatrix = new THREE.Matrix4(); + var j = 0; - for ( var i = 0; i < this.skeleton.bones.length; i ++ ) { + for ( var i = 0; i < this.bones.length; i ++ ) { - var bone = this.skeleton.bones[ i ]; + var bone = this.bones[ i ]; if ( bone.parent instanceof THREE.Bone ) { - geometry.vertices[ j ].setFromMatrixPosition( bone.skinMatrix ); - geometry.vertices[ j + 1 ].setFromMatrixPosition( bone.parent.skinMatrix ); + boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); + geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); + + boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld ); + geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix ); j += 2; @@ -36101,6 +33402,8 @@ THREE.SkeletonHelper.prototype.update = function () { }; +// File:src/extras/helpers/SpotLightHelper.js + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ @@ -36119,7 +33422,7 @@ THREE.SpotLightHelper = function ( light ) { var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true ); - geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) ); + geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) ); geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); @@ -36161,6 +33464,8 @@ THREE.SpotLightHelper.prototype.update = function () { }(); +// File:src/extras/helpers/VertexNormalsHelper.js + /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley @@ -36188,8 +33493,7 @@ THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - geometry.vertices.push( new THREE.Vector3() ); - geometry.vertices.push( new THREE.Vector3() ); + geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() ); } @@ -36262,6 +33566,8 @@ THREE.VertexNormalsHelper.prototype.update = ( function ( object ) { }()); +// File:src/extras/helpers/VertexTangentsHelper.js + /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley @@ -36359,6 +33665,8 @@ THREE.VertexTangentsHelper.prototype.update = ( function ( object ) { }()); +// File:src/extras/helpers/WireframeHelper.js + /** * @author mrdoob / http://mrdoob.com/ */ @@ -36407,9 +33715,7 @@ THREE.WireframeHelper = function ( object, hex ) { } - geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) ); - - var coords = geometry.attributes.position.array; + var coords = new Float32Array( numEdges * 2 * 3 ); for ( var i = 0, l = numEdges; i < l; i ++ ) { @@ -36426,517 +33732,531 @@ THREE.WireframeHelper = function ( object, hex ) { } - } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry + geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); - var vertices = object.geometry.attributes.position.array; - var indices = object.geometry.attributes.index.array; - var offsets = object.geometry.offsets; - var numEdges = 0; + } else if ( object.geometry instanceof THREE.BufferGeometry ) { - // allocate maximal size - var edges = new Uint32Array( 2 * indices.length ); + if ( object.geometry.attributes.index !== undefined ) { // Indexed BufferGeometry + + var vertices = object.geometry.attributes.position.array; + var indices = object.geometry.attributes.index.array; + var offsets = object.geometry.offsets; + var numEdges = 0; + + // allocate maximal size + var edges = new Uint32Array( 2 * indices.length ); + + for ( var o = 0, ol = offsets.length; o < ol; ++ o ) { + + var start = offsets[ o ].start; + var count = offsets[ o ].count; + var index = offsets[ o ].index; + + for ( var i = start, il = start + count; i < il; i += 3 ) { + + for ( var j = 0; j < 3; j ++ ) { + + edge[ 0 ] = index + indices[ i + j ]; + edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ]; + edge.sort( sortFunction ); + + var key = edge.toString(); + + if ( hash[ key ] === undefined ) { + + edges[ 2 * numEdges ] = edge[ 0 ]; + edges[ 2 * numEdges + 1 ] = edge[ 1 ]; + hash[ key ] = true; + numEdges ++; + + } + + } + + } + + } + + var coords = new Float32Array( numEdges * 2 * 3 ); - for ( var o = 0, ol = offsets.length; o < ol; ++ o ) { + for ( var i = 0, l = numEdges; i < l; i ++ ) { - var start = offsets[ o ].start; - var count = offsets[ o ].count; - var index = offsets[ o ].index; + for ( var j = 0; j < 2; j ++ ) { - for ( var i = start, il = start + count; i < il; i += 3 ) { + var index = 6 * i + 3 * j; + var index2 = 3 * edges[ 2 * i + j]; + coords[ index + 0 ] = vertices[ index2 ]; + coords[ index + 1 ] = vertices[ index2 + 1 ]; + coords[ index + 2 ] = vertices[ index2 + 2 ]; + + } + + } + + geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + + } else { // non-indexed BufferGeometry + + var vertices = object.geometry.attributes.position.array; + var numEdges = vertices.length / 3; + var numTris = numEdges / 3; + + var coords = new Float32Array( numEdges * 2 * 3 ); + + for ( var i = 0, l = numTris; i < l; i ++ ) { for ( var j = 0; j < 3; j ++ ) { - edge[ 0 ] = index + indices[ i + j ]; - edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ]; - edge.sort( sortFunction ); + var index = 18 * i + 6 * j; + + var index1 = 9 * i + 3 * j; + coords[ index + 0 ] = vertices[ index1 ]; + coords[ index + 1 ] = vertices[ index1 + 1 ]; + coords[ index + 2 ] = vertices[ index1 + 2 ]; + + var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 ); + coords[ index + 3 ] = vertices[ index2 ]; + coords[ index + 4 ] = vertices[ index2 + 1 ]; + coords[ index + 5 ] = vertices[ index2 + 2 ]; + + } + + } + + geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + + } + + } + + THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces ); + + this.matrixAutoUpdate = false; + this.matrixWorld = object.matrixWorld; + +}; + +THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype ); + +// File:src/extras/objects/ImmediateRenderObject.js + +/** + * @author alteredq / http://alteredqualia.com/ + */ + +THREE.ImmediateRenderObject = function () { + + THREE.Object3D.call( this ); + + this.render = function ( renderCallback ) {}; + +}; + +THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype ); + +// File:src/extras/objects/LensFlare.js + +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ + +THREE.LensFlare = function ( texture, size, distance, blending, color ) { + + THREE.Object3D.call( this ); + + this.lensFlares = []; + + this.positionScreen = new THREE.Vector3(); + this.customUpdateCallback = undefined; + + if( texture !== undefined ) { + + this.add( texture, size, distance, blending, color ); + + } + +}; + +THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype ); + + +/* + * Add: adds another flare + */ + +THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) { + + if( size === undefined ) size = - 1; + if( distance === undefined ) distance = 0; + if( opacity === undefined ) opacity = 1; + if( color === undefined ) color = new THREE.Color( 0xffffff ); + if( blending === undefined ) blending = THREE.NormalBlending; + + distance = Math.min( distance, Math.max( 0, distance ) ); + + this.lensFlares.push( { texture: texture, // THREE.Texture + size: size, // size in pixels (-1 = use texture.width) + distance: distance, // distance (0-1) from light source (0=at light source) + x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back + scale: 1, // scale + rotation: 1, // rotation + opacity: opacity, // opacity + color: color, // color + blending: blending } ); // blending + +}; + + +/* + * Update lens flares update positions on all flares based on the screen position + * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way. + */ + +THREE.LensFlare.prototype.updateLensFlares = function () { + + var f, fl = this.lensFlares.length; + var flare; + var vecX = - this.positionScreen.x * 2; + var vecY = - this.positionScreen.y * 2; + + for( f = 0; f < fl; f ++ ) { + + flare = this.lensFlares[ f ]; + + flare.x = this.positionScreen.x + vecX * flare.distance; + flare.y = this.positionScreen.y + vecY * flare.distance; + + flare.wantedRotation = flare.x * Math.PI * 0.25; + flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; + + } + +}; + + + + + + + + + + + + + +// File:src/extras/objects/MorphBlendMesh.js + +/** + * @author alteredq / http://alteredqualia.com/ + */ + +THREE.MorphBlendMesh = function( geometry, material ) { + + THREE.Mesh.call( this, geometry, material ); + + this.animationsMap = {}; + this.animationsList = []; + + // prepare default animation + // (all frames played together in 1 second) + + var numFrames = this.geometry.morphTargets.length; + + var name = "__default"; + + var startFrame = 0; + var endFrame = numFrames - 1; + + var fps = numFrames / 1; + + this.createAnimation( name, startFrame, endFrame, fps ); + this.setAnimationWeight( name, 1 ); + +}; + +THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype ); + +THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { + + var animation = { + + startFrame: start, + endFrame: end, + + length: end - start + 1, + + fps: fps, + duration: ( end - start ) / fps, + + lastFrame: 0, + currentFrame: 0, + + active: false, + + time: 0, + direction: 1, + weight: 1, + + directionBackwards: false, + mirroredLoop: false + + }; + + this.animationsMap[ name ] = animation; + this.animationsList.push( animation ); + +}; + +THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { + + var pattern = /([a-z]+)_?(\d+)/; + + var firstAnimation, frameRanges = {}; + + var geometry = this.geometry; + + for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { + + var morph = geometry.morphTargets[ i ]; + var chunks = morph.name.match( pattern ); + + if ( chunks && chunks.length > 1 ) { + + var name = chunks[ 1 ]; + var num = chunks[ 2 ]; + + if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity }; + + var range = frameRanges[ name ]; + + if ( i < range.start ) range.start = i; + if ( i > range.end ) range.end = i; + + if ( ! firstAnimation ) firstAnimation = name; + + } + + } + + for ( var name in frameRanges ) { + + var range = frameRanges[ name ]; + this.createAnimation( name, range.start, range.end, fps ); + + } + + this.firstAnimation = firstAnimation; + +}; + +THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.direction = 1; + animation.directionBackwards = false; + + } + +}; + +THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.direction = - 1; + animation.directionBackwards = true; + + } + +}; + +THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.fps = fps; + animation.duration = ( animation.end - animation.start ) / animation.fps; + + } + +}; + +THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.duration = duration; + animation.fps = ( animation.end - animation.start ) / animation.duration; + + } + +}; - var key = edge.toString(); +THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { - if ( hash[ key ] === undefined ) { + var animation = this.animationsMap[ name ]; - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; + if ( animation ) { - } + animation.weight = weight; - } + } - } +}; - } +THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { - geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) ); + var animation = this.animationsMap[ name ]; - var coords = geometry.attributes.position.array; + if ( animation ) { - for ( var i = 0, l = numEdges; i < l; i ++ ) { + animation.time = time; - for ( var j = 0; j < 2; j ++ ) { + } - var index = 6 * i + 3 * j; - var index2 = 3 * edges[ 2 * i + j]; - coords[ index + 0 ] = vertices[ index2 ]; - coords[ index + 1 ] = vertices[ index2 + 1 ]; - coords[ index + 2 ] = vertices[ index2 + 2 ]; +}; - } +THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) { - } + var time = 0; - } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry + var animation = this.animationsMap[ name ]; - var vertices = object.geometry.attributes.position.array; - var numEdges = vertices.length / 3; - var numTris = numEdges / 3; + if ( animation ) { - geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) ); + time = animation.time; - var coords = geometry.attributes.position.array; + } - for ( var i = 0, l = numTris; i < l; i ++ ) { + return time; - for ( var j = 0; j < 3; j ++ ) { +}; - var index = 18 * i + 6 * j; +THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { - var index1 = 9 * i + 3 * j; - coords[ index + 0 ] = vertices[ index1 ]; - coords[ index + 1 ] = vertices[ index1 + 1 ]; - coords[ index + 2 ] = vertices[ index1 + 2 ]; + var duration = - 1; - var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 ); - coords[ index + 3 ] = vertices[ index2 ]; - coords[ index + 4 ] = vertices[ index2 + 1 ]; - coords[ index + 5 ] = vertices[ index2 + 2 ]; + var animation = this.animationsMap[ name ]; - } + if ( animation ) { - } + duration = animation.duration; } - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces ); - - this.matrixAutoUpdate = false; - this.matrixWorld = object.matrixWorld; + return duration; }; -THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype ); - -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.ImmediateRenderObject = function () { +THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) { - THREE.Object3D.call( this ); + var animation = this.animationsMap[ name ]; - this.render = function ( renderCallback ) { }; + if ( animation ) { -}; + animation.time = 0; + animation.active = true; -THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype ); + } else { -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + console.warn( "animation[" + name + "] undefined" ); -THREE.LensFlare = function ( texture, size, distance, blending, color ) { + } - THREE.Object3D.call( this ); +}; - this.lensFlares = []; +THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) { - this.positionScreen = new THREE.Vector3(); - this.customUpdateCallback = undefined; + var animation = this.animationsMap[ name ]; - if( texture !== undefined ) { + if ( animation ) { - this.add( texture, size, distance, blending, color ); + animation.active = false; } }; -THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype ); +THREE.MorphBlendMesh.prototype.update = function ( delta ) { + for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { -/* - * Add: adds another flare - */ + var animation = this.animationsList[ i ]; -THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) { + if ( ! animation.active ) continue; - if( size === undefined ) size = -1; - if( distance === undefined ) distance = 0; - if( opacity === undefined ) opacity = 1; - if( color === undefined ) color = new THREE.Color( 0xffffff ); - if( blending === undefined ) blending = THREE.NormalBlending; + var frameTime = animation.duration / animation.length; - distance = Math.min( distance, Math.max( 0, distance ) ); + animation.time += animation.direction * delta; - this.lensFlares.push( { texture: texture, // THREE.Texture - size: size, // size in pixels (-1 = use texture.width) - distance: distance, // distance (0-1) from light source (0=at light source) - x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back - scale: 1, // scale - rotation: 1, // rotation - opacity: opacity, // opacity - color: color, // color - blending: blending } ); // blending + if ( animation.mirroredLoop ) { -}; + if ( animation.time > animation.duration || animation.time < 0 ) { + animation.direction *= - 1; -/* - * Update lens flares update positions on all flares based on the screen position - * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way. - */ + if ( animation.time > animation.duration ) { -THREE.LensFlare.prototype.updateLensFlares = function () { + animation.time = animation.duration; + animation.directionBackwards = true; - var f, fl = this.lensFlares.length; - var flare; - var vecX = -this.positionScreen.x * 2; - var vecY = -this.positionScreen.y * 2; + } - for( f = 0; f < fl; f ++ ) { + if ( animation.time < 0 ) { - flare = this.lensFlares[ f ]; + animation.time = 0; + animation.directionBackwards = false; - flare.x = this.positionScreen.x + vecX * flare.distance; - flare.y = this.positionScreen.y + vecY * flare.distance; + } - flare.wantedRotation = flare.x * Math.PI * 0.25; - flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; + } - } + } else { -}; + animation.time = animation.time % animation.duration; + if ( animation.time < 0 ) animation.time += animation.duration; + } + + var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); + var weight = animation.weight; + if ( keyframe !== animation.currentFrame ) { + this.morphTargetInfluences[ animation.lastFrame ] = 0; + this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; + this.morphTargetInfluences[ keyframe ] = 0; + animation.lastFrame = animation.currentFrame; + animation.currentFrame = keyframe; + } + var mix = ( animation.time % frameTime ) / frameTime; + if ( animation.directionBackwards ) mix = 1 - mix; + this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; + this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; + } +}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.MorphBlendMesh = function( geometry, material ) { - - THREE.Mesh.call( this, geometry, material ); - - this.animationsMap = {}; - this.animationsList = []; - - // prepare default animation - // (all frames played together in 1 second) - - var numFrames = this.geometry.morphTargets.length; - - var name = "__default"; - - var startFrame = 0; - var endFrame = numFrames - 1; - - var fps = numFrames / 1; - - this.createAnimation( name, startFrame, endFrame, fps ); - this.setAnimationWeight( name, 1 ); - -}; - -THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype ); - -THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { - - var animation = { - - startFrame: start, - endFrame: end, - - length: end - start + 1, - - fps: fps, - duration: ( end - start ) / fps, - - lastFrame: 0, - currentFrame: 0, - - active: false, - - time: 0, - direction: 1, - weight: 1, - - directionBackwards: false, - mirroredLoop: false - - }; - - this.animationsMap[ name ] = animation; - this.animationsList.push( animation ); - -}; - -THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { - - var pattern = /([a-z]+)(\d+)/; - - var firstAnimation, frameRanges = {}; - - var geometry = this.geometry; - - for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { - - var morph = geometry.morphTargets[ i ]; - var chunks = morph.name.match( pattern ); - - if ( chunks && chunks.length > 1 ) { - - var name = chunks[ 1 ]; - var num = chunks[ 2 ]; - - if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity }; - - var range = frameRanges[ name ]; - - if ( i < range.start ) range.start = i; - if ( i > range.end ) range.end = i; - - if ( ! firstAnimation ) firstAnimation = name; - - } - - } - - for ( var name in frameRanges ) { - - var range = frameRanges[ name ]; - this.createAnimation( name, range.start, range.end, fps ); - - } - - this.firstAnimation = firstAnimation; - -}; - -THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.direction = 1; - animation.directionBackwards = false; - - } - -}; - -THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.direction = -1; - animation.directionBackwards = true; - - } - -}; - -THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.fps = fps; - animation.duration = ( animation.end - animation.start ) / animation.fps; - - } - -}; - -THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.duration = duration; - animation.fps = ( animation.end - animation.start ) / animation.duration; - - } - -}; - -THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.weight = weight; - - } - -}; - -THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.time = time; - - } - -}; - -THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) { - - var time = 0; - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - time = animation.time; - - } - - return time; - -}; - -THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { - - var duration = -1; - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - duration = animation.duration; - - } - - return duration; - -}; - -THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.time = 0; - animation.active = true; - - } else { - - console.warn( "animation[" + name + "] undefined" ); - - } - -}; - -THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.active = false; - - } - -}; - -THREE.MorphBlendMesh.prototype.update = function ( delta ) { - - for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { - - var animation = this.animationsList[ i ]; - - if ( ! animation.active ) continue; - - var frameTime = animation.duration / animation.length; - - animation.time += animation.direction * delta; - - if ( animation.mirroredLoop ) { - - if ( animation.time > animation.duration || animation.time < 0 ) { - - animation.direction *= -1; - - if ( animation.time > animation.duration ) { - - animation.time = animation.duration; - animation.directionBackwards = true; - - } - - if ( animation.time < 0 ) { - - animation.time = 0; - animation.directionBackwards = false; - - } - - } - - } else { - - animation.time = animation.time % animation.duration; - - if ( animation.time < 0 ) animation.time += animation.duration; - - } - - var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); - var weight = animation.weight; - - if ( keyframe !== animation.currentFrame ) { - - this.morphTargetInfluences[ animation.lastFrame ] = 0; - this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; - - this.morphTargetInfluences[ keyframe ] = 0; - - animation.lastFrame = animation.currentFrame; - animation.currentFrame = keyframe; - - } - - var mix = ( animation.time % frameTime ) / frameTime; - - if ( animation.directionBackwards ) mix = 1 - mix; - - this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; - this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; - - } - -}; +// File:src/extras/renderers/plugins/LensFlarePlugin.js /** * @author mikael emtinger / http://gomo.se/ @@ -36945,6 +34265,8 @@ THREE.MorphBlendMesh.prototype.update = function ( delta ) { THREE.LensFlarePlugin = function () { + var flares = []; + var _gl, _renderer, _precision, _lensFlare = {}; this.init = function ( renderer ) { @@ -36958,21 +34280,21 @@ THREE.LensFlarePlugin = function () { _lensFlare.faces = new Uint16Array( 6 ); var i = 0; - _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex - _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc. + _lensFlare.vertices[ i ++ ] = - 1; _lensFlare.vertices[ i ++ ] = - 1; // vertex + _lensFlare.vertices[ i ++ ] = 0; _lensFlare.vertices[ i ++ ] = 0; // uv... etc. - _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1; - _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0; + _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = - 1; + _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = 0; - _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1; - _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1; + _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = 1; + _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = 1; - _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1; - _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1; + _lensFlare.vertices[ i ++ ] = - 1; _lensFlare.vertices[ i ++ ] = 1; + _lensFlare.vertices[ i ++ ] = 0; _lensFlare.vertices[ i ++ ] = 1; i = 0; - _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2; - _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3; + _lensFlare.faces[ i ++ ] = 0; _lensFlare.faces[ i ++ ] = 1; _lensFlare.faces[ i ++ ] = 2; + _lensFlare.faces[ i ++ ] = 0; _lensFlare.faces[ i ++ ] = 2; _lensFlare.faces[ i ++ ] = 3; // buffers @@ -37045,10 +34367,19 @@ THREE.LensFlarePlugin = function () { this.render = function ( scene, camera, viewportWidth, viewportHeight ) { - var flares = scene.__webglFlares, - nFlares = flares.length; + flares.length = 0; + + scene.traverseVisible( function ( child ) { + + if ( child instanceof THREE.LensFlare ) { + + flares.push( child ); + + } + + } ); - if ( ! nFlares ) return; + if ( flares.length === 0 ) return; var tempPosition = new THREE.Vector3(); @@ -37087,17 +34418,15 @@ THREE.LensFlarePlugin = function () { _gl.disable( _gl.CULL_FACE ); _gl.depthMask( false ); - var i, j, jl, flare, sprite; - - for ( i = 0; i < nFlares; i ++ ) { + for ( var i = 0, l = flares.length; i < l; i ++ ) { size = 16 / viewportHeight; scale.set( size * invAspect, size ); // calc object screen position - flare = flares[ i ]; - + var flare = flares[ i ]; + tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] ); tempPosition.applyMatrix4( camera.matrixWorldInverse ); @@ -37173,9 +34502,9 @@ THREE.LensFlarePlugin = function () { _gl.uniform1i( uniforms.renderType, 2 ); _gl.enable( _gl.BLEND ); - for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { + for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { - sprite = flare.lensFlares[ j ]; + var sprite = flare.lensFlares[ j ]; if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { @@ -37242,6 +34571,8 @@ THREE.LensFlarePlugin = function () { }; +// File:src/extras/renderers/plugins/ShadowMapPlugin.js + /** * @author alteredq / http://alteredqualia.com/ */ @@ -37258,7 +34589,9 @@ THREE.ShadowMapPlugin = function () { _min = new THREE.Vector3(), _max = new THREE.Vector3(), - _matrixPosition = new THREE.Vector3(); + _matrixPosition = new THREE.Vector3(), + + _renderList = []; this.init = function ( renderer ) { @@ -37295,7 +34628,6 @@ THREE.ShadowMapPlugin = function () { shadowMap, shadowMatrix, shadowCamera, program, buffer, material, webglObject, object, light, - renderList, lights = [], k = 0, @@ -37474,85 +34806,62 @@ THREE.ShadowMapPlugin = function () { // set object matrices & frustum culling - renderList = scene.__webglObjects; - - for ( j = 0, jl = renderList.length; j < jl; j ++ ) { - - webglObject = renderList[ j ]; - object = webglObject.object; - - webglObject.render = false; - - if ( object.visible && object.castShadow ) { - - if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) { + _renderList.length = 0; + projectObject(scene,scene,shadowCamera); - object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); - - webglObject.render = true; - - } - - } - - } // render regular objects var objectMaterial, useMorphing, useSkinning; - for ( j = 0, jl = renderList.length; j < jl; j ++ ) { - - webglObject = renderList[ j ]; - - if ( webglObject.render ) { + for ( j = 0, jl = _renderList.length; j < jl; j ++ ) { - object = webglObject.object; - buffer = webglObject.buffer; + webglObject = _renderList[ j ]; - // culling is overriden globally for all objects - // while rendering depth map + object = webglObject.object; + buffer = webglObject.buffer; - // need to deal with MeshFaceMaterial somehow - // in that case just use the first of material.materials for now - // (proper solution would require to break objects by materials - // similarly to regular rendering and then set corresponding - // depth materials per each chunk instead of just once per object) + // culling is overriden globally for all objects + // while rendering depth map - objectMaterial = getObjectMaterial( object ); + // need to deal with MeshFaceMaterial somehow + // in that case just use the first of material.materials for now + // (proper solution would require to break objects by materials + // similarly to regular rendering and then set corresponding + // depth materials per each chunk instead of just once per object) - useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets; - useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning; + objectMaterial = getObjectMaterial( object ); - if ( object.customDepthMaterial ) { + useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets; + useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning; - material = object.customDepthMaterial; + if ( object.customDepthMaterial ) { - } else if ( useSkinning ) { + material = object.customDepthMaterial; - material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin; + } else if ( useSkinning ) { - } else if ( useMorphing ) { + material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin; - material = _depthMaterialMorph; + } else if ( useMorphing ) { - } else { + material = _depthMaterialMorph; - material = _depthMaterial; + } else { - } + material = _depthMaterial; - _renderer.setMaterialFaces( objectMaterial ); + } - if ( buffer instanceof THREE.BufferGeometry ) { + _renderer.setMaterialFaces( objectMaterial ); - _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object ); + if ( buffer instanceof THREE.BufferGeometry ) { - } else { + _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object ); - _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object ); + } else { - } + _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object ); } @@ -37560,7 +34869,7 @@ THREE.ShadowMapPlugin = function () { // set matrices and render immediate objects - renderList = scene.__webglObjectsImmediate; + var renderList = scene.__webglObjectsImmediate; for ( j = 0, jl = renderList.length; j < jl; j ++ ) { @@ -37594,6 +34903,33 @@ THREE.ShadowMapPlugin = function () { } }; + + function projectObject(scene, object,shadowCamera){ + + if ( object.visible ) { + + var webglObjects = scene.__webglObjects[object.id]; + + if (webglObjects && object.castShadow && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) { + + + for (var i = 0, l = webglObjects.length; i < l; i++){ + + var webglObject = webglObjects[i]; + + object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + _renderList.push(webglObject); + + } + } + + for(var i = 0, l = object.children.length; i < l; i++) { + + projectObject(scene, object.children[i],shadowCamera); + } + + } + } function createVirtualLight( light, cascade ) { @@ -37636,14 +34972,14 @@ THREE.ShadowMapPlugin = function () { var nearZ = light.shadowCascadeNearZ[ cascade ]; var farZ = light.shadowCascadeFarZ[ cascade ]; - pointsFrustum[ 0 ].set( -1, -1, nearZ ); - pointsFrustum[ 1 ].set( 1, -1, nearZ ); - pointsFrustum[ 2 ].set( -1, 1, nearZ ); + pointsFrustum[ 0 ].set( - 1, - 1, nearZ ); + pointsFrustum[ 1 ].set( 1, - 1, nearZ ); + pointsFrustum[ 2 ].set( - 1, 1, nearZ ); pointsFrustum[ 3 ].set( 1, 1, nearZ ); - pointsFrustum[ 4 ].set( -1, -1, farZ ); - pointsFrustum[ 5 ].set( 1, -1, farZ ); - pointsFrustum[ 6 ].set( -1, 1, farZ ); + pointsFrustum[ 4 ].set( - 1, - 1, farZ ); + pointsFrustum[ 5 ].set( 1, - 1, farZ ); + pointsFrustum[ 6 ].set( - 1, 1, farZ ); pointsFrustum[ 7 ].set( 1, 1, farZ ); return virtualLight; @@ -37691,7 +35027,7 @@ THREE.ShadowMapPlugin = function () { pointsWorld = light.pointsWorld; _min.set( Infinity, Infinity, Infinity ); - _max.set( -Infinity, -Infinity, -Infinity ); + _max.set( - Infinity, - Infinity, - Infinity ); for ( var i = 0; i < 8; i ++ ) { @@ -37741,6 +35077,8 @@ THREE.ShadowMapPlugin = function () { THREE.ShadowMapPlugin.__projector = new THREE.Projector(); +// File:src/extras/renderers/plugins/SpritePlugin.js + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ @@ -37750,6 +35088,8 @@ THREE.SpritePlugin = function () { var _gl, _renderer, _texture; + var sprites = []; + var vertices, faces, vertexBuffer, elementBuffer; var program, attributes, uniforms; @@ -37808,14 +35148,14 @@ THREE.SpritePlugin = function () { alphaTest: _gl.getUniformLocation( program, 'alphaTest' ) }; - + var canvas = document.createElement( 'canvas' ); canvas.width = 8; canvas.height = 8; - + var context = canvas.getContext( '2d' ); - context.fillStyle = '#ffffff'; - context.fillRect( 0, 0, canvas.width, canvas.height ); + context.fillStyle = 'white'; + context.fillRect( 0, 0, 8, 8 ); _texture = new THREE.Texture( canvas ); _texture.needsUpdate = true; @@ -37824,10 +35164,19 @@ THREE.SpritePlugin = function () { this.render = function ( scene, camera, viewportWidth, viewportHeight ) { - var sprites = scene.__webglSprites, - nSprites = sprites.length; + sprites.length = 0; + + scene.traverseVisible( function ( child ) { - if ( ! nSprites ) return; + if ( child instanceof THREE.Sprite ) { + + sprites.push( child ); + + } + + } ); + + if ( sprites.length === 0 ) return; // setup gl @@ -37888,14 +35237,10 @@ THREE.SpritePlugin = function () { // update positions and sort - var i, sprite, material, fogType, scale = []; - - for( i = 0; i < nSprites; i ++ ) { - - sprite = sprites[ i ]; - material = sprite.material; + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - if ( sprite.visible === false ) continue; + var sprite = sprites[ i ]; + var material = sprite.material; sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); sprite.z = - sprite._modelViewMatrix.elements[ 14 ]; @@ -37906,13 +35251,12 @@ THREE.SpritePlugin = function () { // render all sprites - for( i = 0; i < nSprites; i ++ ) { + var scale = []; - sprite = sprites[ i ]; + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - if ( sprite.visible === false ) continue; - - material = sprite.material; + var sprite = sprites[ i ]; + var material = sprite.material; _gl.uniform1f( uniforms.alphaTest, material.alphaTest ); _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements ); @@ -37920,14 +35264,12 @@ THREE.SpritePlugin = function () { scale[ 0 ] = sprite.scale.x; scale[ 1 ] = sprite.scale.y; + var fogType = 0; + if ( scene.fog && material.fog ) { fogType = sceneFogType; - } else { - - fogType = 0; - } if ( oldFogType !== fogType ) { @@ -38102,6 +35444,8 @@ THREE.SpritePlugin = function () { }; +// File:src/extras/renderers/plugins/DepthPassPlugin.js + /** * @author alteredq / http://alteredqualia.com/ */ @@ -38116,7 +35460,8 @@ THREE.DepthPassPlugin = function () { _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin, _frustum = new THREE.Frustum(), - _projScreenMatrix = new THREE.Matrix4(); + _projScreenMatrix = new THREE.Matrix4(), + _renderList = []; this.init = function ( renderer ) { @@ -38180,84 +35525,61 @@ THREE.DepthPassPlugin = function () { _renderer.clear(); // set object matrices & frustum culling - - renderList = scene.__webglObjects; - - for ( j = 0, jl = renderList.length; j < jl; j ++ ) { - - webglObject = renderList[ j ]; - object = webglObject.object; - - webglObject.render = false; - - if ( object.visible ) { - - if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) { - - object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - - webglObject.render = true; - - } - - } - - } + + _renderList.length = 0; + projectObject(scene,scene,camera); // render regular objects var objectMaterial, useMorphing, useSkinning; - for ( j = 0, jl = renderList.length; j < jl; j ++ ) { - - webglObject = renderList[ j ]; - - if ( webglObject.render ) { + for ( j = 0, jl = _renderList.length; j < jl; j ++ ) { - object = webglObject.object; - buffer = webglObject.buffer; + webglObject = _renderList[ j ]; - // todo: create proper depth material for particles + object = webglObject.object; + buffer = webglObject.buffer; - if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue; + // todo: create proper depth material for particles - objectMaterial = getObjectMaterial( object ); + if ( object instanceof THREE.PointCloud && ! object.customDepthMaterial ) continue; - if ( objectMaterial ) _renderer.setMaterialFaces( object.material ); + objectMaterial = getObjectMaterial( object ); - useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets; - useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning; + if ( objectMaterial ) _renderer.setMaterialFaces( object.material ); - if ( object.customDepthMaterial ) { + useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets; + useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning; - material = object.customDepthMaterial; + if ( object.customDepthMaterial ) { - } else if ( useSkinning ) { + material = object.customDepthMaterial; - material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin; + } else if ( useSkinning ) { - } else if ( useMorphing ) { + material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin; - material = _depthMaterialMorph; + } else if ( useMorphing ) { - } else { + material = _depthMaterialMorph; - material = _depthMaterial; + } else { - } + material = _depthMaterial; - if ( buffer instanceof THREE.BufferGeometry ) { + } - _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object ); + if ( buffer instanceof THREE.BufferGeometry ) { - } else { + _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object ); - _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object ); + } else { - } + _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object ); } + } // set matrices and render immediate objects @@ -38288,6 +35610,33 @@ THREE.DepthPassPlugin = function () { _gl.enable( _gl.BLEND ); }; + + function projectObject(scene, object,camera){ + + if ( object.visible ) { + + var webglObjects = scene.__webglObjects[object.id]; + + if (webglObjects && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) { + + + for (var i = 0, l = webglObjects.length; i < l; i++){ + + var webglObject = webglObjects[i]; + + object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + _renderList.push(webglObject); + + } + } + + for(var i = 0, l = object.children.length; i < l; i++) { + + projectObject(scene, object.children[i], camera); + } + + } + } // For the moment just ignore objects that have multiple materials with different animation methods // Only the first material will be taken into account for deciding which depth material to use @@ -38303,6 +35652,8 @@ THREE.DepthPassPlugin = function () { }; +// File:src/extras/shaders/ShaderFlares.js + /** * @author mikael emtinger / http://gomo.se/ */ From 1948d15743572da7a8456cb7c405819ceccab7ad Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Sun, 12 Oct 2014 14:04:24 -0400 Subject: [PATCH 45/50] Implemented pluggable target node types #60 --- effects/seriously.blend.js | 1 + seriously.js | 282 ++++++++++++++++++++++++++----------- 2 files changed, 202 insertions(+), 81 deletions(-) diff --git a/effects/seriously.blend.js b/effects/seriously.blend.js index f0db0b8..d6ed228 100644 --- a/effects/seriously.blend.js +++ b/effects/seriously.blend.js @@ -83,6 +83,7 @@ nativeBlendModes = { normal: ['FUNC_ADD', 'SRC_ALPHA', 'ONE_MINUS_SRC_ALPHA', 'SRC_ALPHA', 'DST_ALPHA']/*, add: ['FUNC_ADD', 'SRC_ALPHA', 'ONE_MINUS_SRC_ALPHA', 'SRC_ALPHA', 'DST_ALPHA']*/ + //todo: multiply, screen }, identity = new Float32Array([ 1, 0, 0, 0, diff --git a/seriously.js b/seriously.js index 63076cf..cc699a8 100755 --- a/seriously.js +++ b/seriously.js @@ -36,6 +36,7 @@ seriousEffects = {}, seriousTransforms = {}, seriousSources = {}, + seriousTargets = {}, timeouts = [], allEffectsByHook = {}, allTransformsByHook = {}, @@ -44,6 +45,7 @@ image: [], video: [] }, + allTargetsByHook = {}, allTargets = window.WeakMap && new WeakMap(), identity, maxSeriouslyId = 0, @@ -1169,6 +1171,7 @@ if (!node.model) { node.model = rectangleModel; + node.shader = baseShader; } //todo: initialize frame buffer if not main canvas @@ -1604,8 +1607,8 @@ var i; if (!this.ready) { - this.emit('ready'); this.ready = true; + this.emit('ready'); if (this.targets) { for (i = 0; i < this.targets.length; i++) { this.targets[i].setReady(); @@ -1618,8 +1621,8 @@ var i; if (this.ready) { - this.emit('unready'); this.ready = false; + this.emit('unready'); if (this.targets) { for (i = 0; i < this.targets.length; i++) { this.targets[i].setUnready(); @@ -3484,22 +3487,9 @@ }, set: function (value) { if (!isNaN(value) && value >0 && me.width !== value) { - me.width = me.desiredWidth = value; - me.target.width = value; - me.uniforms.resolution[0] = value; - + me.width = value; + me.resize(); me.setTransformDirty(); - me.emit('resize'); - /* - if (this.source && this.source.resize) { - this.source.resize(value); - - //todo: for secondary webgl nodes, we need a new array - //if (this.pixels && this.pixels.length !== (this.width * this.height * 4)) { - // delete this.pixels; - //} - } - */ } } }, @@ -3511,23 +3501,9 @@ }, set: function (value) { if (!isNaN(value) && value >0 && me.height !== value) { - me.height = me.desiredHeight = value; - me.target.height = value; - me.uniforms.resolution[1] = value; - + me.height = value; + me.resize(); me.setTransformDirty(); - me.emit('resize'); - - /* - if (this.source && this.source.resize) { - this.source.resize(undefined, value); - - //for secondary webgl nodes, we need a new array - //if (this.pixels && this.pixels.length !== (this.width * this.height * 4)) { - // delete this.pixels; - //} - } - */ } } }, @@ -3607,38 +3583,76 @@ /* possible targets: canvas (2d or 3d), gl render buffer (must be same canvas) */ - TargetNode = function (target, options) { - var opts = options || {}, - flip = opts.flip === undefined ? true : opts.flip, - width = parseInt(opts.width, 10), - height = parseInt(opts.height, 10), + TargetNode = function (hook, target, options) { + var opts, + flip, + width, + height, + that = this, matchedType = false, i, element, elements, context, - debugContext = opts.debugContext, + debugContext, frameBuffer, targetList, - triedWebGl = false; + triedWebGl = false, + key; - Node.call(this, opts); + function targetPlugin(hook, target, options, force) { + var plugin = seriousTargets[hook]; + if (plugin.definition) { + plugin = plugin.definition.call(that, target, options, force); + if (!plugin) { + return null; + } + plugin = extend(extend({}, seriousTargets[hook]), plugin); + that.hook = key; + matchedType = true; + that.plugin = plugin; + that.compare = plugin.compare; + if (plugin.target) { + target = plugin.target; + } + if (plugin.gl && !that.gl) { + that.gl = plugin.gl; + if (!gl) { + attachContext(plugin.gl); + } + } + if (that.gl === gl) { + that.model = rectangleModel; + that.shader = baseShader; + } + } + return plugin; + } - this.renderToTexture = opts.renderToTexture; + function compareTarget(target) { + return that.target === target; + } - if (typeof target === 'string') { - elements = document.querySelectorAll(target); + Node.call(this); - for (i = 0; i < elements.length; i++) { - element = elements[i]; - if (element.tagName === 'CANVAS') { - break; - } + if (hook && typeof hook !== 'string' || !target && target !== 0) { + if (!options || typeof options !== 'object') { + options = target; } + target = hook; + } - if (i >= elements.length) { - throw new Error('not a valid HTML element (must be image, video or canvas)'); - } + opts = options || {}; + flip = opts.flip === undefined ? true : opts.flip + width = parseInt(opts.width, 10); + height = parseInt(opts.height, 10); + debugContext = opts.debugContext; - target = element; - } else if (target instanceof WebGLFramebuffer) { + // forced target type? + if (typeof hook === 'string' && seriousTargets[hook]) { + targetPlugin(hook, target, opts, true); + } + + this.renderToTexture = opts.renderToTexture; + + if (target instanceof WebGLFramebuffer) { frameBuffer = target; if (opts instanceof HTMLCanvasElement) { @@ -3688,6 +3702,10 @@ attachContext(context); } this.render = this.renderWebGL; + + /* + Don't remember what this is for. Maybe we should remove it + */ if (opts.renderToTexture) { if (gl) { this.frameBuffer = new FrameBuffer(gl, width, height, false); @@ -3724,6 +3742,16 @@ matchedType = true; } + if (!matchedType) { + for (key in seriousTargets) { + if (seriousTargets.hasOwnProperty(key) && seriousTargets[key]) { + if (targetPlugin(key, target, opts, false)) { + break; + } + } + } + } + if (!matchedType) { throw new Error('Unknown target type'); } @@ -3749,8 +3777,12 @@ this.transform = null; this.transformDirty = true; this.flip = flip; - this.width = width; - this.height = height; + if (width) { + this.width = width; + } + if (height) { + this.height = height; + } this.uniforms.resolution[0] = this.width; this.uniforms.resolution[1] = this.height; @@ -3787,10 +3819,13 @@ this.source = newSource; newSource.addTarget(this); - if (newSource && newSource.ready) { - this.setReady(); - } else { - this.setUnready(); + if (newSource) { + this.resize(); + if (newSource.ready) { + this.setReady(); + } else { + this.setUnready(); + } } this.setDirty(); @@ -3807,14 +3842,17 @@ TargetNode.prototype.resize = function () { //if target is a canvas, reset size to canvas size - if (this.target instanceof HTMLCanvasElement && - (this.width !== this.target.width || this.height !== this.target.height)) { - this.width = this.target.width; - this.height = this.target.height; - this.uniforms.resolution[0] = this.width; - this.uniforms.resolution[1] = this.height; - this.emit('resize'); - this.setTransformDirty(); + if (this.target instanceof HTMLCanvasElement) { + if (this.width !== this.target.width || this.height !== this.target.height) { + this.target.width = this.width; + this.target.height = this.height; + this.uniforms.resolution[0] = this.width; + this.uniforms.resolution[1] = this.height; + this.emit('resize'); + this.setTransformDirty(); + } + } else if (this.plugin && this.plugin.resize) { + this.plugin.resize.call(this); } if (this.source && @@ -3839,6 +3877,12 @@ this.auto = false; }; + TargetNode.prototype.render = function () { + if (gl && this.plugin && this.plugin.render) { + this.plugin.render.call(this, draw, baseShader, rectangleModel); + } + }; + TargetNode.prototype.renderWebGL = function () { var matrix, x, y; @@ -3950,6 +3994,10 @@ } } + if (this.plugin && this.plugin.destroy) { + this.plugin.destroy.call(this); + } + delete this.source; delete this.target; delete this.pub; @@ -4710,26 +4758,38 @@ return transformNode.pub; }; - this.target = function (target, options) { + this.target = function (hook, target, options) { var targetNode, - renderToTexture, - targetRenderToTexture, + element, + hook, i; - /* - Returns existing target if duplicate texture or canvas is passed - */ - renderToTexture = !!(options && options.renderToTexture); + if (hook && typeof hook === 'string' && !seriousTargets[hook]) { + element = document.querySelector(hook); + } + + if (typeof hook !== 'string' || !target && target !== 0 || element) { + if (!options || typeof options !== 'object') { + options = target; + } + target = element || hook; + hook = null; + } + + if (typeof target === 'string' && isNaN(target)) { + target = document.querySelector(target); + } + for (i = 0; i < targets.length; i++) { - if (targets[i] === target || targets[i].target === target) { - targetRenderToTexture = !!targets[i].renderToTexture; - if (renderToTexture === targetRenderToTexture) { - return targets[i].pub; - } + targetNode = targets[i]; + if ((!hook || hook === targetNode.hook) && + (targetNode.target === target || targetNode.compare && targetNode.compare(target, options))) { + + return targetNode.pub; } } - targetNode = new TargetNode(target, options); + targetNode = new TargetNode(hook, target, options); return targetNode.pub; }; @@ -5216,6 +5276,66 @@ return this; }; + Seriously.target = function (hook, definition, meta) { + var target; + + if (seriousTargets[hook]) { + Seriously.logger.warn('Target [' + hook + '] already loaded'); + return; + } + + if (meta === undefined && typeof definition === 'object') { + meta = definition; + } + + if (!meta && !definition) { + return; + } + + target = extend({}, meta); + + if (typeof definition === 'function') { + target.definition = definition; + } + + if (!target.title) { + target.title = hook; + } + + + seriousTargets[hook] = target; + allTargetsByHook[hook] = []; + + return target; + }; + + Seriously.removeTarget = function (hook) { + var all, target, plugin; + + if (!hook) { + return this; + } + + plugin = seriousTargets[hook]; + + if (!plugin) { + return this; + } + + all = allTargetsByHook[hook]; + if (all) { + while (all.length) { + target = all.shift(); + target.destroy(); + } + delete allTargetsByHook[hook]; + } + + delete seriousTargets[hook]; + + return this; + }; + //todo: validators should not allocate new objects/arrays if input is valid Seriously.inputValidators = { color: function (value, input, defaultValue, oldValue) { From b1e5ca01d2c2148356e761278401926380818a52 Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Sun, 12 Oct 2014 14:07:48 -0400 Subject: [PATCH 46/50] Target plugin for Three.js texture #61 --- .../{threejs.html => threejs-source.html} | 2 +- examples/demo/threejs-target.html | 273 ++++++++++++++++++ examples/index.html | 3 +- examples/target/multi-target.html | 6 +- sources/seriously.three.js | 2 +- targets/seriously.three.js | 169 +++++++++++ 6 files changed, 449 insertions(+), 6 deletions(-) rename examples/demo/{threejs.html => threejs-source.html} (99%) create mode 100644 examples/demo/threejs-target.html create mode 100644 targets/seriously.three.js diff --git a/examples/demo/threejs.html b/examples/demo/threejs-source.html similarity index 99% rename from examples/demo/threejs.html rename to examples/demo/threejs-source.html index c303916..e6bd889 100644 --- a/examples/demo/threejs.html +++ b/examples/demo/threejs-source.html @@ -131,7 +131,7 @@ // resize 3D scene camera.aspect = aspect; camera.updateProjectionMatrix(); - renderer.setSize(outputWidth / devicePixelRatio, outputWidth / devicePixelRatio); + renderer.setSize(outputWidth / devicePixelRatio, outputHeight / devicePixelRatio); /* Three.js likes to force our canvas to be a certain size, diff --git a/examples/demo/threejs-target.html b/examples/demo/threejs-target.html new file mode 100644 index 0000000..026534c --- /dev/null +++ b/examples/demo/threejs-target.html @@ -0,0 +1,273 @@ + + + + Seriously.js Three.js Target Example + + + + + + + + + + + + + + + + + + + diff --git a/examples/index.html b/examples/index.html index bc8dbe2..2d942b2 100644 --- a/examples/index.html +++ b/examples/index.html @@ -33,7 +33,8 @@
  • Drunk
  • Fog
  • Panorama
  • -
  • Three.js
  • +
  • Three.js Source
  • +
  • Three.js Target
  • Mirror (Camera)
  • Transforms
      diff --git a/examples/target/multi-target.html b/examples/target/multi-target.html index d4e37ee..6886942 100644 --- a/examples/target/multi-target.html +++ b/examples/target/multi-target.html @@ -28,10 +28,10 @@ ], split1, split2, - target; // a wrapper object for our target canvas + mainTarget; // a wrapper object for our target canvas //create main WebGL canvas first! - target = seriously.target('#main'); + mainTarget = seriously.target('#main'); effects[2].saturation = -1; @@ -67,7 +67,7 @@ split2.split = 2 / 3; split2.angle = Math.PI / 16; - target.source = split2; + mainTarget.source = split2; seriously.go(); }()); diff --git a/sources/seriously.three.js b/sources/seriously.three.js index d75303f..8a5b031 100644 --- a/sources/seriously.three.js +++ b/sources/seriously.three.js @@ -81,6 +81,6 @@ }; } }, { - title: 'Three.js WebGLRenderTarget' + title: 'Three.js WebGLRenderTarget Source' }); })); \ No newline at end of file diff --git a/targets/seriously.three.js b/targets/seriously.three.js new file mode 100644 index 0000000..813eccb --- /dev/null +++ b/targets/seriously.three.js @@ -0,0 +1,169 @@ +/* global define, require */ +(function (root, factory) { + 'use strict'; + + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['seriously', 'three'], factory); + } else if (typeof exports === 'object') { + // Node/CommonJS + factory(require('seriously'), require('three')); + } else { + /* + todo: build out-of-order loading for sources and transforms or remove this + if (!root.Seriously) { + root.Seriously = { plugin: function (name, opt) { this[name] = opt; } }; + } + */ + factory(root.Seriously, root.THREE); + } +}(this, function (Seriously, THREE) { + 'use strict'; + + /* + There is currently no way to resize a THREE.WebGLRenderTarget, + so we won't allow resizing of this kind of target node until that gets fixed + */ + + var identity = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]), + mat4 = Seriously.util.mat4; + + Seriously.target('three', function (target, options, force) { + var me = this, + gl, + frameBuffer; + + function initialize() { + if (!frameBuffer || !gl || me.initialized) { + // not ready yet + return; + } + + me.initialized = true; + me.allowRefresh = true; + me.setReady(); + } + + if (THREE && target instanceof THREE.WebGLRenderTarget) { + /* + if not passed a canvas or gl by options and we don't have one already, + throw an error + */ + if (me.gl) { + gl = me.gl; + } else if (options) { + if (options.gl) { + gl = options.gl; + } else if (options.canvas) { + try { + gl = canvas.getContext('webgl'); + } catch (expError) { + } + + if (!gl) { + try { + gl = canvas.getContext('experimental-webgl'); + } catch (error) { + } + } + } + } + + if (!gl) { + throw new Error('Failed to create Three.js target. Missing WebGL context'); + } + + this.ready = false; + this.width = target.width; + this.height = target.height; + + if (target.__webglFramebuffer) { + if (!gl.isFramebuffer(target.__webglFramebuffer)) { + throw new Error('Failed to create Three.js target. WebGL texture is from a different context'); + } + frameBuffer = target.__webglFramebuffer; + initialize(); + } else { + Object.defineProperty(target, '__webglFramebuffer', { + configurable: true, + enumerable: true, + get: function () { + return frameBuffer; + }, + set: function (fb) { + if (fb) { + frameBuffer = fb; + initialize(); + } + } + }); + } + + this.setReady = function () { + if (frameBuffer && this.source && this.source.ready && !this.ready) { + this.emit('ready'); + this.ready = true; + } + }; + + this.target = target; + + return { + gl: gl, + resize: function () { + this.width = target.width; + this.height = target.height; + }, + render: function (draw, shader, model) { + var matrix, x, y; + if (gl && this.dirty && this.ready && this.source) { + + this.source.render(); + this.uniforms.source = this.source.texture; + + if (this.source.width === this.width && this.source.height === this.height) { + this.uniforms.transform = this.source.cumulativeMatrix || identity; + } else if (this.transformDirty) { + matrix = this.transform; + mat4.copy(matrix, this.source.cumulativeMatrix || identity); + x = this.source.width / this.width; + y = this.source.height / this.height; + matrix[0] *= x; + matrix[1] *= x; + matrix[2] *= x; + matrix[3] *= x; + matrix[4] *= y; + matrix[5] *= y; + matrix[6] *= y; + matrix[7] *= y; + this.uniforms.transform = matrix; + this.transformDirty = false; + } + + draw(shader, model, this.uniforms, frameBuffer, this); + + this.emit('render'); + this.dirty = false; + if (target.onUpdate) { + target.onUpdate(); + } + } + }, + destroy: function () { + Object.defineProperty(target, '__webglFramebuffer', { + configurable: true, + enumerable: true, + value: frameBuffer + }); + } + }; + } + }, { + title: 'THREE.js WebGLRenderTarget Target' + }); +})); \ No newline at end of file From bd5dbf264fe3077ee71023049b66ff87985dad00 Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Sun, 12 Oct 2014 14:20:19 -0400 Subject: [PATCH 47/50] Clean up Three.js Target example code #61 --- examples/demo/threejs-target.html | 36 ++++++------------------------- 1 file changed, 6 insertions(+), 30 deletions(-) diff --git a/examples/demo/threejs-target.html b/examples/demo/threejs-target.html index 026534c..d62e22a 100644 --- a/examples/demo/threejs-target.html +++ b/examples/demo/threejs-target.html @@ -20,32 +20,6 @@ height: 100%; } - #controls { - position: absolute; - right: 0; - bottom: 0; - background-color: rgba(100, 100, 100, 0.6); - padding: 4px; - opacity: 0.5; - color: white; - } - - #controls:hover { - opacity: 1; - } - - .title { - opacity: 0.4; - position: absolute; - padding: 8px; - color: white; - background-color: black; - } - - #controls .rs-base { - position: static;; - } - @@ -177,7 +151,7 @@ object.position.set(200, 0, 0); scene.add(object); - var screen = new THREE.Mesh( + object = new THREE.Mesh( new THREE.PlaneGeometry(300, 300), new THREE.MeshLambertMaterial({ ambient: 0xffffff, @@ -185,8 +159,8 @@ side: THREE.DoubleSide }) ); - screen.position.set(-200, 0, 0); - scene.add(screen); + object.position.set(-200, 0, 0); + scene.add(object); renderer = new THREE.WebGLRenderer({ canvas: canvas @@ -201,6 +175,8 @@ // set up composition function initSeriouslyComps() { + var reformat; + seriously = new Seriously(); simplex = seriously.effect('simplex'); @@ -215,7 +191,7 @@ }); noiseTarget.source = simplex; - var reformat = seriously.transform('reformat'); + reformat = seriously.transform('reformat'); reformat.width = 512; reformat.height = 512; reformat.mode = 'distort'; From e98dea08d404cc5c59f852edf3986c8fe9a58b4c Mon Sep 17 00:00:00 2001 From: Brian Chirls Date: Sun, 12 Oct 2014 14:22:39 -0400 Subject: [PATCH 48/50] Remove some junk from Three.js Target example code #61 --- examples/demo/threejs-target.html | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/examples/demo/threejs-target.html b/examples/demo/threejs-target.html index d62e22a..788cda9 100644 --- a/examples/demo/threejs-target.html +++ b/examples/demo/threejs-target.html @@ -28,14 +28,10 @@ - - - - - +